Adding test for pragma key on attach
[sqlcipher.git] / sqlite3.c
bloba36fd5adddaab6eadcdfae30cfb9ac80d3a35e9a
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.8.0. 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
309 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
310 # define _BSD_SOURCE
311 #endif
314 ** Include standard header files as necessary
316 #ifdef HAVE_STDINT_H
317 #include <stdint.h>
318 #endif
319 #ifdef HAVE_INTTYPES_H
320 #include <inttypes.h>
321 #endif
324 ** The following macros are used to cast pointers to integers and
325 ** integers to pointers. The way you do this varies from one compiler
326 ** to the next, so we have developed the following set of #if statements
327 ** to generate appropriate macros for a wide range of compilers.
329 ** The correct "ANSI" way to do this is to use the intptr_t type.
330 ** Unfortunately, that typedef is not available on all compilers, or
331 ** if it is available, it requires an #include of specific headers
332 ** that vary from one machine to the next.
334 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
335 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
336 ** So we have to define the macros in different ways depending on the
337 ** compiler.
339 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
340 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
341 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
342 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
343 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
344 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
345 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
346 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
347 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
348 #else /* Generates a warning - but it always works */
349 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
350 # define SQLITE_PTR_TO_INT(X) ((int)(X))
351 #endif
354 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
355 ** 0 means mutexes are permanently disable and the library is never
356 ** threadsafe. 1 means the library is serialized which is the highest
357 ** level of threadsafety. 2 means the library is multithreaded - multiple
358 ** threads can use SQLite as long as no two threads try to use the same
359 ** database connection at the same time.
361 ** Older versions of SQLite used an optional THREADSAFE macro.
362 ** We support that for legacy.
364 #if !defined(SQLITE_THREADSAFE)
365 # if defined(THREADSAFE)
366 # define SQLITE_THREADSAFE THREADSAFE
367 # else
368 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
369 # endif
370 #endif
373 ** Powersafe overwrite is on by default. But can be turned off using
374 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
376 #ifndef SQLITE_POWERSAFE_OVERWRITE
377 # define SQLITE_POWERSAFE_OVERWRITE 1
378 #endif
381 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
382 ** It determines whether or not the features related to
383 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
384 ** be overridden at runtime using the sqlite3_config() API.
386 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
387 # define SQLITE_DEFAULT_MEMSTATUS 1
388 #endif
391 ** Exactly one of the following macros must be defined in order to
392 ** specify which memory allocation subsystem to use.
394 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
395 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
396 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
397 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
399 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
400 ** assert() macro is enabled, each call into the Win32 native heap subsystem
401 ** will cause HeapValidate to be called. If heap validation should fail, an
402 ** assertion will be triggered.
404 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
405 ** the default.
407 #if defined(SQLITE_SYSTEM_MALLOC) \
408 + defined(SQLITE_WIN32_MALLOC) \
409 + defined(SQLITE_ZERO_MALLOC) \
410 + defined(SQLITE_MEMDEBUG)>1
411 # error "Two or more of the following compile-time configuration options\
412 are defined but at most one is allowed:\
413 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
414 SQLITE_ZERO_MALLOC"
415 #endif
416 #if defined(SQLITE_SYSTEM_MALLOC) \
417 + defined(SQLITE_WIN32_MALLOC) \
418 + defined(SQLITE_ZERO_MALLOC) \
419 + defined(SQLITE_MEMDEBUG)==0
420 # define SQLITE_SYSTEM_MALLOC 1
421 #endif
424 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
425 ** sizes of memory allocations below this value where possible.
427 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
428 # define SQLITE_MALLOC_SOFT_LIMIT 1024
429 #endif
432 ** We need to define _XOPEN_SOURCE as follows in order to enable
433 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
434 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
435 ** it.
437 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
438 # define _XOPEN_SOURCE 600
439 #endif
442 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
443 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
444 ** make it true by defining or undefining NDEBUG.
446 ** Setting NDEBUG makes the code smaller and faster by disabling the
447 ** assert() statements in the code. So we want the default action
448 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
449 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
450 ** feature.
452 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
453 # define NDEBUG 1
454 #endif
455 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
456 # undef NDEBUG
457 #endif
460 ** The testcase() macro is used to aid in coverage testing. When
461 ** doing coverage testing, the condition inside the argument to
462 ** testcase() must be evaluated both true and false in order to
463 ** get full branch coverage. The testcase() macro is inserted
464 ** to help ensure adequate test coverage in places where simple
465 ** condition/decision coverage is inadequate. For example, testcase()
466 ** can be used to make sure boundary values are tested. For
467 ** bitmask tests, testcase() can be used to make sure each bit
468 ** is significant and used at least once. On switch statements
469 ** where multiple cases go to the same block of code, testcase()
470 ** can insure that all cases are evaluated.
473 #ifdef SQLITE_COVERAGE_TEST
474 SQLITE_PRIVATE void sqlite3Coverage(int);
475 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
476 #else
477 # define testcase(X)
478 #endif
481 ** The TESTONLY macro is used to enclose variable declarations or
482 ** other bits of code that are needed to support the arguments
483 ** within testcase() and assert() macros.
485 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
486 # define TESTONLY(X) X
487 #else
488 # define TESTONLY(X)
489 #endif
492 ** Sometimes we need a small amount of code such as a variable initialization
493 ** to setup for a later assert() statement. We do not want this code to
494 ** appear when assert() is disabled. The following macro is therefore
495 ** used to contain that setup code. The "VVA" acronym stands for
496 ** "Verification, Validation, and Accreditation". In other words, the
497 ** code within VVA_ONLY() will only run during verification processes.
499 #ifndef NDEBUG
500 # define VVA_ONLY(X) X
501 #else
502 # define VVA_ONLY(X)
503 #endif
506 ** The ALWAYS and NEVER macros surround boolean expressions which
507 ** are intended to always be true or false, respectively. Such
508 ** expressions could be omitted from the code completely. But they
509 ** are included in a few cases in order to enhance the resilience
510 ** of SQLite to unexpected behavior - to make the code "self-healing"
511 ** or "ductile" rather than being "brittle" and crashing at the first
512 ** hint of unplanned behavior.
514 ** In other words, ALWAYS and NEVER are added for defensive code.
516 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
517 ** be true and false so that the unreachable code they specify will
518 ** not be counted as untested code.
520 #if defined(SQLITE_COVERAGE_TEST)
521 # define ALWAYS(X) (1)
522 # define NEVER(X) (0)
523 #elif !defined(NDEBUG)
524 # define ALWAYS(X) ((X)?1:(assert(0),0))
525 # define NEVER(X) ((X)?(assert(0),1):0)
526 #else
527 # define ALWAYS(X) (X)
528 # define NEVER(X) (X)
529 #endif
532 ** Return true (non-zero) if the input is a integer that is too large
533 ** to fit in 32-bits. This macro is used inside of various testcase()
534 ** macros to verify that we have tested SQLite for large-file support.
536 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
539 ** The macro unlikely() is a hint that surrounds a boolean
540 ** expression that is usually false. Macro likely() surrounds
541 ** a boolean expression that is usually true. These hints could,
542 ** in theory, be used by the compiler to generate better code, but
543 ** currently they are just comments for human readers.
545 #define likely(X) (X)
546 #define unlikely(X) (X)
548 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
549 /************** Begin file sqlite3.h *****************************************/
551 ** 2001 September 15
553 ** The author disclaims copyright to this source code. In place of
554 ** a legal notice, here is a blessing:
556 ** May you do good and not evil.
557 ** May you find forgiveness for yourself and forgive others.
558 ** May you share freely, never taking more than you give.
560 *************************************************************************
561 ** This header file defines the interface that the SQLite library
562 ** presents to client programs. If a C-function, structure, datatype,
563 ** or constant definition does not appear in this file, then it is
564 ** not a published API of SQLite, is subject to change without
565 ** notice, and should not be referenced by programs that use SQLite.
567 ** Some of the definitions that are in this file are marked as
568 ** "experimental". Experimental interfaces are normally new
569 ** features recently added to SQLite. We do not anticipate changes
570 ** to experimental interfaces but reserve the right to make minor changes
571 ** if experience from use "in the wild" suggest such changes are prudent.
573 ** The official C-language API documentation for SQLite is derived
574 ** from comments in this file. This file is the authoritative source
575 ** on how SQLite interfaces are suppose to operate.
577 ** The name of this file under configuration management is "sqlite.h.in".
578 ** The makefile makes some minor changes to this file (such as inserting
579 ** the version number) and changes its name to "sqlite3.h" as
580 ** part of the build process.
582 #ifndef _SQLITE3_H_
583 #define _SQLITE3_H_
584 #include <stdarg.h> /* Needed for the definition of va_list */
587 ** Make sure we can call this stuff from C++.
589 #if 0
590 extern "C" {
591 #endif
595 ** Add the ability to override 'extern'
597 #ifndef SQLITE_EXTERN
598 # define SQLITE_EXTERN extern
599 #endif
601 #ifndef SQLITE_API
602 # define SQLITE_API
603 #endif
607 ** These no-op macros are used in front of interfaces to mark those
608 ** interfaces as either deprecated or experimental. New applications
609 ** should not use deprecated interfaces - they are support for backwards
610 ** compatibility only. Application writers should be aware that
611 ** experimental interfaces are subject to change in point releases.
613 ** These macros used to resolve to various kinds of compiler magic that
614 ** would generate warning messages when they were used. But that
615 ** compiler magic ended up generating such a flurry of bug reports
616 ** that we have taken it all out and gone back to using simple
617 ** noop macros.
619 #define SQLITE_DEPRECATED
620 #define SQLITE_EXPERIMENTAL
623 ** Ensure these symbols were not defined by some previous header file.
625 #ifdef SQLITE_VERSION
626 # undef SQLITE_VERSION
627 #endif
628 #ifdef SQLITE_VERSION_NUMBER
629 # undef SQLITE_VERSION_NUMBER
630 #endif
633 ** CAPI3REF: Compile-Time Library Version Numbers
635 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
636 ** evaluates to a string literal that is the SQLite version in the
637 ** format "X.Y.Z" where X is the major version number (always 3 for
638 ** SQLite3) and Y is the minor version number and Z is the release number.)^
639 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
640 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
641 ** numbers used in [SQLITE_VERSION].)^
642 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
643 ** be larger than the release from which it is derived. Either Y will
644 ** be held constant and Z will be incremented or else Y will be incremented
645 ** and Z will be reset to zero.
647 ** Since version 3.6.18, SQLite source code has been stored in the
648 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
649 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
650 ** a string which identifies a particular check-in of SQLite
651 ** within its configuration management system. ^The SQLITE_SOURCE_ID
652 ** string contains the date and time of the check-in (UTC) and an SHA1
653 ** hash of the entire source tree.
655 ** See also: [sqlite3_libversion()],
656 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
657 ** [sqlite_version()] and [sqlite_source_id()].
659 #define SQLITE_VERSION "3.8.0"
660 #define SQLITE_VERSION_NUMBER 3008000
661 #define SQLITE_SOURCE_ID "2013-08-26 04:50:08 f64cd21e2e23ed7cff48f7dafa5e76adde9321c2"
664 ** CAPI3REF: Run-Time Library Version Numbers
665 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
667 ** These interfaces provide the same information as the [SQLITE_VERSION],
668 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
669 ** but are associated with the library instead of the header file. ^(Cautious
670 ** programmers might include assert() statements in their application to
671 ** verify that values returned by these interfaces match the macros in
672 ** the header, and thus insure that the application is
673 ** compiled with matching library and header files.
675 ** <blockquote><pre>
676 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
677 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
678 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
679 ** </pre></blockquote>)^
681 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
682 ** macro. ^The sqlite3_libversion() function returns a pointer to the
683 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
684 ** function is provided for use in DLLs since DLL users usually do not have
685 ** direct access to string constants within the DLL. ^The
686 ** sqlite3_libversion_number() function returns an integer equal to
687 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
688 ** a pointer to a string constant whose value is the same as the
689 ** [SQLITE_SOURCE_ID] C preprocessor macro.
691 ** See also: [sqlite_version()] and [sqlite_source_id()].
693 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
694 SQLITE_API const char *sqlite3_libversion(void);
695 SQLITE_API const char *sqlite3_sourceid(void);
696 SQLITE_API int sqlite3_libversion_number(void);
699 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
701 ** ^The sqlite3_compileoption_used() function returns 0 or 1
702 ** indicating whether the specified option was defined at
703 ** compile time. ^The SQLITE_ prefix may be omitted from the
704 ** option name passed to sqlite3_compileoption_used().
706 ** ^The sqlite3_compileoption_get() function allows iterating
707 ** over the list of options that were defined at compile time by
708 ** returning the N-th compile time option string. ^If N is out of range,
709 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
710 ** prefix is omitted from any strings returned by
711 ** sqlite3_compileoption_get().
713 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
714 ** and sqlite3_compileoption_get() may be omitted by specifying the
715 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
717 ** See also: SQL functions [sqlite_compileoption_used()] and
718 ** [sqlite_compileoption_get()] and the [compile_options pragma].
720 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
721 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
722 SQLITE_API const char *sqlite3_compileoption_get(int N);
723 #endif
726 ** CAPI3REF: Test To See If The Library Is Threadsafe
728 ** ^The sqlite3_threadsafe() function returns zero if and only if
729 ** SQLite was compiled with mutexing code omitted due to the
730 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
732 ** SQLite can be compiled with or without mutexes. When
733 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
734 ** are enabled and SQLite is threadsafe. When the
735 ** [SQLITE_THREADSAFE] macro is 0,
736 ** the mutexes are omitted. Without the mutexes, it is not safe
737 ** to use SQLite concurrently from more than one thread.
739 ** Enabling mutexes incurs a measurable performance penalty.
740 ** So if speed is of utmost importance, it makes sense to disable
741 ** the mutexes. But for maximum safety, mutexes should be enabled.
742 ** ^The default behavior is for mutexes to be enabled.
744 ** This interface can be used by an application to make sure that the
745 ** version of SQLite that it is linking against was compiled with
746 ** the desired setting of the [SQLITE_THREADSAFE] macro.
748 ** This interface only reports on the compile-time mutex setting
749 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
750 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
751 ** can be fully or partially disabled using a call to [sqlite3_config()]
752 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
753 ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
754 ** sqlite3_threadsafe() function shows only the compile-time setting of
755 ** thread safety, not any run-time changes to that setting made by
756 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
757 ** is unchanged by calls to sqlite3_config().)^
759 ** See the [threading mode] documentation for additional information.
761 SQLITE_API int sqlite3_threadsafe(void);
764 ** CAPI3REF: Database Connection Handle
765 ** KEYWORDS: {database connection} {database connections}
767 ** Each open SQLite database is represented by a pointer to an instance of
768 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
769 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
770 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
771 ** and [sqlite3_close_v2()] are its destructors. There are many other
772 ** interfaces (such as
773 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
774 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
775 ** sqlite3 object.
777 typedef struct sqlite3 sqlite3;
780 ** CAPI3REF: 64-Bit Integer Types
781 ** KEYWORDS: sqlite_int64 sqlite_uint64
783 ** Because there is no cross-platform way to specify 64-bit integer types
784 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
786 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
787 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
788 ** compatibility only.
790 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
791 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
792 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
793 ** between 0 and +18446744073709551615 inclusive.
795 #ifdef SQLITE_INT64_TYPE
796 typedef SQLITE_INT64_TYPE sqlite_int64;
797 typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
798 #elif defined(_MSC_VER) || defined(__BORLANDC__)
799 typedef __int64 sqlite_int64;
800 typedef unsigned __int64 sqlite_uint64;
801 #else
802 typedef long long int sqlite_int64;
803 typedef unsigned long long int sqlite_uint64;
804 #endif
805 typedef sqlite_int64 sqlite3_int64;
806 typedef sqlite_uint64 sqlite3_uint64;
809 ** If compiling for a processor that lacks floating point support,
810 ** substitute integer for floating-point.
812 #ifdef SQLITE_OMIT_FLOATING_POINT
813 # define double sqlite3_int64
814 #endif
817 ** CAPI3REF: Closing A Database Connection
819 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
820 ** for the [sqlite3] object.
821 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
822 ** the [sqlite3] object is successfully destroyed and all associated
823 ** resources are deallocated.
825 ** ^If the database connection is associated with unfinalized prepared
826 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
827 ** will leave the database connection open and return [SQLITE_BUSY].
828 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
829 ** and unfinished sqlite3_backups, then the database connection becomes
830 ** an unusable "zombie" which will automatically be deallocated when the
831 ** last prepared statement is finalized or the last sqlite3_backup is
832 ** finished. The sqlite3_close_v2() interface is intended for use with
833 ** host languages that are garbage collected, and where the order in which
834 ** destructors are called is arbitrary.
836 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
837 ** [sqlite3_blob_close | close] all [BLOB handles], and
838 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
839 ** with the [sqlite3] object prior to attempting to close the object. ^If
840 ** sqlite3_close_v2() is called on a [database connection] that still has
841 ** outstanding [prepared statements], [BLOB handles], and/or
842 ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
843 ** of resources is deferred until all [prepared statements], [BLOB handles],
844 ** and [sqlite3_backup] objects are also destroyed.
846 ** ^If an [sqlite3] object is destroyed while a transaction is open,
847 ** the transaction is automatically rolled back.
849 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
850 ** must be either a NULL
851 ** pointer or an [sqlite3] object pointer obtained
852 ** from [sqlite3_open()], [sqlite3_open16()], or
853 ** [sqlite3_open_v2()], and not previously closed.
854 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
855 ** argument is a harmless no-op.
857 SQLITE_API int sqlite3_close(sqlite3*);
858 SQLITE_API int sqlite3_close_v2(sqlite3*);
861 ** The type for a callback function.
862 ** This is legacy and deprecated. It is included for historical
863 ** compatibility and is not documented.
865 typedef int (*sqlite3_callback)(void*,int,char**, char**);
868 ** CAPI3REF: One-Step Query Execution Interface
870 ** The sqlite3_exec() interface is a convenience wrapper around
871 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
872 ** that allows an application to run multiple statements of SQL
873 ** without having to use a lot of C code.
875 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
876 ** semicolon-separate SQL statements passed into its 2nd argument,
877 ** in the context of the [database connection] passed in as its 1st
878 ** argument. ^If the callback function of the 3rd argument to
879 ** sqlite3_exec() is not NULL, then it is invoked for each result row
880 ** coming out of the evaluated SQL statements. ^The 4th argument to
881 ** sqlite3_exec() is relayed through to the 1st argument of each
882 ** callback invocation. ^If the callback pointer to sqlite3_exec()
883 ** is NULL, then no callback is ever invoked and result rows are
884 ** ignored.
886 ** ^If an error occurs while evaluating the SQL statements passed into
887 ** sqlite3_exec(), then execution of the current statement stops and
888 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
889 ** is not NULL then any error message is written into memory obtained
890 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
891 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
892 ** on error message strings returned through the 5th parameter of
893 ** of sqlite3_exec() after the error message string is no longer needed.
894 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
895 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
896 ** NULL before returning.
898 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
899 ** routine returns SQLITE_ABORT without invoking the callback again and
900 ** without running any subsequent SQL statements.
902 ** ^The 2nd argument to the sqlite3_exec() callback function is the
903 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
904 ** callback is an array of pointers to strings obtained as if from
905 ** [sqlite3_column_text()], one for each column. ^If an element of a
906 ** result row is NULL then the corresponding string pointer for the
907 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
908 ** sqlite3_exec() callback is an array of pointers to strings where each
909 ** entry represents the name of corresponding result column as obtained
910 ** from [sqlite3_column_name()].
912 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
913 ** to an empty string, or a pointer that contains only whitespace and/or
914 ** SQL comments, then no SQL statements are evaluated and the database
915 ** is not changed.
917 ** Restrictions:
919 ** <ul>
920 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
921 ** is a valid and open [database connection].
922 ** <li> The application must not close [database connection] specified by
923 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
924 ** <li> The application must not modify the SQL statement text passed into
925 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
926 ** </ul>
928 SQLITE_API int sqlite3_exec(
929 sqlite3*, /* An open database */
930 const char *sql, /* SQL to be evaluated */
931 int (*callback)(void*,int,char**,char**), /* Callback function */
932 void *, /* 1st argument to callback */
933 char **errmsg /* Error msg written here */
937 ** CAPI3REF: Result Codes
938 ** KEYWORDS: SQLITE_OK {error code} {error codes}
939 ** KEYWORDS: {result code} {result codes}
941 ** Many SQLite functions return an integer result code from the set shown
942 ** here in order to indicate success or failure.
944 ** New error codes may be added in future versions of SQLite.
946 ** See also: [SQLITE_IOERR_READ | extended result codes],
947 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
949 #define SQLITE_OK 0 /* Successful result */
950 /* beginning-of-error-codes */
951 #define SQLITE_ERROR 1 /* SQL error or missing database */
952 #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
953 #define SQLITE_PERM 3 /* Access permission denied */
954 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
955 #define SQLITE_BUSY 5 /* The database file is locked */
956 #define SQLITE_LOCKED 6 /* A table in the database is locked */
957 #define SQLITE_NOMEM 7 /* A malloc() failed */
958 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
959 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
960 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
961 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
962 #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
963 #define SQLITE_FULL 13 /* Insertion failed because database is full */
964 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
965 #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
966 #define SQLITE_EMPTY 16 /* Database is empty */
967 #define SQLITE_SCHEMA 17 /* The database schema changed */
968 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
969 #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
970 #define SQLITE_MISMATCH 20 /* Data type mismatch */
971 #define SQLITE_MISUSE 21 /* Library used incorrectly */
972 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
973 #define SQLITE_AUTH 23 /* Authorization denied */
974 #define SQLITE_FORMAT 24 /* Auxiliary database format error */
975 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
976 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
977 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
978 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
979 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
980 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
981 /* end-of-error-codes */
984 ** CAPI3REF: Extended Result Codes
985 ** KEYWORDS: {extended error code} {extended error codes}
986 ** KEYWORDS: {extended result code} {extended result codes}
988 ** In its default configuration, SQLite API routines return one of 26 integer
989 ** [SQLITE_OK | result codes]. However, experience has shown that many of
990 ** these result codes are too coarse-grained. They do not provide as
991 ** much information about problems as programmers might like. In an effort to
992 ** address this, newer versions of SQLite (version 3.3.8 and later) include
993 ** support for additional result codes that provide more detailed information
994 ** about errors. The extended result codes are enabled or disabled
995 ** on a per database connection basis using the
996 ** [sqlite3_extended_result_codes()] API.
998 ** Some of the available extended result codes are listed here.
999 ** One may expect the number of extended result codes will be expand
1000 ** over time. Software that uses extended result codes should expect
1001 ** to see new result codes in future releases of SQLite.
1003 ** The SQLITE_OK result code will never be extended. It will always
1004 ** be exactly zero.
1006 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
1007 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
1008 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
1009 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
1010 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
1011 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
1012 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
1013 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
1014 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
1015 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
1016 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
1017 #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
1018 #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
1019 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1020 #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
1021 #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
1022 #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
1023 #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
1024 #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
1025 #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
1026 #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
1027 #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
1028 #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
1029 #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
1030 #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
1031 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
1032 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
1033 #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
1034 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
1035 #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
1036 #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
1037 #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
1038 #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
1039 #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
1040 #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
1041 #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
1042 #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
1043 #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
1044 #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
1045 #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
1046 #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
1047 #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
1048 #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
1049 #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
1050 #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
1051 #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
1052 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
1053 #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
1056 ** CAPI3REF: Flags For File Open Operations
1058 ** These bit values are intended for use in the
1059 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1060 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1062 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
1063 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
1064 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
1065 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
1066 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
1067 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
1068 #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
1069 #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
1070 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
1071 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
1072 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
1073 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
1074 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
1075 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
1076 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
1077 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
1078 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
1079 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
1080 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
1081 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
1083 /* Reserved: 0x00F00000 */
1086 ** CAPI3REF: Device Characteristics
1088 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1089 ** object returns an integer which is a vector of these
1090 ** bit values expressing I/O characteristics of the mass storage
1091 ** device that holds the file that the [sqlite3_io_methods]
1092 ** refers to.
1094 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1095 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1096 ** mean that writes of blocks that are nnn bytes in size and
1097 ** are aligned to an address which is an integer multiple of
1098 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1099 ** that when data is appended to a file, the data is appended
1100 ** first then the size of the file is extended, never the other
1101 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1102 ** information is written to disk in the same order as calls
1103 ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1104 ** after reboot following a crash or power loss, the only bytes in a
1105 ** file that were written at the application level might have changed
1106 ** and that adjacent bytes, even bytes within the same sector are
1107 ** guaranteed to be unchanged.
1109 #define SQLITE_IOCAP_ATOMIC 0x00000001
1110 #define SQLITE_IOCAP_ATOMIC512 0x00000002
1111 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
1112 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
1113 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
1114 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
1115 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
1116 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
1117 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
1118 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
1119 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
1120 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
1121 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
1124 ** CAPI3REF: File Locking Levels
1126 ** SQLite uses one of these integer values as the second
1127 ** argument to calls it makes to the xLock() and xUnlock() methods
1128 ** of an [sqlite3_io_methods] object.
1130 #define SQLITE_LOCK_NONE 0
1131 #define SQLITE_LOCK_SHARED 1
1132 #define SQLITE_LOCK_RESERVED 2
1133 #define SQLITE_LOCK_PENDING 3
1134 #define SQLITE_LOCK_EXCLUSIVE 4
1137 ** CAPI3REF: Synchronization Type Flags
1139 ** When SQLite invokes the xSync() method of an
1140 ** [sqlite3_io_methods] object it uses a combination of
1141 ** these integer values as the second argument.
1143 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1144 ** sync operation only needs to flush data to mass storage. Inode
1145 ** information need not be flushed. If the lower four bits of the flag
1146 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1147 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1148 ** to use Mac OS X style fullsync instead of fsync().
1150 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1151 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1152 ** settings. The [synchronous pragma] determines when calls to the
1153 ** xSync VFS method occur and applies uniformly across all platforms.
1154 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1155 ** energetic or rigorous or forceful the sync operations are and
1156 ** only make a difference on Mac OSX for the default SQLite code.
1157 ** (Third-party VFS implementations might also make the distinction
1158 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1159 ** operating systems natively supported by SQLite, only Mac OSX
1160 ** cares about the difference.)
1162 #define SQLITE_SYNC_NORMAL 0x00002
1163 #define SQLITE_SYNC_FULL 0x00003
1164 #define SQLITE_SYNC_DATAONLY 0x00010
1167 ** CAPI3REF: OS Interface Open File Handle
1169 ** An [sqlite3_file] object represents an open file in the
1170 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
1171 ** implementations will
1172 ** want to subclass this object by appending additional fields
1173 ** for their own use. The pMethods entry is a pointer to an
1174 ** [sqlite3_io_methods] object that defines methods for performing
1175 ** I/O operations on the open file.
1177 typedef struct sqlite3_file sqlite3_file;
1178 struct sqlite3_file {
1179 const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
1183 ** CAPI3REF: OS Interface File Virtual Methods Object
1185 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1186 ** [sqlite3_file] object (or, more commonly, a subclass of the
1187 ** [sqlite3_file] object) with a pointer to an instance of this object.
1188 ** This object defines the methods used to perform various operations
1189 ** against the open file represented by the [sqlite3_file] object.
1191 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1192 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1193 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
1194 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1195 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1196 ** to NULL.
1198 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1199 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
1200 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
1201 ** flag may be ORed in to indicate that only the data of the file
1202 ** and not its inode needs to be synced.
1204 ** The integer values to xLock() and xUnlock() are one of
1205 ** <ul>
1206 ** <li> [SQLITE_LOCK_NONE],
1207 ** <li> [SQLITE_LOCK_SHARED],
1208 ** <li> [SQLITE_LOCK_RESERVED],
1209 ** <li> [SQLITE_LOCK_PENDING], or
1210 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1211 ** </ul>
1212 ** xLock() increases the lock. xUnlock() decreases the lock.
1213 ** The xCheckReservedLock() method checks whether any database connection,
1214 ** either in this process or in some other process, is holding a RESERVED,
1215 ** PENDING, or EXCLUSIVE lock on the file. It returns true
1216 ** if such a lock exists and false otherwise.
1218 ** The xFileControl() method is a generic interface that allows custom
1219 ** VFS implementations to directly control an open file using the
1220 ** [sqlite3_file_control()] interface. The second "op" argument is an
1221 ** integer opcode. The third argument is a generic pointer intended to
1222 ** point to a structure that may contain arguments or space in which to
1223 ** write return values. Potential uses for xFileControl() might be
1224 ** functions to enable blocking locks with timeouts, to change the
1225 ** locking strategy (for example to use dot-file locks), to inquire
1226 ** about the status of a lock, or to break stale locks. The SQLite
1227 ** core reserves all opcodes less than 100 for its own use.
1228 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1229 ** Applications that define a custom xFileControl method should use opcodes
1230 ** greater than 100 to avoid conflicts. VFS implementations should
1231 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1232 ** recognize.
1234 ** The xSectorSize() method returns the sector size of the
1235 ** device that underlies the file. The sector size is the
1236 ** minimum write that can be performed without disturbing
1237 ** other bytes in the file. The xDeviceCharacteristics()
1238 ** method returns a bit vector describing behaviors of the
1239 ** underlying device:
1241 ** <ul>
1242 ** <li> [SQLITE_IOCAP_ATOMIC]
1243 ** <li> [SQLITE_IOCAP_ATOMIC512]
1244 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1245 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1246 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1247 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1248 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1249 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1250 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1251 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1252 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1253 ** </ul>
1255 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1256 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1257 ** mean that writes of blocks that are nnn bytes in size and
1258 ** are aligned to an address which is an integer multiple of
1259 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1260 ** that when data is appended to a file, the data is appended
1261 ** first then the size of the file is extended, never the other
1262 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1263 ** information is written to disk in the same order as calls
1264 ** to xWrite().
1266 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1267 ** in the unread portions of the buffer with zeros. A VFS that
1268 ** fails to zero-fill short reads might seem to work. However,
1269 ** failure to zero-fill short reads will eventually lead to
1270 ** database corruption.
1272 typedef struct sqlite3_io_methods sqlite3_io_methods;
1273 struct sqlite3_io_methods {
1274 int iVersion;
1275 int (*xClose)(sqlite3_file*);
1276 int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1277 int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1278 int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1279 int (*xSync)(sqlite3_file*, int flags);
1280 int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1281 int (*xLock)(sqlite3_file*, int);
1282 int (*xUnlock)(sqlite3_file*, int);
1283 int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1284 int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1285 int (*xSectorSize)(sqlite3_file*);
1286 int (*xDeviceCharacteristics)(sqlite3_file*);
1287 /* Methods above are valid for version 1 */
1288 int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1289 int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1290 void (*xShmBarrier)(sqlite3_file*);
1291 int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1292 /* Methods above are valid for version 2 */
1293 int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1294 int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1295 /* Methods above are valid for version 3 */
1296 /* Additional methods may be added in future releases */
1300 ** CAPI3REF: Standard File Control Opcodes
1302 ** These integer constants are opcodes for the xFileControl method
1303 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1304 ** interface.
1306 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1307 ** opcode causes the xFileControl method to write the current state of
1308 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1309 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1310 ** into an integer that the pArg argument points to. This capability
1311 ** is used during testing and only needs to be supported when SQLITE_TEST
1312 ** is defined.
1313 ** <ul>
1314 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1315 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1316 ** layer a hint of how large the database file will grow to be during the
1317 ** current transaction. This hint is not guaranteed to be accurate but it
1318 ** is often close. The underlying VFS might choose to preallocate database
1319 ** file space based on this hint in order to help writes to the database
1320 ** file run faster.
1322 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1323 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1324 ** extends and truncates the database file in chunks of a size specified
1325 ** by the user. The fourth argument to [sqlite3_file_control()] should
1326 ** point to an integer (type int) containing the new chunk-size to use
1327 ** for the nominated database. Allocating database file space in large
1328 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1329 ** improve performance on some systems.
1331 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1332 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1333 ** to the [sqlite3_file] object associated with a particular database
1334 ** connection. See the [sqlite3_file_control()] documentation for
1335 ** additional information.
1337 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1338 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1339 ** SQLite and sent to all VFSes in place of a call to the xSync method
1340 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1341 ** Some specialized VFSes need this signal in order to operate correctly
1342 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
1343 ** VFSes do not need this signal and should silently ignore this opcode.
1344 ** Applications should not call [sqlite3_file_control()] with this
1345 ** opcode as doing so may disrupt the operation of the specialized VFSes
1346 ** that do require it.
1348 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1349 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1350 ** retry counts and intervals for certain disk I/O operations for the
1351 ** windows [VFS] in order to provide robustness in the presence of
1352 ** anti-virus programs. By default, the windows VFS will retry file read,
1353 ** file write, and file delete operations up to 10 times, with a delay
1354 ** of 25 milliseconds before the first retry and with the delay increasing
1355 ** by an additional 25 milliseconds with each subsequent retry. This
1356 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1357 ** to be adjusted. The values are changed for all database connections
1358 ** within the same process. The argument is a pointer to an array of two
1359 ** integers where the first integer i the new retry count and the second
1360 ** integer is the delay. If either integer is negative, then the setting
1361 ** is not changed but instead the prior value of that setting is written
1362 ** into the array entry, allowing the current retry settings to be
1363 ** interrogated. The zDbName parameter is ignored.
1365 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1366 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1367 ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1368 ** write ahead log and shared memory files used for transaction control
1369 ** are automatically deleted when the latest connection to the database
1370 ** closes. Setting persistent WAL mode causes those files to persist after
1371 ** close. Persisting the files is useful when other processes that do not
1372 ** have write permission on the directory containing the database file want
1373 ** to read the database file, as the WAL and shared memory files must exist
1374 ** in order for the database to be readable. The fourth parameter to
1375 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1376 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1377 ** WAL mode. If the integer is -1, then it is overwritten with the current
1378 ** WAL persistence setting.
1380 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1381 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1382 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1383 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1384 ** xDeviceCharacteristics methods. The fourth parameter to
1385 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1386 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1387 ** mode. If the integer is -1, then it is overwritten with the current
1388 ** zero-damage mode setting.
1390 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1391 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1392 ** a write transaction to indicate that, unless it is rolled back for some
1393 ** reason, the entire database file will be overwritten by the current
1394 ** transaction. This is used by VACUUM operations.
1396 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1397 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1398 ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
1399 ** final bottom-level VFS are written into memory obtained from
1400 ** [sqlite3_malloc()] and the result is stored in the char* variable
1401 ** that the fourth parameter of [sqlite3_file_control()] points to.
1402 ** The caller is responsible for freeing the memory when done. As with
1403 ** all file-control actions, there is no guarantee that this will actually
1404 ** do anything. Callers should initialize the char* variable to a NULL
1405 ** pointer in case this file-control is not implemented. This file-control
1406 ** is intended for diagnostic use only.
1408 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1409 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1410 ** file control is sent to the open [sqlite3_file] object corresponding
1411 ** to the database file to which the pragma statement refers. ^The argument
1412 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1413 ** pointers to strings (char**) in which the second element of the array
1414 ** is the name of the pragma and the third element is the argument to the
1415 ** pragma or NULL if the pragma has no argument. ^The handler for an
1416 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1417 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1418 ** or the equivalent and that string will become the result of the pragma or
1419 ** the error message if the pragma fails. ^If the
1420 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1421 ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1422 ** file control returns [SQLITE_OK], then the parser assumes that the
1423 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1424 ** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1425 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1426 ** that the VFS encountered an error while handling the [PRAGMA] and the
1427 ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1428 ** file control occurs at the beginning of pragma statement analysis and so
1429 ** it is able to override built-in [PRAGMA] statements.
1431 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1432 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1433 ** file-control may be invoked by SQLite on the database file handle
1434 ** shortly after it is opened in order to provide a custom VFS with access
1435 ** to the connections busy-handler callback. The argument is of type (void **)
1436 ** - an array of two (void *) values. The first (void *) actually points
1437 ** to a function of type (int (*)(void *)). In order to invoke the connections
1438 ** busy-handler, this function should be invoked with the second (void *) in
1439 ** the array as the only argument. If it returns non-zero, then the operation
1440 ** should be retried. If it returns zero, the custom VFS should abandon the
1441 ** current operation.
1443 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1444 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1445 ** to have SQLite generate a
1446 ** temporary filename using the same algorithm that is followed to generate
1447 ** temporary filenames for TEMP tables and other internal uses. The
1448 ** argument should be a char** which will be filled with the filename
1449 ** written into memory obtained from [sqlite3_malloc()]. The caller should
1450 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1452 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1453 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1454 ** maximum number of bytes that will be used for memory-mapped I/O.
1455 ** The argument is a pointer to a value of type sqlite3_int64 that
1456 ** is an advisory maximum number of bytes in the file to memory map. The
1457 ** pointer is overwritten with the old value. The limit is not changed if
1458 ** the value originally pointed to is negative, and so the current limit
1459 ** can be queried by passing in a pointer to a negative number. This
1460 ** file-control is used internally to implement [PRAGMA mmap_size].
1462 ** </ul>
1464 #define SQLITE_FCNTL_LOCKSTATE 1
1465 #define SQLITE_GET_LOCKPROXYFILE 2
1466 #define SQLITE_SET_LOCKPROXYFILE 3
1467 #define SQLITE_LAST_ERRNO 4
1468 #define SQLITE_FCNTL_SIZE_HINT 5
1469 #define SQLITE_FCNTL_CHUNK_SIZE 6
1470 #define SQLITE_FCNTL_FILE_POINTER 7
1471 #define SQLITE_FCNTL_SYNC_OMITTED 8
1472 #define SQLITE_FCNTL_WIN32_AV_RETRY 9
1473 #define SQLITE_FCNTL_PERSIST_WAL 10
1474 #define SQLITE_FCNTL_OVERWRITE 11
1475 #define SQLITE_FCNTL_VFSNAME 12
1476 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
1477 #define SQLITE_FCNTL_PRAGMA 14
1478 #define SQLITE_FCNTL_BUSYHANDLER 15
1479 #define SQLITE_FCNTL_TEMPFILENAME 16
1480 #define SQLITE_FCNTL_MMAP_SIZE 18
1483 ** CAPI3REF: Mutex Handle
1485 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1486 ** abstract type for a mutex object. The SQLite core never looks
1487 ** at the internal representation of an [sqlite3_mutex]. It only
1488 ** deals with pointers to the [sqlite3_mutex] object.
1490 ** Mutexes are created using [sqlite3_mutex_alloc()].
1492 typedef struct sqlite3_mutex sqlite3_mutex;
1495 ** CAPI3REF: OS Interface Object
1497 ** An instance of the sqlite3_vfs object defines the interface between
1498 ** the SQLite core and the underlying operating system. The "vfs"
1499 ** in the name of the object stands for "virtual file system". See
1500 ** the [VFS | VFS documentation] for further information.
1502 ** The value of the iVersion field is initially 1 but may be larger in
1503 ** future versions of SQLite. Additional fields may be appended to this
1504 ** object when the iVersion value is increased. Note that the structure
1505 ** of the sqlite3_vfs object changes in the transaction between
1506 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1507 ** modified.
1509 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1510 ** structure used by this VFS. mxPathname is the maximum length of
1511 ** a pathname in this VFS.
1513 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1514 ** the pNext pointer. The [sqlite3_vfs_register()]
1515 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1516 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1517 ** searches the list. Neither the application code nor the VFS
1518 ** implementation should use the pNext pointer.
1520 ** The pNext field is the only field in the sqlite3_vfs
1521 ** structure that SQLite will ever modify. SQLite will only access
1522 ** or modify this field while holding a particular static mutex.
1523 ** The application should never modify anything within the sqlite3_vfs
1524 ** object once the object has been registered.
1526 ** The zName field holds the name of the VFS module. The name must
1527 ** be unique across all VFS modules.
1529 ** [[sqlite3_vfs.xOpen]]
1530 ** ^SQLite guarantees that the zFilename parameter to xOpen
1531 ** is either a NULL pointer or string obtained
1532 ** from xFullPathname() with an optional suffix added.
1533 ** ^If a suffix is added to the zFilename parameter, it will
1534 ** consist of a single "-" character followed by no more than
1535 ** 11 alphanumeric and/or "-" characters.
1536 ** ^SQLite further guarantees that
1537 ** the string will be valid and unchanged until xClose() is
1538 ** called. Because of the previous sentence,
1539 ** the [sqlite3_file] can safely store a pointer to the
1540 ** filename if it needs to remember the filename for some reason.
1541 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1542 ** must invent its own temporary name for the file. ^Whenever the
1543 ** xFilename parameter is NULL it will also be the case that the
1544 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1546 ** The flags argument to xOpen() includes all bits set in
1547 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1548 ** or [sqlite3_open16()] is used, then flags includes at least
1549 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1550 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1551 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1553 ** ^(SQLite will also add one of the following flags to the xOpen()
1554 ** call, depending on the object being opened:
1556 ** <ul>
1557 ** <li> [SQLITE_OPEN_MAIN_DB]
1558 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1559 ** <li> [SQLITE_OPEN_TEMP_DB]
1560 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1561 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1562 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1563 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1564 ** <li> [SQLITE_OPEN_WAL]
1565 ** </ul>)^
1567 ** The file I/O implementation can use the object type flags to
1568 ** change the way it deals with files. For example, an application
1569 ** that does not care about crash recovery or rollback might make
1570 ** the open of a journal file a no-op. Writes to this journal would
1571 ** also be no-ops, and any attempt to read the journal would return
1572 ** SQLITE_IOERR. Or the implementation might recognize that a database
1573 ** file will be doing page-aligned sector reads and writes in a random
1574 ** order and set up its I/O subsystem accordingly.
1576 ** SQLite might also add one of the following flags to the xOpen method:
1578 ** <ul>
1579 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1580 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1581 ** </ul>
1583 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1584 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1585 ** will be set for TEMP databases and their journals, transient
1586 ** databases, and subjournals.
1588 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1589 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1590 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1591 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1592 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1593 ** be created, and that it is an error if it already exists.
1594 ** It is <i>not</i> used to indicate the file should be opened
1595 ** for exclusive access.
1597 ** ^At least szOsFile bytes of memory are allocated by SQLite
1598 ** to hold the [sqlite3_file] structure passed as the third
1599 ** argument to xOpen. The xOpen method does not have to
1600 ** allocate the structure; it should just fill it in. Note that
1601 ** the xOpen method must set the sqlite3_file.pMethods to either
1602 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1603 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1604 ** element will be valid after xOpen returns regardless of the success
1605 ** or failure of the xOpen call.
1607 ** [[sqlite3_vfs.xAccess]]
1608 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1609 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1610 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1611 ** to test whether a file is at least readable. The file can be a
1612 ** directory.
1614 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1615 ** output buffer xFullPathname. The exact size of the output buffer
1616 ** is also passed as a parameter to both methods. If the output buffer
1617 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1618 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1619 ** to prevent this by setting mxPathname to a sufficiently large value.
1621 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1622 ** interfaces are not strictly a part of the filesystem, but they are
1623 ** included in the VFS structure for completeness.
1624 ** The xRandomness() function attempts to return nBytes bytes
1625 ** of good-quality randomness into zOut. The return value is
1626 ** the actual number of bytes of randomness obtained.
1627 ** The xSleep() method causes the calling thread to sleep for at
1628 ** least the number of microseconds given. ^The xCurrentTime()
1629 ** method returns a Julian Day Number for the current date and time as
1630 ** a floating point value.
1631 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1632 ** Day Number multiplied by 86400000 (the number of milliseconds in
1633 ** a 24-hour day).
1634 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1635 ** date and time if that method is available (if iVersion is 2 or
1636 ** greater and the function pointer is not NULL) and will fall back
1637 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1639 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1640 ** are not used by the SQLite core. These optional interfaces are provided
1641 ** by some VFSes to facilitate testing of the VFS code. By overriding
1642 ** system calls with functions under its control, a test program can
1643 ** simulate faults and error conditions that would otherwise be difficult
1644 ** or impossible to induce. The set of system calls that can be overridden
1645 ** varies from one VFS to another, and from one version of the same VFS to the
1646 ** next. Applications that use these interfaces must be prepared for any
1647 ** or all of these interfaces to be NULL or for their behavior to change
1648 ** from one release to the next. Applications must not attempt to access
1649 ** any of these methods if the iVersion of the VFS is less than 3.
1651 typedef struct sqlite3_vfs sqlite3_vfs;
1652 typedef void (*sqlite3_syscall_ptr)(void);
1653 struct sqlite3_vfs {
1654 int iVersion; /* Structure version number (currently 3) */
1655 int szOsFile; /* Size of subclassed sqlite3_file */
1656 int mxPathname; /* Maximum file pathname length */
1657 sqlite3_vfs *pNext; /* Next registered VFS */
1658 const char *zName; /* Name of this virtual file system */
1659 void *pAppData; /* Pointer to application-specific data */
1660 int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1661 int flags, int *pOutFlags);
1662 int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1663 int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1664 int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1665 void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1666 void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1667 void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1668 void (*xDlClose)(sqlite3_vfs*, void*);
1669 int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1670 int (*xSleep)(sqlite3_vfs*, int microseconds);
1671 int (*xCurrentTime)(sqlite3_vfs*, double*);
1672 int (*xGetLastError)(sqlite3_vfs*, int, char *);
1674 ** The methods above are in version 1 of the sqlite_vfs object
1675 ** definition. Those that follow are added in version 2 or later
1677 int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1679 ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1680 ** Those below are for version 3 and greater.
1682 int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1683 sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1684 const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1686 ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1687 ** New fields may be appended in figure versions. The iVersion
1688 ** value will increment whenever this happens.
1693 ** CAPI3REF: Flags for the xAccess VFS method
1695 ** These integer constants can be used as the third parameter to
1696 ** the xAccess method of an [sqlite3_vfs] object. They determine
1697 ** what kind of permissions the xAccess method is looking for.
1698 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1699 ** simply checks whether the file exists.
1700 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1701 ** checks whether the named directory is both readable and writable
1702 ** (in other words, if files can be added, removed, and renamed within
1703 ** the directory).
1704 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1705 ** [temp_store_directory pragma], though this could change in a future
1706 ** release of SQLite.
1707 ** With SQLITE_ACCESS_READ, the xAccess method
1708 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1709 ** currently unused, though it might be used in a future release of
1710 ** SQLite.
1712 #define SQLITE_ACCESS_EXISTS 0
1713 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1714 #define SQLITE_ACCESS_READ 2 /* Unused */
1717 ** CAPI3REF: Flags for the xShmLock VFS method
1719 ** These integer constants define the various locking operations
1720 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
1721 ** following are the only legal combinations of flags to the
1722 ** xShmLock method:
1724 ** <ul>
1725 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1726 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1727 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1728 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1729 ** </ul>
1731 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1732 ** was given no the corresponding lock.
1734 ** The xShmLock method can transition between unlocked and SHARED or
1735 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1736 ** and EXCLUSIVE.
1738 #define SQLITE_SHM_UNLOCK 1
1739 #define SQLITE_SHM_LOCK 2
1740 #define SQLITE_SHM_SHARED 4
1741 #define SQLITE_SHM_EXCLUSIVE 8
1744 ** CAPI3REF: Maximum xShmLock index
1746 ** The xShmLock method on [sqlite3_io_methods] may use values
1747 ** between 0 and this upper bound as its "offset" argument.
1748 ** The SQLite core will never attempt to acquire or release a
1749 ** lock outside of this range
1751 #define SQLITE_SHM_NLOCK 8
1755 ** CAPI3REF: Initialize The SQLite Library
1757 ** ^The sqlite3_initialize() routine initializes the
1758 ** SQLite library. ^The sqlite3_shutdown() routine
1759 ** deallocates any resources that were allocated by sqlite3_initialize().
1760 ** These routines are designed to aid in process initialization and
1761 ** shutdown on embedded systems. Workstation applications using
1762 ** SQLite normally do not need to invoke either of these routines.
1764 ** A call to sqlite3_initialize() is an "effective" call if it is
1765 ** the first time sqlite3_initialize() is invoked during the lifetime of
1766 ** the process, or if it is the first time sqlite3_initialize() is invoked
1767 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1768 ** of sqlite3_initialize() does any initialization. All other calls
1769 ** are harmless no-ops.)^
1771 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1772 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1773 ** an effective call to sqlite3_shutdown() does any deinitialization.
1774 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1776 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1777 ** is not. The sqlite3_shutdown() interface must only be called from a
1778 ** single thread. All open [database connections] must be closed and all
1779 ** other SQLite resources must be deallocated prior to invoking
1780 ** sqlite3_shutdown().
1782 ** Among other things, ^sqlite3_initialize() will invoke
1783 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1784 ** will invoke sqlite3_os_end().
1786 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1787 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1788 ** the library (perhaps it is unable to allocate a needed resource such
1789 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1791 ** ^The sqlite3_initialize() routine is called internally by many other
1792 ** SQLite interfaces so that an application usually does not need to
1793 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1794 ** calls sqlite3_initialize() so the SQLite library will be automatically
1795 ** initialized when [sqlite3_open()] is called if it has not be initialized
1796 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1797 ** compile-time option, then the automatic calls to sqlite3_initialize()
1798 ** are omitted and the application must call sqlite3_initialize() directly
1799 ** prior to using any other SQLite interface. For maximum portability,
1800 ** it is recommended that applications always invoke sqlite3_initialize()
1801 ** directly prior to using any other SQLite interface. Future releases
1802 ** of SQLite may require this. In other words, the behavior exhibited
1803 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1804 ** default behavior in some future release of SQLite.
1806 ** The sqlite3_os_init() routine does operating-system specific
1807 ** initialization of the SQLite library. The sqlite3_os_end()
1808 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
1809 ** performed by these routines include allocation or deallocation
1810 ** of static resources, initialization of global variables,
1811 ** setting up a default [sqlite3_vfs] module, or setting up
1812 ** a default configuration using [sqlite3_config()].
1814 ** The application should never invoke either sqlite3_os_init()
1815 ** or sqlite3_os_end() directly. The application should only invoke
1816 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1817 ** interface is called automatically by sqlite3_initialize() and
1818 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1819 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1820 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1821 ** When [custom builds | built for other platforms]
1822 ** (using the [SQLITE_OS_OTHER=1] compile-time
1823 ** option) the application must supply a suitable implementation for
1824 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1825 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1826 ** must return [SQLITE_OK] on success and some other [error code] upon
1827 ** failure.
1829 SQLITE_API int sqlite3_initialize(void);
1830 SQLITE_API int sqlite3_shutdown(void);
1831 SQLITE_API int sqlite3_os_init(void);
1832 SQLITE_API int sqlite3_os_end(void);
1835 ** CAPI3REF: Configuring The SQLite Library
1837 ** The sqlite3_config() interface is used to make global configuration
1838 ** changes to SQLite in order to tune SQLite to the specific needs of
1839 ** the application. The default configuration is recommended for most
1840 ** applications and so this routine is usually not necessary. It is
1841 ** provided to support rare applications with unusual needs.
1843 ** The sqlite3_config() interface is not threadsafe. The application
1844 ** must insure that no other SQLite interfaces are invoked by other
1845 ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
1846 ** may only be invoked prior to library initialization using
1847 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1848 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1849 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1850 ** Note, however, that ^sqlite3_config() can be called as part of the
1851 ** implementation of an application-defined [sqlite3_os_init()].
1853 ** The first argument to sqlite3_config() is an integer
1854 ** [configuration option] that determines
1855 ** what property of SQLite is to be configured. Subsequent arguments
1856 ** vary depending on the [configuration option]
1857 ** in the first argument.
1859 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1860 ** ^If the option is unknown or SQLite is unable to set the option
1861 ** then this routine returns a non-zero [error code].
1863 SQLITE_API int sqlite3_config(int, ...);
1866 ** CAPI3REF: Configure database connections
1868 ** The sqlite3_db_config() interface is used to make configuration
1869 ** changes to a [database connection]. The interface is similar to
1870 ** [sqlite3_config()] except that the changes apply to a single
1871 ** [database connection] (specified in the first argument).
1873 ** The second argument to sqlite3_db_config(D,V,...) is the
1874 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1875 ** that indicates what aspect of the [database connection] is being configured.
1876 ** Subsequent arguments vary depending on the configuration verb.
1878 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1879 ** the call is considered successful.
1881 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1884 ** CAPI3REF: Memory Allocation Routines
1886 ** An instance of this object defines the interface between SQLite
1887 ** and low-level memory allocation routines.
1889 ** This object is used in only one place in the SQLite interface.
1890 ** A pointer to an instance of this object is the argument to
1891 ** [sqlite3_config()] when the configuration option is
1892 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1893 ** By creating an instance of this object
1894 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1895 ** during configuration, an application can specify an alternative
1896 ** memory allocation subsystem for SQLite to use for all of its
1897 ** dynamic memory needs.
1899 ** Note that SQLite comes with several [built-in memory allocators]
1900 ** that are perfectly adequate for the overwhelming majority of applications
1901 ** and that this object is only useful to a tiny minority of applications
1902 ** with specialized memory allocation requirements. This object is
1903 ** also used during testing of SQLite in order to specify an alternative
1904 ** memory allocator that simulates memory out-of-memory conditions in
1905 ** order to verify that SQLite recovers gracefully from such
1906 ** conditions.
1908 ** The xMalloc, xRealloc, and xFree methods must work like the
1909 ** malloc(), realloc() and free() functions from the standard C library.
1910 ** ^SQLite guarantees that the second argument to
1911 ** xRealloc is always a value returned by a prior call to xRoundup.
1913 ** xSize should return the allocated size of a memory allocation
1914 ** previously obtained from xMalloc or xRealloc. The allocated size
1915 ** is always at least as big as the requested size but may be larger.
1917 ** The xRoundup method returns what would be the allocated size of
1918 ** a memory allocation given a particular requested size. Most memory
1919 ** allocators round up memory allocations at least to the next multiple
1920 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
1921 ** Every memory allocation request coming in through [sqlite3_malloc()]
1922 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
1923 ** that causes the corresponding memory allocation to fail.
1925 ** The xInit method initializes the memory allocator. (For example,
1926 ** it might allocate any require mutexes or initialize internal data
1927 ** structures. The xShutdown method is invoked (indirectly) by
1928 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1929 ** by xInit. The pAppData pointer is used as the only parameter to
1930 ** xInit and xShutdown.
1932 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1933 ** the xInit method, so the xInit method need not be threadsafe. The
1934 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1935 ** not need to be threadsafe either. For all other methods, SQLite
1936 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1937 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1938 ** it is by default) and so the methods are automatically serialized.
1939 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1940 ** methods must be threadsafe or else make their own arrangements for
1941 ** serialization.
1943 ** SQLite will never invoke xInit() more than once without an intervening
1944 ** call to xShutdown().
1946 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1947 struct sqlite3_mem_methods {
1948 void *(*xMalloc)(int); /* Memory allocation function */
1949 void (*xFree)(void*); /* Free a prior allocation */
1950 void *(*xRealloc)(void*,int); /* Resize an allocation */
1951 int (*xSize)(void*); /* Return the size of an allocation */
1952 int (*xRoundup)(int); /* Round up request size to allocation size */
1953 int (*xInit)(void*); /* Initialize the memory allocator */
1954 void (*xShutdown)(void*); /* Deinitialize the memory allocator */
1955 void *pAppData; /* Argument to xInit() and xShutdown() */
1959 ** CAPI3REF: Configuration Options
1960 ** KEYWORDS: {configuration option}
1962 ** These constants are the available integer configuration options that
1963 ** can be passed as the first argument to the [sqlite3_config()] interface.
1965 ** New configuration options may be added in future releases of SQLite.
1966 ** Existing configuration options might be discontinued. Applications
1967 ** should check the return code from [sqlite3_config()] to make sure that
1968 ** the call worked. The [sqlite3_config()] interface will return a
1969 ** non-zero [error code] if a discontinued or unsupported configuration option
1970 ** is invoked.
1972 ** <dl>
1973 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1974 ** <dd>There are no arguments to this option. ^This option sets the
1975 ** [threading mode] to Single-thread. In other words, it disables
1976 ** all mutexing and puts SQLite into a mode where it can only be used
1977 ** by a single thread. ^If SQLite is compiled with
1978 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1979 ** it is not possible to change the [threading mode] from its default
1980 ** value of Single-thread and so [sqlite3_config()] will return
1981 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1982 ** configuration option.</dd>
1984 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1985 ** <dd>There are no arguments to this option. ^This option sets the
1986 ** [threading mode] to Multi-thread. In other words, it disables
1987 ** mutexing on [database connection] and [prepared statement] objects.
1988 ** The application is responsible for serializing access to
1989 ** [database connections] and [prepared statements]. But other mutexes
1990 ** are enabled so that SQLite will be safe to use in a multi-threaded
1991 ** environment as long as no two threads attempt to use the same
1992 ** [database connection] at the same time. ^If SQLite is compiled with
1993 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1994 ** it is not possible to set the Multi-thread [threading mode] and
1995 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1996 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1998 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1999 ** <dd>There are no arguments to this option. ^This option sets the
2000 ** [threading mode] to Serialized. In other words, this option enables
2001 ** all mutexes including the recursive
2002 ** mutexes on [database connection] and [prepared statement] objects.
2003 ** In this mode (which is the default when SQLite is compiled with
2004 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
2005 ** to [database connections] and [prepared statements] so that the
2006 ** application is free to use the same [database connection] or the
2007 ** same [prepared statement] in different threads at the same time.
2008 ** ^If SQLite is compiled with
2009 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2010 ** it is not possible to set the Serialized [threading mode] and
2011 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2012 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
2014 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
2015 ** <dd> ^(This option takes a single argument which is a pointer to an
2016 ** instance of the [sqlite3_mem_methods] structure. The argument specifies
2017 ** alternative low-level memory allocation routines to be used in place of
2018 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
2019 ** its own private copy of the content of the [sqlite3_mem_methods] structure
2020 ** before the [sqlite3_config()] call returns.</dd>
2022 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2023 ** <dd> ^(This option takes a single argument which is a pointer to an
2024 ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
2025 ** structure is filled with the currently defined memory allocation routines.)^
2026 ** This option can be used to overload the default memory allocation
2027 ** routines with a wrapper that simulations memory allocation failure or
2028 ** tracks memory usage, for example. </dd>
2030 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2031 ** <dd> ^This option takes single argument of type int, interpreted as a
2032 ** boolean, which enables or disables the collection of memory allocation
2033 ** statistics. ^(When memory allocation statistics are disabled, the
2034 ** following SQLite interfaces become non-operational:
2035 ** <ul>
2036 ** <li> [sqlite3_memory_used()]
2037 ** <li> [sqlite3_memory_highwater()]
2038 ** <li> [sqlite3_soft_heap_limit64()]
2039 ** <li> [sqlite3_status()]
2040 ** </ul>)^
2041 ** ^Memory allocation statistics are enabled by default unless SQLite is
2042 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2043 ** allocation statistics are disabled by default.
2044 ** </dd>
2046 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2047 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2048 ** scratch memory. There are three arguments: A pointer an 8-byte
2049 ** aligned memory buffer from which the scratch allocations will be
2050 ** drawn, the size of each scratch allocation (sz),
2051 ** and the maximum number of scratch allocations (N). The sz
2052 ** argument must be a multiple of 16.
2053 ** The first argument must be a pointer to an 8-byte aligned buffer
2054 ** of at least sz*N bytes of memory.
2055 ** ^SQLite will use no more than two scratch buffers per thread. So
2056 ** N should be set to twice the expected maximum number of threads.
2057 ** ^SQLite will never require a scratch buffer that is more than 6
2058 ** times the database page size. ^If SQLite needs needs additional
2059 ** scratch memory beyond what is provided by this configuration option, then
2060 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
2062 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2063 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2064 ** the database page cache with the default page cache implementation.
2065 ** This configuration should not be used if an application-define page
2066 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
2067 ** There are three arguments to this option: A pointer to 8-byte aligned
2068 ** memory, the size of each page buffer (sz), and the number of pages (N).
2069 ** The sz argument should be the size of the largest database page
2070 ** (a power of two between 512 and 32768) plus a little extra for each
2071 ** page header. ^The page header size is 20 to 40 bytes depending on
2072 ** the host architecture. ^It is harmless, apart from the wasted memory,
2073 ** to make sz a little too large. The first
2074 ** argument should point to an allocation of at least sz*N bytes of memory.
2075 ** ^SQLite will use the memory provided by the first argument to satisfy its
2076 ** memory needs for the first N pages that it adds to cache. ^If additional
2077 ** page cache memory is needed beyond what is provided by this option, then
2078 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
2079 ** The pointer in the first argument must
2080 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
2081 ** will be undefined.</dd>
2083 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2084 ** <dd> ^This option specifies a static memory buffer that SQLite will use
2085 ** for all of its dynamic memory allocation needs beyond those provided
2086 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
2087 ** There are three arguments: An 8-byte aligned pointer to the memory,
2088 ** the number of bytes in the memory buffer, and the minimum allocation size.
2089 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2090 ** to using its default memory allocator (the system malloc() implementation),
2091 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
2092 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
2093 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
2094 ** allocator is engaged to handle all of SQLites memory allocation needs.
2095 ** The first pointer (the memory pointer) must be aligned to an 8-byte
2096 ** boundary or subsequent behavior of SQLite will be undefined.
2097 ** The minimum allocation size is capped at 2**12. Reasonable values
2098 ** for the minimum allocation size are 2**5 through 2**8.</dd>
2100 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2101 ** <dd> ^(This option takes a single argument which is a pointer to an
2102 ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
2103 ** alternative low-level mutex routines to be used in place
2104 ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
2105 ** content of the [sqlite3_mutex_methods] structure before the call to
2106 ** [sqlite3_config()] returns. ^If SQLite is compiled with
2107 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2108 ** the entire mutexing subsystem is omitted from the build and hence calls to
2109 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2110 ** return [SQLITE_ERROR].</dd>
2112 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2113 ** <dd> ^(This option takes a single argument which is a pointer to an
2114 ** instance of the [sqlite3_mutex_methods] structure. The
2115 ** [sqlite3_mutex_methods]
2116 ** structure is filled with the currently defined mutex routines.)^
2117 ** This option can be used to overload the default mutex allocation
2118 ** routines with a wrapper used to track mutex usage for performance
2119 ** profiling or testing, for example. ^If SQLite is compiled with
2120 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2121 ** the entire mutexing subsystem is omitted from the build and hence calls to
2122 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2123 ** return [SQLITE_ERROR].</dd>
2125 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2126 ** <dd> ^(This option takes two arguments that determine the default
2127 ** memory allocation for the lookaside memory allocator on each
2128 ** [database connection]. The first argument is the
2129 ** size of each lookaside buffer slot and the second is the number of
2130 ** slots allocated to each database connection.)^ ^(This option sets the
2131 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2132 ** verb to [sqlite3_db_config()] can be used to change the lookaside
2133 ** configuration on individual connections.)^ </dd>
2135 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2136 ** <dd> ^(This option takes a single argument which is a pointer to
2137 ** an [sqlite3_pcache_methods2] object. This object specifies the interface
2138 ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
2139 ** object and uses it for page cache memory allocations.</dd>
2141 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2142 ** <dd> ^(This option takes a single argument which is a pointer to an
2143 ** [sqlite3_pcache_methods2] object. SQLite copies of the current
2144 ** page cache implementation into that object.)^ </dd>
2146 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2147 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2148 ** global [error log].
2149 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2150 ** function with a call signature of void(*)(void*,int,const char*),
2151 ** and a pointer to void. ^If the function pointer is not NULL, it is
2152 ** invoked by [sqlite3_log()] to process each logging event. ^If the
2153 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2154 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2155 ** passed through as the first parameter to the application-defined logger
2156 ** function whenever that function is invoked. ^The second parameter to
2157 ** the logger function is a copy of the first parameter to the corresponding
2158 ** [sqlite3_log()] call and is intended to be a [result code] or an
2159 ** [extended result code]. ^The third parameter passed to the logger is
2160 ** log message after formatting via [sqlite3_snprintf()].
2161 ** The SQLite logging interface is not reentrant; the logger function
2162 ** supplied by the application must not invoke any SQLite interface.
2163 ** In a multi-threaded application, the application-defined logger
2164 ** function must be threadsafe. </dd>
2166 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2167 ** <dd> This option takes a single argument of type int. If non-zero, then
2168 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2169 ** is globally disabled. If URI handling is globally enabled, all filenames
2170 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2171 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2172 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2173 ** connection is opened. If it is globally disabled, filenames are
2174 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2175 ** database connection is opened. By default, URI handling is globally
2176 ** disabled. The default value may be changed by compiling with the
2177 ** [SQLITE_USE_URI] symbol defined.
2179 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2180 ** <dd> This option takes a single integer argument which is interpreted as
2181 ** a boolean in order to enable or disable the use of covering indices for
2182 ** full table scans in the query optimizer. The default setting is determined
2183 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2184 ** if that compile-time option is omitted.
2185 ** The ability to disable the use of covering indices for full table scans
2186 ** is because some incorrectly coded legacy applications might malfunction
2187 ** malfunction when the optimization is enabled. Providing the ability to
2188 ** disable the optimization allows the older, buggy application code to work
2189 ** without change even with newer versions of SQLite.
2191 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2192 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2193 ** <dd> These options are obsolete and should not be used by new code.
2194 ** They are retained for backwards compatibility but are now no-ops.
2195 ** </dd>
2197 ** [[SQLITE_CONFIG_SQLLOG]]
2198 ** <dt>SQLITE_CONFIG_SQLLOG
2199 ** <dd>This option is only available if sqlite is compiled with the
2200 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2201 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2202 ** The second should be of type (void*). The callback is invoked by the library
2203 ** in three separate circumstances, identified by the value passed as the
2204 ** fourth parameter. If the fourth parameter is 0, then the database connection
2205 ** passed as the second argument has just been opened. The third argument
2206 ** points to a buffer containing the name of the main database file. If the
2207 ** fourth parameter is 1, then the SQL statement that the third parameter
2208 ** points to has just been executed. Or, if the fourth parameter is 2, then
2209 ** the connection being passed as the second parameter is being closed. The
2210 ** third parameter is passed NULL In this case. An example of using this
2211 ** configuration option can be seen in the "test_sqllog.c" source file in
2212 ** the canonical SQLite source tree.</dd>
2214 ** [[SQLITE_CONFIG_MMAP_SIZE]]
2215 ** <dt>SQLITE_CONFIG_MMAP_SIZE
2216 ** <dd>SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2217 ** that are the default mmap size limit (the default setting for
2218 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2219 ** The default setting can be overridden by each database connection using
2220 ** either the [PRAGMA mmap_size] command, or by using the
2221 ** [SQLITE_FCNTL_MMAP_SIZE] file control. The maximum allowed mmap size
2222 ** cannot be changed at run-time. Nor may the maximum allowed mmap size
2223 ** exceed the compile-time maximum mmap size set by the
2224 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.
2225 ** If either argument to this option is negative, then that argument is
2226 ** changed to its compile-time default.
2227 ** </dl>
2229 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
2230 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
2231 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
2232 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
2233 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
2234 #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
2235 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
2236 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
2237 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
2238 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
2239 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
2240 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2241 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
2242 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
2243 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
2244 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
2245 #define SQLITE_CONFIG_URI 17 /* int */
2246 #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
2247 #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
2248 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
2249 #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
2250 #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
2253 ** CAPI3REF: Database Connection Configuration Options
2255 ** These constants are the available integer configuration options that
2256 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2258 ** New configuration options may be added in future releases of SQLite.
2259 ** Existing configuration options might be discontinued. Applications
2260 ** should check the return code from [sqlite3_db_config()] to make sure that
2261 ** the call worked. ^The [sqlite3_db_config()] interface will return a
2262 ** non-zero [error code] if a discontinued or unsupported configuration option
2263 ** is invoked.
2265 ** <dl>
2266 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2267 ** <dd> ^This option takes three additional arguments that determine the
2268 ** [lookaside memory allocator] configuration for the [database connection].
2269 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2270 ** pointer to a memory buffer to use for lookaside memory.
2271 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2272 ** may be NULL in which case SQLite will allocate the
2273 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2274 ** size of each lookaside buffer slot. ^The third argument is the number of
2275 ** slots. The size of the buffer in the first argument must be greater than
2276 ** or equal to the product of the second and third arguments. The buffer
2277 ** must be aligned to an 8-byte boundary. ^If the second argument to
2278 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2279 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
2280 ** configuration for a database connection can only be changed when that
2281 ** connection is not currently using lookaside memory, or in other words
2282 ** when the "current value" returned by
2283 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2284 ** Any attempt to change the lookaside memory configuration when lookaside
2285 ** memory is in use leaves the configuration unchanged and returns
2286 ** [SQLITE_BUSY].)^</dd>
2288 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2289 ** <dd> ^This option is used to enable or disable the enforcement of
2290 ** [foreign key constraints]. There should be two additional arguments.
2291 ** The first argument is an integer which is 0 to disable FK enforcement,
2292 ** positive to enable FK enforcement or negative to leave FK enforcement
2293 ** unchanged. The second parameter is a pointer to an integer into which
2294 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2295 ** following this call. The second parameter may be a NULL pointer, in
2296 ** which case the FK enforcement setting is not reported back. </dd>
2298 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2299 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2300 ** There should be two additional arguments.
2301 ** The first argument is an integer which is 0 to disable triggers,
2302 ** positive to enable triggers or negative to leave the setting unchanged.
2303 ** The second parameter is a pointer to an integer into which
2304 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2305 ** following this call. The second parameter may be a NULL pointer, in
2306 ** which case the trigger setting is not reported back. </dd>
2308 ** </dl>
2310 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2311 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2312 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2316 ** CAPI3REF: Enable Or Disable Extended Result Codes
2318 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2319 ** [extended result codes] feature of SQLite. ^The extended result
2320 ** codes are disabled by default for historical compatibility.
2322 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2325 ** CAPI3REF: Last Insert Rowid
2327 ** ^Each entry in an SQLite table has a unique 64-bit signed
2328 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2329 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2330 ** names are not also used by explicitly declared columns. ^If
2331 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2332 ** is another alias for the rowid.
2334 ** ^This routine returns the [rowid] of the most recent
2335 ** successful [INSERT] into the database from the [database connection]
2336 ** in the first argument. ^As of SQLite version 3.7.7, this routines
2337 ** records the last insert rowid of both ordinary tables and [virtual tables].
2338 ** ^If no successful [INSERT]s
2339 ** have ever occurred on that database connection, zero is returned.
2341 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2342 ** method, then this routine will return the [rowid] of the inserted
2343 ** row as long as the trigger or virtual table method is running.
2344 ** But once the trigger or virtual table method ends, the value returned
2345 ** by this routine reverts to what it was before the trigger or virtual
2346 ** table method began.)^
2348 ** ^An [INSERT] that fails due to a constraint violation is not a
2349 ** successful [INSERT] and does not change the value returned by this
2350 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2351 ** and INSERT OR ABORT make no changes to the return value of this
2352 ** routine when their insertion fails. ^(When INSERT OR REPLACE
2353 ** encounters a constraint violation, it does not fail. The
2354 ** INSERT continues to completion after deleting rows that caused
2355 ** the constraint problem so INSERT OR REPLACE will always change
2356 ** the return value of this interface.)^
2358 ** ^For the purposes of this routine, an [INSERT] is considered to
2359 ** be successful even if it is subsequently rolled back.
2361 ** This function is accessible to SQL statements via the
2362 ** [last_insert_rowid() SQL function].
2364 ** If a separate thread performs a new [INSERT] on the same
2365 ** database connection while the [sqlite3_last_insert_rowid()]
2366 ** function is running and thus changes the last insert [rowid],
2367 ** then the value returned by [sqlite3_last_insert_rowid()] is
2368 ** unpredictable and might not equal either the old or the new
2369 ** last insert [rowid].
2371 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2374 ** CAPI3REF: Count The Number Of Rows Modified
2376 ** ^This function returns the number of database rows that were changed
2377 ** or inserted or deleted by the most recently completed SQL statement
2378 ** on the [database connection] specified by the first parameter.
2379 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2380 ** or [DELETE] statement are counted. Auxiliary changes caused by
2381 ** triggers or [foreign key actions] are not counted.)^ Use the
2382 ** [sqlite3_total_changes()] function to find the total number of changes
2383 ** including changes caused by triggers and foreign key actions.
2385 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2386 ** are not counted. Only real table changes are counted.
2388 ** ^(A "row change" is a change to a single row of a single table
2389 ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
2390 ** are changed as side effects of [REPLACE] constraint resolution,
2391 ** rollback, ABORT processing, [DROP TABLE], or by any other
2392 ** mechanisms do not count as direct row changes.)^
2394 ** A "trigger context" is a scope of execution that begins and
2395 ** ends with the script of a [CREATE TRIGGER | trigger].
2396 ** Most SQL statements are
2397 ** evaluated outside of any trigger. This is the "top level"
2398 ** trigger context. If a trigger fires from the top level, a
2399 ** new trigger context is entered for the duration of that one
2400 ** trigger. Subtriggers create subcontexts for their duration.
2402 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2403 ** not create a new trigger context.
2405 ** ^This function returns the number of direct row changes in the
2406 ** most recent INSERT, UPDATE, or DELETE statement within the same
2407 ** trigger context.
2409 ** ^Thus, when called from the top level, this function returns the
2410 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2411 ** that also occurred at the top level. ^(Within the body of a trigger,
2412 ** the sqlite3_changes() interface can be called to find the number of
2413 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2414 ** statement within the body of the same trigger.
2415 ** However, the number returned does not include changes
2416 ** caused by subtriggers since those have their own context.)^
2418 ** See also the [sqlite3_total_changes()] interface, the
2419 ** [count_changes pragma], and the [changes() SQL function].
2421 ** If a separate thread makes changes on the same database connection
2422 ** while [sqlite3_changes()] is running then the value returned
2423 ** is unpredictable and not meaningful.
2425 SQLITE_API int sqlite3_changes(sqlite3*);
2428 ** CAPI3REF: Total Number Of Rows Modified
2430 ** ^This function returns the number of row changes caused by [INSERT],
2431 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2432 ** ^(The count returned by sqlite3_total_changes() includes all changes
2433 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2434 ** [foreign key actions]. However,
2435 ** the count does not include changes used to implement [REPLACE] constraints,
2436 ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
2437 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2438 ** though if the INSTEAD OF trigger makes changes of its own, those changes
2439 ** are counted.)^
2440 ** ^The sqlite3_total_changes() function counts the changes as soon as
2441 ** the statement that makes them is completed (when the statement handle
2442 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2444 ** See also the [sqlite3_changes()] interface, the
2445 ** [count_changes pragma], and the [total_changes() SQL function].
2447 ** If a separate thread makes changes on the same database connection
2448 ** while [sqlite3_total_changes()] is running then the value
2449 ** returned is unpredictable and not meaningful.
2451 SQLITE_API int sqlite3_total_changes(sqlite3*);
2454 ** CAPI3REF: Interrupt A Long-Running Query
2456 ** ^This function causes any pending database operation to abort and
2457 ** return at its earliest opportunity. This routine is typically
2458 ** called in response to a user action such as pressing "Cancel"
2459 ** or Ctrl-C where the user wants a long query operation to halt
2460 ** immediately.
2462 ** ^It is safe to call this routine from a thread different from the
2463 ** thread that is currently running the database operation. But it
2464 ** is not safe to call this routine with a [database connection] that
2465 ** is closed or might close before sqlite3_interrupt() returns.
2467 ** ^If an SQL operation is very nearly finished at the time when
2468 ** sqlite3_interrupt() is called, then it might not have an opportunity
2469 ** to be interrupted and might continue to completion.
2471 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2472 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2473 ** that is inside an explicit transaction, then the entire transaction
2474 ** will be rolled back automatically.
2476 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2477 ** SQL statements on [database connection] D complete. ^Any new SQL statements
2478 ** that are started after the sqlite3_interrupt() call and before the
2479 ** running statements reaches zero are interrupted as if they had been
2480 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
2481 ** that are started after the running statement count reaches zero are
2482 ** not effected by the sqlite3_interrupt().
2483 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2484 ** SQL statements is a no-op and has no effect on SQL statements
2485 ** that are started after the sqlite3_interrupt() call returns.
2487 ** If the database connection closes while [sqlite3_interrupt()]
2488 ** is running then bad things will likely happen.
2490 SQLITE_API void sqlite3_interrupt(sqlite3*);
2493 ** CAPI3REF: Determine If An SQL Statement Is Complete
2495 ** These routines are useful during command-line input to determine if the
2496 ** currently entered text seems to form a complete SQL statement or
2497 ** if additional input is needed before sending the text into
2498 ** SQLite for parsing. ^These routines return 1 if the input string
2499 ** appears to be a complete SQL statement. ^A statement is judged to be
2500 ** complete if it ends with a semicolon token and is not a prefix of a
2501 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2502 ** string literals or quoted identifier names or comments are not
2503 ** independent tokens (they are part of the token in which they are
2504 ** embedded) and thus do not count as a statement terminator. ^Whitespace
2505 ** and comments that follow the final semicolon are ignored.
2507 ** ^These routines return 0 if the statement is incomplete. ^If a
2508 ** memory allocation fails, then SQLITE_NOMEM is returned.
2510 ** ^These routines do not parse the SQL statements thus
2511 ** will not detect syntactically incorrect SQL.
2513 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2514 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2515 ** automatically by sqlite3_complete16(). If that initialization fails,
2516 ** then the return value from sqlite3_complete16() will be non-zero
2517 ** regardless of whether or not the input SQL is complete.)^
2519 ** The input to [sqlite3_complete()] must be a zero-terminated
2520 ** UTF-8 string.
2522 ** The input to [sqlite3_complete16()] must be a zero-terminated
2523 ** UTF-16 string in native byte order.
2525 SQLITE_API int sqlite3_complete(const char *sql);
2526 SQLITE_API int sqlite3_complete16(const void *sql);
2529 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2531 ** ^This routine sets a callback function that might be invoked whenever
2532 ** an attempt is made to open a database table that another thread
2533 ** or process has locked.
2535 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2536 ** is returned immediately upon encountering the lock. ^If the busy callback
2537 ** is not NULL, then the callback might be invoked with two arguments.
2539 ** ^The first argument to the busy handler is a copy of the void* pointer which
2540 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
2541 ** the busy handler callback is the number of times that the busy handler has
2542 ** been invoked for this locking event. ^If the
2543 ** busy callback returns 0, then no additional attempts are made to
2544 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2545 ** ^If the callback returns non-zero, then another attempt
2546 ** is made to open the database for reading and the cycle repeats.
2548 ** The presence of a busy handler does not guarantee that it will be invoked
2549 ** when there is lock contention. ^If SQLite determines that invoking the busy
2550 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2551 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2552 ** Consider a scenario where one process is holding a read lock that
2553 ** it is trying to promote to a reserved lock and
2554 ** a second process is holding a reserved lock that it is trying
2555 ** to promote to an exclusive lock. The first process cannot proceed
2556 ** because it is blocked by the second and the second process cannot
2557 ** proceed because it is blocked by the first. If both processes
2558 ** invoke the busy handlers, neither will make any progress. Therefore,
2559 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2560 ** will induce the first process to release its read lock and allow
2561 ** the second process to proceed.
2563 ** ^The default busy callback is NULL.
2565 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2566 ** when SQLite is in the middle of a large transaction where all the
2567 ** changes will not fit into the in-memory cache. SQLite will
2568 ** already hold a RESERVED lock on the database file, but it needs
2569 ** to promote this lock to EXCLUSIVE so that it can spill cache
2570 ** pages into the database file without harm to concurrent
2571 ** readers. ^If it is unable to promote the lock, then the in-memory
2572 ** cache will be left in an inconsistent state and so the error
2573 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2574 ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
2575 ** forces an automatic rollback of the changes. See the
2576 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2577 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2578 ** this is important.
2580 ** ^(There can only be a single busy handler defined for each
2581 ** [database connection]. Setting a new busy handler clears any
2582 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
2583 ** will also set or clear the busy handler.
2585 ** The busy callback should not take any actions which modify the
2586 ** database connection that invoked the busy handler. Any such actions
2587 ** result in undefined behavior.
2589 ** A busy handler must not close the database connection
2590 ** or [prepared statement] that invoked the busy handler.
2592 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2595 ** CAPI3REF: Set A Busy Timeout
2597 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2598 ** for a specified amount of time when a table is locked. ^The handler
2599 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2600 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
2601 ** the handler returns 0 which causes [sqlite3_step()] to return
2602 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2604 ** ^Calling this routine with an argument less than or equal to zero
2605 ** turns off all busy handlers.
2607 ** ^(There can only be a single busy handler for a particular
2608 ** [database connection] any any given moment. If another busy handler
2609 ** was defined (using [sqlite3_busy_handler()]) prior to calling
2610 ** this routine, that other busy handler is cleared.)^
2612 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2615 ** CAPI3REF: Convenience Routines For Running Queries
2617 ** This is a legacy interface that is preserved for backwards compatibility.
2618 ** Use of this interface is not recommended.
2620 ** Definition: A <b>result table</b> is memory data structure created by the
2621 ** [sqlite3_get_table()] interface. A result table records the
2622 ** complete query results from one or more queries.
2624 ** The table conceptually has a number of rows and columns. But
2625 ** these numbers are not part of the result table itself. These
2626 ** numbers are obtained separately. Let N be the number of rows
2627 ** and M be the number of columns.
2629 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2630 ** There are (N+1)*M elements in the array. The first M pointers point
2631 ** to zero-terminated strings that contain the names of the columns.
2632 ** The remaining entries all point to query results. NULL values result
2633 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
2634 ** string representation as returned by [sqlite3_column_text()].
2636 ** A result table might consist of one or more memory allocations.
2637 ** It is not safe to pass a result table directly to [sqlite3_free()].
2638 ** A result table should be deallocated using [sqlite3_free_table()].
2640 ** ^(As an example of the result table format, suppose a query result
2641 ** is as follows:
2643 ** <blockquote><pre>
2644 ** Name | Age
2645 ** -----------------------
2646 ** Alice | 43
2647 ** Bob | 28
2648 ** Cindy | 21
2649 ** </pre></blockquote>
2651 ** There are two column (M==2) and three rows (N==3). Thus the
2652 ** result table has 8 entries. Suppose the result table is stored
2653 ** in an array names azResult. Then azResult holds this content:
2655 ** <blockquote><pre>
2656 ** azResult&#91;0] = "Name";
2657 ** azResult&#91;1] = "Age";
2658 ** azResult&#91;2] = "Alice";
2659 ** azResult&#91;3] = "43";
2660 ** azResult&#91;4] = "Bob";
2661 ** azResult&#91;5] = "28";
2662 ** azResult&#91;6] = "Cindy";
2663 ** azResult&#91;7] = "21";
2664 ** </pre></blockquote>)^
2666 ** ^The sqlite3_get_table() function evaluates one or more
2667 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2668 ** string of its 2nd parameter and returns a result table to the
2669 ** pointer given in its 3rd parameter.
2671 ** After the application has finished with the result from sqlite3_get_table(),
2672 ** it must pass the result table pointer to sqlite3_free_table() in order to
2673 ** release the memory that was malloced. Because of the way the
2674 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2675 ** function must not try to call [sqlite3_free()] directly. Only
2676 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2678 ** The sqlite3_get_table() interface is implemented as a wrapper around
2679 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2680 ** to any internal data structures of SQLite. It uses only the public
2681 ** interface defined here. As a consequence, errors that occur in the
2682 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2683 ** reflected in subsequent calls to [sqlite3_errcode()] or
2684 ** [sqlite3_errmsg()].
2686 SQLITE_API int sqlite3_get_table(
2687 sqlite3 *db, /* An open database */
2688 const char *zSql, /* SQL to be evaluated */
2689 char ***pazResult, /* Results of the query */
2690 int *pnRow, /* Number of result rows written here */
2691 int *pnColumn, /* Number of result columns written here */
2692 char **pzErrmsg /* Error msg written here */
2694 SQLITE_API void sqlite3_free_table(char **result);
2697 ** CAPI3REF: Formatted String Printing Functions
2699 ** These routines are work-alikes of the "printf()" family of functions
2700 ** from the standard C library.
2702 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2703 ** results into memory obtained from [sqlite3_malloc()].
2704 ** The strings returned by these two routines should be
2705 ** released by [sqlite3_free()]. ^Both routines return a
2706 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2707 ** memory to hold the resulting string.
2709 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2710 ** the standard C library. The result is written into the
2711 ** buffer supplied as the second parameter whose size is given by
2712 ** the first parameter. Note that the order of the
2713 ** first two parameters is reversed from snprintf().)^ This is an
2714 ** historical accident that cannot be fixed without breaking
2715 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
2716 ** returns a pointer to its buffer instead of the number of
2717 ** characters actually written into the buffer.)^ We admit that
2718 ** the number of characters written would be a more useful return
2719 ** value but we cannot change the implementation of sqlite3_snprintf()
2720 ** now without breaking compatibility.
2722 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2723 ** guarantees that the buffer is always zero-terminated. ^The first
2724 ** parameter "n" is the total size of the buffer, including space for
2725 ** the zero terminator. So the longest string that can be completely
2726 ** written will be n-1 characters.
2728 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2730 ** These routines all implement some additional formatting
2731 ** options that are useful for constructing SQL statements.
2732 ** All of the usual printf() formatting options apply. In addition, there
2733 ** is are "%q", "%Q", and "%z" options.
2735 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2736 ** string from the argument list. But %q also doubles every '\'' character.
2737 ** %q is designed for use inside a string literal.)^ By doubling each '\''
2738 ** character it escapes that character and allows it to be inserted into
2739 ** the string.
2741 ** For example, assume the string variable zText contains text as follows:
2743 ** <blockquote><pre>
2744 ** char *zText = "It's a happy day!";
2745 ** </pre></blockquote>
2747 ** One can use this text in an SQL statement as follows:
2749 ** <blockquote><pre>
2750 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2751 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2752 ** sqlite3_free(zSQL);
2753 ** </pre></blockquote>
2755 ** Because the %q format string is used, the '\'' character in zText
2756 ** is escaped and the SQL generated is as follows:
2758 ** <blockquote><pre>
2759 ** INSERT INTO table1 VALUES('It''s a happy day!')
2760 ** </pre></blockquote>
2762 ** This is correct. Had we used %s instead of %q, the generated SQL
2763 ** would have looked like this:
2765 ** <blockquote><pre>
2766 ** INSERT INTO table1 VALUES('It's a happy day!');
2767 ** </pre></blockquote>
2769 ** This second example is an SQL syntax error. As a general rule you should
2770 ** always use %q instead of %s when inserting text into a string literal.
2772 ** ^(The %Q option works like %q except it also adds single quotes around
2773 ** the outside of the total string. Additionally, if the parameter in the
2774 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2775 ** single quotes).)^ So, for example, one could say:
2777 ** <blockquote><pre>
2778 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2779 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2780 ** sqlite3_free(zSQL);
2781 ** </pre></blockquote>
2783 ** The code above will render a correct SQL statement in the zSQL
2784 ** variable even if the zText variable is a NULL pointer.
2786 ** ^(The "%z" formatting option works like "%s" but with the
2787 ** addition that after the string has been read and copied into
2788 ** the result, [sqlite3_free()] is called on the input string.)^
2790 SQLITE_API char *sqlite3_mprintf(const char*,...);
2791 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2792 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2793 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2796 ** CAPI3REF: Memory Allocation Subsystem
2798 ** The SQLite core uses these three routines for all of its own
2799 ** internal memory allocation needs. "Core" in the previous sentence
2800 ** does not include operating-system specific VFS implementation. The
2801 ** Windows VFS uses native malloc() and free() for some operations.
2803 ** ^The sqlite3_malloc() routine returns a pointer to a block
2804 ** of memory at least N bytes in length, where N is the parameter.
2805 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2806 ** memory, it returns a NULL pointer. ^If the parameter N to
2807 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2808 ** a NULL pointer.
2810 ** ^Calling sqlite3_free() with a pointer previously returned
2811 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2812 ** that it might be reused. ^The sqlite3_free() routine is
2813 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
2814 ** to sqlite3_free() is harmless. After being freed, memory
2815 ** should neither be read nor written. Even reading previously freed
2816 ** memory might result in a segmentation fault or other severe error.
2817 ** Memory corruption, a segmentation fault, or other severe error
2818 ** might result if sqlite3_free() is called with a non-NULL pointer that
2819 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2821 ** ^(The sqlite3_realloc() interface attempts to resize a
2822 ** prior memory allocation to be at least N bytes, where N is the
2823 ** second parameter. The memory allocation to be resized is the first
2824 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2825 ** is a NULL pointer then its behavior is identical to calling
2826 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2827 ** ^If the second parameter to sqlite3_realloc() is zero or
2828 ** negative then the behavior is exactly the same as calling
2829 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2830 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2831 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2832 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2833 ** of the prior allocation are copied into the beginning of buffer returned
2834 ** by sqlite3_realloc() and the prior allocation is freed.
2835 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2836 ** is not freed.
2838 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2839 ** is always aligned to at least an 8 byte boundary, or to a
2840 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2841 ** option is used.
2843 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2844 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2845 ** implementation of these routines to be omitted. That capability
2846 ** is no longer provided. Only built-in memory allocators can be used.
2848 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2849 ** the system malloc() and free() directly when converting
2850 ** filenames between the UTF-8 encoding used by SQLite
2851 ** and whatever filename encoding is used by the particular Windows
2852 ** installation. Memory allocation errors were detected, but
2853 ** they were reported back as [SQLITE_CANTOPEN] or
2854 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2856 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2857 ** must be either NULL or else pointers obtained from a prior
2858 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2859 ** not yet been released.
2861 ** The application must not read or write any part of
2862 ** a block of memory after it has been released using
2863 ** [sqlite3_free()] or [sqlite3_realloc()].
2865 SQLITE_API void *sqlite3_malloc(int);
2866 SQLITE_API void *sqlite3_realloc(void*, int);
2867 SQLITE_API void sqlite3_free(void*);
2870 ** CAPI3REF: Memory Allocator Statistics
2872 ** SQLite provides these two interfaces for reporting on the status
2873 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2874 ** routines, which form the built-in memory allocation subsystem.
2876 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2877 ** of memory currently outstanding (malloced but not freed).
2878 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2879 ** value of [sqlite3_memory_used()] since the high-water mark
2880 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
2881 ** [sqlite3_memory_highwater()] include any overhead
2882 ** added by SQLite in its implementation of [sqlite3_malloc()],
2883 ** but not overhead added by the any underlying system library
2884 ** routines that [sqlite3_malloc()] may call.
2886 ** ^The memory high-water mark is reset to the current value of
2887 ** [sqlite3_memory_used()] if and only if the parameter to
2888 ** [sqlite3_memory_highwater()] is true. ^The value returned
2889 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2890 ** prior to the reset.
2892 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2893 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2896 ** CAPI3REF: Pseudo-Random Number Generator
2898 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2899 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2900 ** already uses the largest possible [ROWID]. The PRNG is also used for
2901 ** the build-in random() and randomblob() SQL functions. This interface allows
2902 ** applications to access the same PRNG for other purposes.
2904 ** ^A call to this routine stores N bytes of randomness into buffer P.
2906 ** ^The first time this routine is invoked (either internally or by
2907 ** the application) the PRNG is seeded using randomness obtained
2908 ** from the xRandomness method of the default [sqlite3_vfs] object.
2909 ** ^On all subsequent invocations, the pseudo-randomness is generated
2910 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2911 ** method.
2913 SQLITE_API void sqlite3_randomness(int N, void *P);
2916 ** CAPI3REF: Compile-Time Authorization Callbacks
2918 ** ^This routine registers an authorizer callback with a particular
2919 ** [database connection], supplied in the first argument.
2920 ** ^The authorizer callback is invoked as SQL statements are being compiled
2921 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2922 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
2923 ** points during the compilation process, as logic is being created
2924 ** to perform various actions, the authorizer callback is invoked to
2925 ** see if those actions are allowed. ^The authorizer callback should
2926 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2927 ** specific action but allow the SQL statement to continue to be
2928 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2929 ** rejected with an error. ^If the authorizer callback returns
2930 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2931 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2932 ** the authorizer will fail with an error message.
2934 ** When the callback returns [SQLITE_OK], that means the operation
2935 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
2936 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2937 ** authorizer will fail with an error message explaining that
2938 ** access is denied.
2940 ** ^The first parameter to the authorizer callback is a copy of the third
2941 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2942 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2943 ** the particular action to be authorized. ^The third through sixth parameters
2944 ** to the callback are zero-terminated strings that contain additional
2945 ** details about the action to be authorized.
2947 ** ^If the action code is [SQLITE_READ]
2948 ** and the callback returns [SQLITE_IGNORE] then the
2949 ** [prepared statement] statement is constructed to substitute
2950 ** a NULL value in place of the table column that would have
2951 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2952 ** return can be used to deny an untrusted user access to individual
2953 ** columns of a table.
2954 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2955 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2956 ** [truncate optimization] is disabled and all rows are deleted individually.
2958 ** An authorizer is used when [sqlite3_prepare | preparing]
2959 ** SQL statements from an untrusted source, to ensure that the SQL statements
2960 ** do not try to access data they are not allowed to see, or that they do not
2961 ** try to execute malicious statements that damage the database. For
2962 ** example, an application may allow a user to enter arbitrary
2963 ** SQL queries for evaluation by a database. But the application does
2964 ** not want the user to be able to make arbitrary changes to the
2965 ** database. An authorizer could then be put in place while the
2966 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2967 ** disallows everything except [SELECT] statements.
2969 ** Applications that need to process SQL from untrusted sources
2970 ** might also consider lowering resource limits using [sqlite3_limit()]
2971 ** and limiting database size using the [max_page_count] [PRAGMA]
2972 ** in addition to using an authorizer.
2974 ** ^(Only a single authorizer can be in place on a database connection
2975 ** at a time. Each call to sqlite3_set_authorizer overrides the
2976 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
2977 ** The authorizer is disabled by default.
2979 ** The authorizer callback must not do anything that will modify
2980 ** the database connection that invoked the authorizer callback.
2981 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2982 ** database connections for the meaning of "modify" in this paragraph.
2984 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2985 ** statement might be re-prepared during [sqlite3_step()] due to a
2986 ** schema change. Hence, the application should ensure that the
2987 ** correct authorizer callback remains in place during the [sqlite3_step()].
2989 ** ^Note that the authorizer callback is invoked only during
2990 ** [sqlite3_prepare()] or its variants. Authorization is not
2991 ** performed during statement evaluation in [sqlite3_step()], unless
2992 ** as stated in the previous paragraph, sqlite3_step() invokes
2993 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2995 SQLITE_API int sqlite3_set_authorizer(
2996 sqlite3*,
2997 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2998 void *pUserData
3002 ** CAPI3REF: Authorizer Return Codes
3004 ** The [sqlite3_set_authorizer | authorizer callback function] must
3005 ** return either [SQLITE_OK] or one of these two constants in order
3006 ** to signal SQLite whether or not the action is permitted. See the
3007 ** [sqlite3_set_authorizer | authorizer documentation] for additional
3008 ** information.
3010 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
3011 ** from the [sqlite3_vtab_on_conflict()] interface.
3013 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
3014 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
3017 ** CAPI3REF: Authorizer Action Codes
3019 ** The [sqlite3_set_authorizer()] interface registers a callback function
3020 ** that is invoked to authorize certain SQL statement actions. The
3021 ** second parameter to the callback is an integer code that specifies
3022 ** what action is being authorized. These are the integer action codes that
3023 ** the authorizer callback may be passed.
3025 ** These action code values signify what kind of operation is to be
3026 ** authorized. The 3rd and 4th parameters to the authorization
3027 ** callback function will be parameters or NULL depending on which of these
3028 ** codes is used as the second parameter. ^(The 5th parameter to the
3029 ** authorizer callback is the name of the database ("main", "temp",
3030 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
3031 ** is the name of the inner-most trigger or view that is responsible for
3032 ** the access attempt or NULL if this access attempt is directly from
3033 ** top-level SQL code.
3035 /******************************************* 3rd ************ 4th ***********/
3036 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
3037 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
3038 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
3039 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
3040 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
3041 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
3042 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
3043 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
3044 #define SQLITE_DELETE 9 /* Table Name NULL */
3045 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
3046 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
3047 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
3048 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
3049 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
3050 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
3051 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
3052 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
3053 #define SQLITE_INSERT 18 /* Table Name NULL */
3054 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
3055 #define SQLITE_READ 20 /* Table Name Column Name */
3056 #define SQLITE_SELECT 21 /* NULL NULL */
3057 #define SQLITE_TRANSACTION 22 /* Operation NULL */
3058 #define SQLITE_UPDATE 23 /* Table Name Column Name */
3059 #define SQLITE_ATTACH 24 /* Filename NULL */
3060 #define SQLITE_DETACH 25 /* Database Name NULL */
3061 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
3062 #define SQLITE_REINDEX 27 /* Index Name NULL */
3063 #define SQLITE_ANALYZE 28 /* Table Name NULL */
3064 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
3065 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3066 #define SQLITE_FUNCTION 31 /* NULL Function Name */
3067 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3068 #define SQLITE_COPY 0 /* No longer used */
3071 ** CAPI3REF: Tracing And Profiling Functions
3073 ** These routines register callback functions that can be used for
3074 ** tracing and profiling the execution of SQL statements.
3076 ** ^The callback function registered by sqlite3_trace() is invoked at
3077 ** various times when an SQL statement is being run by [sqlite3_step()].
3078 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3079 ** SQL statement text as the statement first begins executing.
3080 ** ^(Additional sqlite3_trace() callbacks might occur
3081 ** as each triggered subprogram is entered. The callbacks for triggers
3082 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3084 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3085 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
3087 ** ^The callback function registered by sqlite3_profile() is invoked
3088 ** as each SQL statement finishes. ^The profile callback contains
3089 ** the original statement text and an estimate of wall-clock time
3090 ** of how long that statement took to run. ^The profile callback
3091 ** time is in units of nanoseconds, however the current implementation
3092 ** is only capable of millisecond resolution so the six least significant
3093 ** digits in the time are meaningless. Future versions of SQLite
3094 ** might provide greater resolution on the profiler callback. The
3095 ** sqlite3_profile() function is considered experimental and is
3096 ** subject to change in future versions of SQLite.
3098 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
3099 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
3100 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3103 ** CAPI3REF: Query Progress Callbacks
3105 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3106 ** function X to be invoked periodically during long running calls to
3107 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3108 ** database connection D. An example use for this
3109 ** interface is to keep a GUI updated during a large query.
3111 ** ^The parameter P is passed through as the only parameter to the
3112 ** callback function X. ^The parameter N is the approximate number of
3113 ** [virtual machine instructions] that are evaluated between successive
3114 ** invocations of the callback X. ^If N is less than one then the progress
3115 ** handler is disabled.
3117 ** ^Only a single progress handler may be defined at one time per
3118 ** [database connection]; setting a new progress handler cancels the
3119 ** old one. ^Setting parameter X to NULL disables the progress handler.
3120 ** ^The progress handler is also disabled by setting N to a value less
3121 ** than 1.
3123 ** ^If the progress callback returns non-zero, the operation is
3124 ** interrupted. This feature can be used to implement a
3125 ** "Cancel" button on a GUI progress dialog box.
3127 ** The progress handler callback must not do anything that will modify
3128 ** the database connection that invoked the progress handler.
3129 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3130 ** database connections for the meaning of "modify" in this paragraph.
3133 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3136 ** CAPI3REF: Opening A New Database Connection
3138 ** ^These routines open an SQLite database file as specified by the
3139 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3140 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3141 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3142 ** returned in *ppDb, even if an error occurs. The only exception is that
3143 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3144 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3145 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3146 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
3147 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3148 ** an English language description of the error following a failure of any
3149 ** of the sqlite3_open() routines.
3151 ** ^The default encoding for the database will be UTF-8 if
3152 ** sqlite3_open() or sqlite3_open_v2() is called and
3153 ** UTF-16 in the native byte order if sqlite3_open16() is used.
3155 ** Whether or not an error occurs when it is opened, resources
3156 ** associated with the [database connection] handle should be released by
3157 ** passing it to [sqlite3_close()] when it is no longer required.
3159 ** The sqlite3_open_v2() interface works like sqlite3_open()
3160 ** except that it accepts two additional parameters for additional control
3161 ** over the new database connection. ^(The flags parameter to
3162 ** sqlite3_open_v2() can take one of
3163 ** the following three values, optionally combined with the
3164 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3165 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3167 ** <dl>
3168 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3169 ** <dd>The database is opened in read-only mode. If the database does not
3170 ** already exist, an error is returned.</dd>)^
3172 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3173 ** <dd>The database is opened for reading and writing if possible, or reading
3174 ** only if the file is write protected by the operating system. In either
3175 ** case the database must already exist, otherwise an error is returned.</dd>)^
3177 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3178 ** <dd>The database is opened for reading and writing, and is created if
3179 ** it does not already exist. This is the behavior that is always used for
3180 ** sqlite3_open() and sqlite3_open16().</dd>)^
3181 ** </dl>
3183 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3184 ** combinations shown above optionally combined with other
3185 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3186 ** then the behavior is undefined.
3188 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3189 ** opens in the multi-thread [threading mode] as long as the single-thread
3190 ** mode has not been set at compile-time or start-time. ^If the
3191 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3192 ** in the serialized [threading mode] unless single-thread was
3193 ** previously selected at compile-time or start-time.
3194 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3195 ** eligible to use [shared cache mode], regardless of whether or not shared
3196 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
3197 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3198 ** participate in [shared cache mode] even if it is enabled.
3200 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3201 ** [sqlite3_vfs] object that defines the operating system interface that
3202 ** the new database connection should use. ^If the fourth parameter is
3203 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3205 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3206 ** is created for the connection. ^This in-memory database will vanish when
3207 ** the database connection is closed. Future versions of SQLite might
3208 ** make use of additional special filenames that begin with the ":" character.
3209 ** It is recommended that when a database filename actually does begin with
3210 ** a ":" character you should prefix the filename with a pathname such as
3211 ** "./" to avoid ambiguity.
3213 ** ^If the filename is an empty string, then a private, temporary
3214 ** on-disk database will be created. ^This private database will be
3215 ** automatically deleted as soon as the database connection is closed.
3217 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3219 ** ^If [URI filename] interpretation is enabled, and the filename argument
3220 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3221 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3222 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3223 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3224 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3225 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3226 ** by default, but future releases of SQLite might enable URI filename
3227 ** interpretation by default. See "[URI filenames]" for additional
3228 ** information.
3230 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3231 ** authority, then it must be either an empty string or the string
3232 ** "localhost". ^If the authority is not an empty string or "localhost", an
3233 ** error is returned to the caller. ^The fragment component of a URI, if
3234 ** present, is ignored.
3236 ** ^SQLite uses the path component of the URI as the name of the disk file
3237 ** which contains the database. ^If the path begins with a '/' character,
3238 ** then it is interpreted as an absolute path. ^If the path does not begin
3239 ** with a '/' (meaning that the authority section is omitted from the URI)
3240 ** then the path is interpreted as a relative path.
3241 ** ^On windows, the first component of an absolute path
3242 ** is a drive specification (e.g. "C:").
3244 ** [[core URI query parameters]]
3245 ** The query component of a URI may contain parameters that are interpreted
3246 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3247 ** SQLite interprets the following three query parameters:
3249 ** <ul>
3250 ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3251 ** a VFS object that provides the operating system interface that should
3252 ** be used to access the database file on disk. ^If this option is set to
3253 ** an empty string the default VFS object is used. ^Specifying an unknown
3254 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3255 ** present, then the VFS specified by the option takes precedence over
3256 ** the value passed as the fourth parameter to sqlite3_open_v2().
3258 ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3259 ** "rwc", or "memory". Attempting to set it to any other value is
3260 ** an error)^.
3261 ** ^If "ro" is specified, then the database is opened for read-only
3262 ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3263 ** third argument to sqlite3_open_v2(). ^If the mode option is set to
3264 ** "rw", then the database is opened for read-write (but not create)
3265 ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3266 ** been set. ^Value "rwc" is equivalent to setting both
3267 ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
3268 ** set to "memory" then a pure [in-memory database] that never reads
3269 ** or writes from disk is used. ^It is an error to specify a value for
3270 ** the mode parameter that is less restrictive than that specified by
3271 ** the flags passed in the third parameter to sqlite3_open_v2().
3273 ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3274 ** "private". ^Setting it to "shared" is equivalent to setting the
3275 ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3276 ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3277 ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3278 ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3279 ** a URI filename, its value overrides any behavior requested by setting
3280 ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3281 ** </ul>
3283 ** ^Specifying an unknown parameter in the query component of a URI is not an
3284 ** error. Future versions of SQLite might understand additional query
3285 ** parameters. See "[query parameters with special meaning to SQLite]" for
3286 ** additional information.
3288 ** [[URI filename examples]] <h3>URI filename examples</h3>
3290 ** <table border="1" align=center cellpadding=5>
3291 ** <tr><th> URI filenames <th> Results
3292 ** <tr><td> file:data.db <td>
3293 ** Open the file "data.db" in the current directory.
3294 ** <tr><td> file:/home/fred/data.db<br>
3295 ** file:///home/fred/data.db <br>
3296 ** file://localhost/home/fred/data.db <br> <td>
3297 ** Open the database file "/home/fred/data.db".
3298 ** <tr><td> file://darkstar/home/fred/data.db <td>
3299 ** An error. "darkstar" is not a recognized authority.
3300 ** <tr><td style="white-space:nowrap">
3301 ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3302 ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
3303 ** C:. Note that the %20 escaping in this example is not strictly
3304 ** necessary - space characters can be used literally
3305 ** in URI filenames.
3306 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3307 ** Open file "data.db" in the current directory for read-only access.
3308 ** Regardless of whether or not shared-cache mode is enabled by
3309 ** default, use a private cache.
3310 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3311 ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3312 ** <tr><td> file:data.db?mode=readonly <td>
3313 ** An error. "readonly" is not a valid option for the "mode" parameter.
3314 ** </table>
3316 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3317 ** query components of a URI. A hexadecimal escape sequence consists of a
3318 ** percent sign - "%" - followed by exactly two hexadecimal digits
3319 ** specifying an octet value. ^Before the path or query components of a
3320 ** URI filename are interpreted, they are encoded using UTF-8 and all
3321 ** hexadecimal escape sequences replaced by a single byte containing the
3322 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3323 ** the results are undefined.
3325 ** <b>Note to Windows users:</b> The encoding used for the filename argument
3326 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3327 ** codepage is currently defined. Filenames containing international
3328 ** characters must be converted to UTF-8 prior to passing them into
3329 ** sqlite3_open() or sqlite3_open_v2().
3331 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
3332 ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
3333 ** features that require the use of temporary files may fail.
3335 ** See also: [sqlite3_temp_directory]
3337 SQLITE_API int sqlite3_open(
3338 const char *filename, /* Database filename (UTF-8) */
3339 sqlite3 **ppDb /* OUT: SQLite db handle */
3341 SQLITE_API int sqlite3_open16(
3342 const void *filename, /* Database filename (UTF-16) */
3343 sqlite3 **ppDb /* OUT: SQLite db handle */
3345 SQLITE_API int sqlite3_open_v2(
3346 const char *filename, /* Database filename (UTF-8) */
3347 sqlite3 **ppDb, /* OUT: SQLite db handle */
3348 int flags, /* Flags */
3349 const char *zVfs /* Name of VFS module to use */
3353 ** CAPI3REF: Obtain Values For URI Parameters
3355 ** These are utility routines, useful to VFS implementations, that check
3356 ** to see if a database file was a URI that contained a specific query
3357 ** parameter, and if so obtains the value of that query parameter.
3359 ** If F is the database filename pointer passed into the xOpen() method of
3360 ** a VFS implementation when the flags parameter to xOpen() has one or
3361 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3362 ** P is the name of the query parameter, then
3363 ** sqlite3_uri_parameter(F,P) returns the value of the P
3364 ** parameter if it exists or a NULL pointer if P does not appear as a
3365 ** query parameter on F. If P is a query parameter of F
3366 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3367 ** a pointer to an empty string.
3369 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3370 ** parameter and returns true (1) or false (0) according to the value
3371 ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3372 ** value of query parameter P is one of "yes", "true", or "on" in any
3373 ** case or if the value begins with a non-zero number. The
3374 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3375 ** query parameter P is one of "no", "false", or "off" in any case or
3376 ** if the value begins with a numeric zero. If P is not a query
3377 ** parameter on F or if the value of P is does not match any of the
3378 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3380 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3381 ** 64-bit signed integer and returns that integer, or D if P does not
3382 ** exist. If the value of P is something other than an integer, then
3383 ** zero is returned.
3385 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3386 ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
3387 ** is not a database file pathname pointer that SQLite passed into the xOpen
3388 ** VFS method, then the behavior of this routine is undefined and probably
3389 ** undesirable.
3391 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3392 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3393 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3397 ** CAPI3REF: Error Codes And Messages
3399 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3400 ** [extended result code] for the most recent failed sqlite3_* API call
3401 ** associated with a [database connection]. If a prior API call failed
3402 ** but the most recent API call succeeded, the return value from
3403 ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
3404 ** interface is the same except that it always returns the
3405 ** [extended result code] even when extended result codes are
3406 ** disabled.
3408 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3409 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3410 ** ^(Memory to hold the error message string is managed internally.
3411 ** The application does not need to worry about freeing the result.
3412 ** However, the error string might be overwritten or deallocated by
3413 ** subsequent calls to other SQLite interface functions.)^
3415 ** ^The sqlite3_errstr() interface returns the English-language text
3416 ** that describes the [result code], as UTF-8.
3417 ** ^(Memory to hold the error message string is managed internally
3418 ** and must not be freed by the application)^.
3420 ** When the serialized [threading mode] is in use, it might be the
3421 ** case that a second error occurs on a separate thread in between
3422 ** the time of the first error and the call to these interfaces.
3423 ** When that happens, the second error will be reported since these
3424 ** interfaces always report the most recent result. To avoid
3425 ** this, each thread can obtain exclusive use of the [database connection] D
3426 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3427 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3428 ** all calls to the interfaces listed here are completed.
3430 ** If an interface fails with SQLITE_MISUSE, that means the interface
3431 ** was invoked incorrectly by the application. In that case, the
3432 ** error code and message may or may not be set.
3434 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3435 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3436 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3437 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3438 SQLITE_API const char *sqlite3_errstr(int);
3441 ** CAPI3REF: SQL Statement Object
3442 ** KEYWORDS: {prepared statement} {prepared statements}
3444 ** An instance of this object represents a single SQL statement.
3445 ** This object is variously known as a "prepared statement" or a
3446 ** "compiled SQL statement" or simply as a "statement".
3448 ** The life of a statement object goes something like this:
3450 ** <ol>
3451 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3452 ** function.
3453 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3454 ** interfaces.
3455 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3456 ** <li> Reset the statement using [sqlite3_reset()] then go back
3457 ** to step 2. Do this zero or more times.
3458 ** <li> Destroy the object using [sqlite3_finalize()].
3459 ** </ol>
3461 ** Refer to documentation on individual methods above for additional
3462 ** information.
3464 typedef struct sqlite3_stmt sqlite3_stmt;
3467 ** CAPI3REF: Run-time Limits
3469 ** ^(This interface allows the size of various constructs to be limited
3470 ** on a connection by connection basis. The first parameter is the
3471 ** [database connection] whose limit is to be set or queried. The
3472 ** second parameter is one of the [limit categories] that define a
3473 ** class of constructs to be size limited. The third parameter is the
3474 ** new limit for that construct.)^
3476 ** ^If the new limit is a negative number, the limit is unchanged.
3477 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3478 ** [limits | hard upper bound]
3479 ** set at compile-time by a C preprocessor macro called
3480 ** [limits | SQLITE_MAX_<i>NAME</i>].
3481 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3482 ** ^Attempts to increase a limit above its hard upper bound are
3483 ** silently truncated to the hard upper bound.
3485 ** ^Regardless of whether or not the limit was changed, the
3486 ** [sqlite3_limit()] interface returns the prior value of the limit.
3487 ** ^Hence, to find the current value of a limit without changing it,
3488 ** simply invoke this interface with the third parameter set to -1.
3490 ** Run-time limits are intended for use in applications that manage
3491 ** both their own internal database and also databases that are controlled
3492 ** by untrusted external sources. An example application might be a
3493 ** web browser that has its own databases for storing history and
3494 ** separate databases controlled by JavaScript applications downloaded
3495 ** off the Internet. The internal databases can be given the
3496 ** large, default limits. Databases managed by external sources can
3497 ** be given much smaller limits designed to prevent a denial of service
3498 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
3499 ** interface to further control untrusted SQL. The size of the database
3500 ** created by an untrusted script can be contained using the
3501 ** [max_page_count] [PRAGMA].
3503 ** New run-time limit categories may be added in future releases.
3505 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3508 ** CAPI3REF: Run-Time Limit Categories
3509 ** KEYWORDS: {limit category} {*limit categories}
3511 ** These constants define various performance limits
3512 ** that can be lowered at run-time using [sqlite3_limit()].
3513 ** The synopsis of the meanings of the various limits is shown below.
3514 ** Additional information is available at [limits | Limits in SQLite].
3516 ** <dl>
3517 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3518 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3520 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3521 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3523 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3524 ** <dd>The maximum number of columns in a table definition or in the
3525 ** result set of a [SELECT] or the maximum number of columns in an index
3526 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3528 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3529 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3531 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3532 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3534 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3535 ** <dd>The maximum number of instructions in a virtual machine program
3536 ** used to implement an SQL statement. This limit is not currently
3537 ** enforced, though that might be added in some future release of
3538 ** SQLite.</dd>)^
3540 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3541 ** <dd>The maximum number of arguments on a function.</dd>)^
3543 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3544 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3546 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3547 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3548 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3549 ** [GLOB] operators.</dd>)^
3551 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3552 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3553 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3555 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3556 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3557 ** </dl>
3559 #define SQLITE_LIMIT_LENGTH 0
3560 #define SQLITE_LIMIT_SQL_LENGTH 1
3561 #define SQLITE_LIMIT_COLUMN 2
3562 #define SQLITE_LIMIT_EXPR_DEPTH 3
3563 #define SQLITE_LIMIT_COMPOUND_SELECT 4
3564 #define SQLITE_LIMIT_VDBE_OP 5
3565 #define SQLITE_LIMIT_FUNCTION_ARG 6
3566 #define SQLITE_LIMIT_ATTACHED 7
3567 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
3568 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
3569 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
3572 ** CAPI3REF: Compiling An SQL Statement
3573 ** KEYWORDS: {SQL statement compiler}
3575 ** To execute an SQL query, it must first be compiled into a byte-code
3576 ** program using one of these routines.
3578 ** The first argument, "db", is a [database connection] obtained from a
3579 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3580 ** [sqlite3_open16()]. The database connection must not have been closed.
3582 ** The second argument, "zSql", is the statement to be compiled, encoded
3583 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
3584 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3585 ** use UTF-16.
3587 ** ^If the nByte argument is less than zero, then zSql is read up to the
3588 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3589 ** number of bytes read from zSql. ^When nByte is non-negative, the
3590 ** zSql string ends at either the first '\000' or '\u0000' character or
3591 ** the nByte-th byte, whichever comes first. If the caller knows
3592 ** that the supplied string is nul-terminated, then there is a small
3593 ** performance advantage to be gained by passing an nByte parameter that
3594 ** is equal to the number of bytes in the input string <i>including</i>
3595 ** the nul-terminator bytes as this saves SQLite from having to
3596 ** make a copy of the input string.
3598 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3599 ** past the end of the first SQL statement in zSql. These routines only
3600 ** compile the first statement in zSql, so *pzTail is left pointing to
3601 ** what remains uncompiled.
3603 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3604 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
3605 ** to NULL. ^If the input text contains no SQL (if the input is an empty
3606 ** string or a comment) then *ppStmt is set to NULL.
3607 ** The calling procedure is responsible for deleting the compiled
3608 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3609 ** ppStmt may not be NULL.
3611 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3612 ** otherwise an [error code] is returned.
3614 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3615 ** recommended for all new programs. The two older interfaces are retained
3616 ** for backwards compatibility, but their use is discouraged.
3617 ** ^In the "v2" interfaces, the prepared statement
3618 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3619 ** original SQL text. This causes the [sqlite3_step()] interface to
3620 ** behave differently in three ways:
3622 ** <ol>
3623 ** <li>
3624 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3625 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3626 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3627 ** retries will occur before sqlite3_step() gives up and returns an error.
3628 ** </li>
3630 ** <li>
3631 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3632 ** [error codes] or [extended error codes]. ^The legacy behavior was that
3633 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3634 ** and the application would have to make a second call to [sqlite3_reset()]
3635 ** in order to find the underlying cause of the problem. With the "v2" prepare
3636 ** interfaces, the underlying reason for the error is returned immediately.
3637 ** </li>
3639 ** <li>
3640 ** ^If the specific value bound to [parameter | host parameter] in the
3641 ** WHERE clause might influence the choice of query plan for a statement,
3642 ** then the statement will be automatically recompiled, as if there had been
3643 ** a schema change, on the first [sqlite3_step()] call following any change
3644 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3645 ** ^The specific value of WHERE-clause [parameter] might influence the
3646 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3647 ** or [GLOB] operator or if the parameter is compared to an indexed column
3648 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3649 ** the
3650 ** </li>
3651 ** </ol>
3653 SQLITE_API int sqlite3_prepare(
3654 sqlite3 *db, /* Database handle */
3655 const char *zSql, /* SQL statement, UTF-8 encoded */
3656 int nByte, /* Maximum length of zSql in bytes. */
3657 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3658 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3660 SQLITE_API int sqlite3_prepare_v2(
3661 sqlite3 *db, /* Database handle */
3662 const char *zSql, /* SQL statement, UTF-8 encoded */
3663 int nByte, /* Maximum length of zSql in bytes. */
3664 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3665 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3667 SQLITE_API int sqlite3_prepare16(
3668 sqlite3 *db, /* Database handle */
3669 const void *zSql, /* SQL statement, UTF-16 encoded */
3670 int nByte, /* Maximum length of zSql in bytes. */
3671 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3672 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3674 SQLITE_API int sqlite3_prepare16_v2(
3675 sqlite3 *db, /* Database handle */
3676 const void *zSql, /* SQL statement, UTF-16 encoded */
3677 int nByte, /* Maximum length of zSql in bytes. */
3678 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3679 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3683 ** CAPI3REF: Retrieving Statement SQL
3685 ** ^This interface can be used to retrieve a saved copy of the original
3686 ** SQL text used to create a [prepared statement] if that statement was
3687 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3689 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3692 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3694 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3695 ** and only if the [prepared statement] X makes no direct changes to
3696 ** the content of the database file.
3698 ** Note that [application-defined SQL functions] or
3699 ** [virtual tables] might change the database indirectly as a side effect.
3700 ** ^(For example, if an application defines a function "eval()" that
3701 ** calls [sqlite3_exec()], then the following SQL statement would
3702 ** change the database file through side-effects:
3704 ** <blockquote><pre>
3705 ** SELECT eval('DELETE FROM t1') FROM t2;
3706 ** </pre></blockquote>
3708 ** But because the [SELECT] statement does not change the database file
3709 ** directly, sqlite3_stmt_readonly() would still return true.)^
3711 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3712 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3713 ** since the statements themselves do not actually modify the database but
3714 ** rather they control the timing of when other statements modify the
3715 ** database. ^The [ATTACH] and [DETACH] statements also cause
3716 ** sqlite3_stmt_readonly() to return true since, while those statements
3717 ** change the configuration of a database connection, they do not make
3718 ** changes to the content of the database files on disk.
3720 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3723 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3725 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3726 ** [prepared statement] S has been stepped at least once using
3727 ** [sqlite3_step(S)] but has not run to completion and/or has not
3728 ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
3729 ** interface returns false if S is a NULL pointer. If S is not a
3730 ** NULL pointer and is not a pointer to a valid [prepared statement]
3731 ** object, then the behavior is undefined and probably undesirable.
3733 ** This interface can be used in combination [sqlite3_next_stmt()]
3734 ** to locate all prepared statements associated with a database
3735 ** connection that are in need of being reset. This can be used,
3736 ** for example, in diagnostic routines to search for prepared
3737 ** statements that are holding a transaction open.
3739 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3742 ** CAPI3REF: Dynamically Typed Value Object
3743 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3745 ** SQLite uses the sqlite3_value object to represent all values
3746 ** that can be stored in a database table. SQLite uses dynamic typing
3747 ** for the values it stores. ^Values stored in sqlite3_value objects
3748 ** can be integers, floating point values, strings, BLOBs, or NULL.
3750 ** An sqlite3_value object may be either "protected" or "unprotected".
3751 ** Some interfaces require a protected sqlite3_value. Other interfaces
3752 ** will accept either a protected or an unprotected sqlite3_value.
3753 ** Every interface that accepts sqlite3_value arguments specifies
3754 ** whether or not it requires a protected sqlite3_value.
3756 ** The terms "protected" and "unprotected" refer to whether or not
3757 ** a mutex is held. An internal mutex is held for a protected
3758 ** sqlite3_value object but no mutex is held for an unprotected
3759 ** sqlite3_value object. If SQLite is compiled to be single-threaded
3760 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3761 ** or if SQLite is run in one of reduced mutex modes
3762 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3763 ** then there is no distinction between protected and unprotected
3764 ** sqlite3_value objects and they can be used interchangeably. However,
3765 ** for maximum code portability it is recommended that applications
3766 ** still make the distinction between protected and unprotected
3767 ** sqlite3_value objects even when not strictly required.
3769 ** ^The sqlite3_value objects that are passed as parameters into the
3770 ** implementation of [application-defined SQL functions] are protected.
3771 ** ^The sqlite3_value object returned by
3772 ** [sqlite3_column_value()] is unprotected.
3773 ** Unprotected sqlite3_value objects may only be used with
3774 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3775 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3776 ** interfaces require protected sqlite3_value objects.
3778 typedef struct Mem sqlite3_value;
3781 ** CAPI3REF: SQL Function Context Object
3783 ** The context in which an SQL function executes is stored in an
3784 ** sqlite3_context object. ^A pointer to an sqlite3_context object
3785 ** is always first parameter to [application-defined SQL functions].
3786 ** The application-defined SQL function implementation will pass this
3787 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3788 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3789 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3790 ** and/or [sqlite3_set_auxdata()].
3792 typedef struct sqlite3_context sqlite3_context;
3795 ** CAPI3REF: Binding Values To Prepared Statements
3796 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3797 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3799 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3800 ** literals may be replaced by a [parameter] that matches one of following
3801 ** templates:
3803 ** <ul>
3804 ** <li> ?
3805 ** <li> ?NNN
3806 ** <li> :VVV
3807 ** <li> @VVV
3808 ** <li> $VVV
3809 ** </ul>
3811 ** In the templates above, NNN represents an integer literal,
3812 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
3813 ** parameters (also called "host parameter names" or "SQL parameters")
3814 ** can be set using the sqlite3_bind_*() routines defined here.
3816 ** ^The first argument to the sqlite3_bind_*() routines is always
3817 ** a pointer to the [sqlite3_stmt] object returned from
3818 ** [sqlite3_prepare_v2()] or its variants.
3820 ** ^The second argument is the index of the SQL parameter to be set.
3821 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
3822 ** SQL parameter is used more than once, second and subsequent
3823 ** occurrences have the same index as the first occurrence.
3824 ** ^The index for named parameters can be looked up using the
3825 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
3826 ** for "?NNN" parameters is the value of NNN.
3827 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3828 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3830 ** ^The third argument is the value to bind to the parameter.
3831 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3832 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3833 ** is ignored and the end result is the same as sqlite3_bind_null().
3835 ** ^(In those routines that have a fourth argument, its value is the
3836 ** number of bytes in the parameter. To be clear: the value is the
3837 ** number of <u>bytes</u> in the value, not the number of characters.)^
3838 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3839 ** is negative, then the length of the string is
3840 ** the number of bytes up to the first zero terminator.
3841 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3842 ** the behavior is undefined.
3843 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3844 ** or sqlite3_bind_text16() then that parameter must be the byte offset
3845 ** where the NUL terminator would occur assuming the string were NUL
3846 ** terminated. If any NUL characters occur at byte offsets less than
3847 ** the value of the fourth parameter then the resulting string value will
3848 ** contain embedded NULs. The result of expressions involving strings
3849 ** with embedded NULs is undefined.
3851 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3852 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3853 ** string after SQLite has finished with it. ^The destructor is called
3854 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3855 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3856 ** ^If the fifth argument is
3857 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3858 ** information is in static, unmanaged space and does not need to be freed.
3859 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3860 ** SQLite makes its own private copy of the data immediately, before
3861 ** the sqlite3_bind_*() routine returns.
3863 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3864 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
3865 ** (just an integer to hold its size) while it is being processed.
3866 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3867 ** content is later written using
3868 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3869 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3871 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3872 ** for the [prepared statement] or with a prepared statement for which
3873 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3874 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
3875 ** routine is passed a [prepared statement] that has been finalized, the
3876 ** result is undefined and probably harmful.
3878 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3879 ** ^Unbound parameters are interpreted as NULL.
3881 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3882 ** [error code] if anything goes wrong.
3883 ** ^[SQLITE_RANGE] is returned if the parameter
3884 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
3886 ** See also: [sqlite3_bind_parameter_count()],
3887 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3889 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3890 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3891 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3892 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3893 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3894 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3895 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3896 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3897 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3900 ** CAPI3REF: Number Of SQL Parameters
3902 ** ^This routine can be used to find the number of [SQL parameters]
3903 ** in a [prepared statement]. SQL parameters are tokens of the
3904 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3905 ** placeholders for values that are [sqlite3_bind_blob | bound]
3906 ** to the parameters at a later time.
3908 ** ^(This routine actually returns the index of the largest (rightmost)
3909 ** parameter. For all forms except ?NNN, this will correspond to the
3910 ** number of unique parameters. If parameters of the ?NNN form are used,
3911 ** there may be gaps in the list.)^
3913 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3914 ** [sqlite3_bind_parameter_name()], and
3915 ** [sqlite3_bind_parameter_index()].
3917 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3920 ** CAPI3REF: Name Of A Host Parameter
3922 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3923 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3924 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3925 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3926 ** respectively.
3927 ** In other words, the initial ":" or "$" or "@" or "?"
3928 ** is included as part of the name.)^
3929 ** ^Parameters of the form "?" without a following integer have no name
3930 ** and are referred to as "nameless" or "anonymous parameters".
3932 ** ^The first host parameter has an index of 1, not 0.
3934 ** ^If the value N is out of range or if the N-th parameter is
3935 ** nameless, then NULL is returned. ^The returned string is
3936 ** always in UTF-8 encoding even if the named parameter was
3937 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3938 ** [sqlite3_prepare16_v2()].
3940 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3941 ** [sqlite3_bind_parameter_count()], and
3942 ** [sqlite3_bind_parameter_index()].
3944 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3947 ** CAPI3REF: Index Of A Parameter With A Given Name
3949 ** ^Return the index of an SQL parameter given its name. ^The
3950 ** index value returned is suitable for use as the second
3951 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
3952 ** is returned if no matching parameter is found. ^The parameter
3953 ** name must be given in UTF-8 even if the original statement
3954 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3956 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3957 ** [sqlite3_bind_parameter_count()], and
3958 ** [sqlite3_bind_parameter_index()].
3960 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3963 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3965 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3966 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3967 ** ^Use this routine to reset all host parameters to NULL.
3969 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3972 ** CAPI3REF: Number Of Columns In A Result Set
3974 ** ^Return the number of columns in the result set returned by the
3975 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3976 ** statement that does not return data (for example an [UPDATE]).
3978 ** See also: [sqlite3_data_count()]
3980 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3983 ** CAPI3REF: Column Names In A Result Set
3985 ** ^These routines return the name assigned to a particular column
3986 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
3987 ** interface returns a pointer to a zero-terminated UTF-8 string
3988 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3989 ** UTF-16 string. ^The first parameter is the [prepared statement]
3990 ** that implements the [SELECT] statement. ^The second parameter is the
3991 ** column number. ^The leftmost column is number 0.
3993 ** ^The returned string pointer is valid until either the [prepared statement]
3994 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3995 ** reprepared by the first call to [sqlite3_step()] for a particular run
3996 ** or until the next call to
3997 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3999 ** ^If sqlite3_malloc() fails during the processing of either routine
4000 ** (for example during a conversion from UTF-8 to UTF-16) then a
4001 ** NULL pointer is returned.
4003 ** ^The name of a result column is the value of the "AS" clause for
4004 ** that column, if there is an AS clause. If there is no AS clause
4005 ** then the name of the column is unspecified and may change from
4006 ** one release of SQLite to the next.
4008 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
4009 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
4012 ** CAPI3REF: Source Of Data In A Query Result
4014 ** ^These routines provide a means to determine the database, table, and
4015 ** table column that is the origin of a particular result column in
4016 ** [SELECT] statement.
4017 ** ^The name of the database or table or column can be returned as
4018 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
4019 ** the database name, the _table_ routines return the table name, and
4020 ** the origin_ routines return the column name.
4021 ** ^The returned string is valid until the [prepared statement] is destroyed
4022 ** using [sqlite3_finalize()] or until the statement is automatically
4023 ** reprepared by the first call to [sqlite3_step()] for a particular run
4024 ** or until the same information is requested
4025 ** again in a different encoding.
4027 ** ^The names returned are the original un-aliased names of the
4028 ** database, table, and column.
4030 ** ^The first argument to these interfaces is a [prepared statement].
4031 ** ^These functions return information about the Nth result column returned by
4032 ** the statement, where N is the second function argument.
4033 ** ^The left-most column is column 0 for these routines.
4035 ** ^If the Nth column returned by the statement is an expression or
4036 ** subquery and is not a column value, then all of these functions return
4037 ** NULL. ^These routine might also return NULL if a memory allocation error
4038 ** occurs. ^Otherwise, they return the name of the attached database, table,
4039 ** or column that query result column was extracted from.
4041 ** ^As with all other SQLite APIs, those whose names end with "16" return
4042 ** UTF-16 encoded strings and the other functions return UTF-8.
4044 ** ^These APIs are only available if the library was compiled with the
4045 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4047 ** If two or more threads call one or more of these routines against the same
4048 ** prepared statement and column at the same time then the results are
4049 ** undefined.
4051 ** If two or more threads call one or more
4052 ** [sqlite3_column_database_name | column metadata interfaces]
4053 ** for the same [prepared statement] and result column
4054 ** at the same time then the results are undefined.
4056 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
4057 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
4058 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
4059 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
4060 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
4061 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
4064 ** CAPI3REF: Declared Datatype Of A Query Result
4066 ** ^(The first parameter is a [prepared statement].
4067 ** If this statement is a [SELECT] statement and the Nth column of the
4068 ** returned result set of that [SELECT] is a table column (not an
4069 ** expression or subquery) then the declared type of the table
4070 ** column is returned.)^ ^If the Nth column of the result set is an
4071 ** expression or subquery, then a NULL pointer is returned.
4072 ** ^The returned string is always UTF-8 encoded.
4074 ** ^(For example, given the database schema:
4076 ** CREATE TABLE t1(c1 VARIANT);
4078 ** and the following statement to be compiled:
4080 ** SELECT c1 + 1, c1 FROM t1;
4082 ** this routine would return the string "VARIANT" for the second result
4083 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
4085 ** ^SQLite uses dynamic run-time typing. ^So just because a column
4086 ** is declared to contain a particular type does not mean that the
4087 ** data stored in that column is of the declared type. SQLite is
4088 ** strongly typed, but the typing is dynamic not static. ^Type
4089 ** is associated with individual values, not with the containers
4090 ** used to hold those values.
4092 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
4093 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
4096 ** CAPI3REF: Evaluate An SQL Statement
4098 ** After a [prepared statement] has been prepared using either
4099 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4100 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4101 ** must be called one or more times to evaluate the statement.
4103 ** The details of the behavior of the sqlite3_step() interface depend
4104 ** on whether the statement was prepared using the newer "v2" interface
4105 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4106 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
4107 ** new "v2" interface is recommended for new applications but the legacy
4108 ** interface will continue to be supported.
4110 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4111 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4112 ** ^With the "v2" interface, any of the other [result codes] or
4113 ** [extended result codes] might be returned as well.
4115 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4116 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
4117 ** or occurs outside of an explicit transaction, then you can retry the
4118 ** statement. If the statement is not a [COMMIT] and occurs within an
4119 ** explicit transaction then you should rollback the transaction before
4120 ** continuing.
4122 ** ^[SQLITE_DONE] means that the statement has finished executing
4123 ** successfully. sqlite3_step() should not be called again on this virtual
4124 ** machine without first calling [sqlite3_reset()] to reset the virtual
4125 ** machine back to its initial state.
4127 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4128 ** is returned each time a new row of data is ready for processing by the
4129 ** caller. The values may be accessed using the [column access functions].
4130 ** sqlite3_step() is called again to retrieve the next row of data.
4132 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4133 ** violation) has occurred. sqlite3_step() should not be called again on
4134 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4135 ** ^With the legacy interface, a more specific error code (for example,
4136 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4137 ** can be obtained by calling [sqlite3_reset()] on the
4138 ** [prepared statement]. ^In the "v2" interface,
4139 ** the more specific error code is returned directly by sqlite3_step().
4141 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4142 ** Perhaps it was called on a [prepared statement] that has
4143 ** already been [sqlite3_finalize | finalized] or on one that had
4144 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
4145 ** be the case that the same database connection is being used by two or
4146 ** more threads at the same moment in time.
4148 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4149 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4150 ** other than [SQLITE_ROW] before any subsequent invocation of
4151 ** sqlite3_step(). Failure to reset the prepared statement using
4152 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4153 ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
4154 ** calling [sqlite3_reset()] automatically in this circumstance rather
4155 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
4156 ** break because any application that ever receives an SQLITE_MISUSE error
4157 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
4158 ** can be used to restore the legacy behavior.
4160 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4161 ** API always returns a generic error code, [SQLITE_ERROR], following any
4162 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
4163 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4164 ** specific [error codes] that better describes the error.
4165 ** We admit that this is a goofy design. The problem has been fixed
4166 ** with the "v2" interface. If you prepare all of your SQL statements
4167 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4168 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4169 ** then the more specific [error codes] are returned directly
4170 ** by sqlite3_step(). The use of the "v2" interface is recommended.
4172 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4175 ** CAPI3REF: Number of columns in a result set
4177 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4178 ** current row of the result set of [prepared statement] P.
4179 ** ^If prepared statement P does not have results ready to return
4180 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4181 ** interfaces) then sqlite3_data_count(P) returns 0.
4182 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4183 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4184 ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
4185 ** will return non-zero if previous call to [sqlite3_step](P) returned
4186 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4187 ** where it always returns zero since each step of that multi-step
4188 ** pragma returns 0 columns of data.
4190 ** See also: [sqlite3_column_count()]
4192 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4195 ** CAPI3REF: Fundamental Datatypes
4196 ** KEYWORDS: SQLITE_TEXT
4198 ** ^(Every value in SQLite has one of five fundamental datatypes:
4200 ** <ul>
4201 ** <li> 64-bit signed integer
4202 ** <li> 64-bit IEEE floating point number
4203 ** <li> string
4204 ** <li> BLOB
4205 ** <li> NULL
4206 ** </ul>)^
4208 ** These constants are codes for each of those types.
4210 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4211 ** for a completely different meaning. Software that links against both
4212 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4213 ** SQLITE_TEXT.
4215 #define SQLITE_INTEGER 1
4216 #define SQLITE_FLOAT 2
4217 #define SQLITE_BLOB 4
4218 #define SQLITE_NULL 5
4219 #ifdef SQLITE_TEXT
4220 # undef SQLITE_TEXT
4221 #else
4222 # define SQLITE_TEXT 3
4223 #endif
4224 #define SQLITE3_TEXT 3
4227 ** CAPI3REF: Result Values From A Query
4228 ** KEYWORDS: {column access functions}
4230 ** These routines form the "result set" interface.
4232 ** ^These routines return information about a single column of the current
4233 ** result row of a query. ^In every case the first argument is a pointer
4234 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4235 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4236 ** and the second argument is the index of the column for which information
4237 ** should be returned. ^The leftmost column of the result set has the index 0.
4238 ** ^The number of columns in the result can be determined using
4239 ** [sqlite3_column_count()].
4241 ** If the SQL statement does not currently point to a valid row, or if the
4242 ** column index is out of range, the result is undefined.
4243 ** These routines may only be called when the most recent call to
4244 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4245 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4246 ** If any of these routines are called after [sqlite3_reset()] or
4247 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4248 ** something other than [SQLITE_ROW], the results are undefined.
4249 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4250 ** are called from a different thread while any of these routines
4251 ** are pending, then the results are undefined.
4253 ** ^The sqlite3_column_type() routine returns the
4254 ** [SQLITE_INTEGER | datatype code] for the initial data type
4255 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
4256 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
4257 ** returned by sqlite3_column_type() is only meaningful if no type
4258 ** conversions have occurred as described below. After a type conversion,
4259 ** the value returned by sqlite3_column_type() is undefined. Future
4260 ** versions of SQLite may change the behavior of sqlite3_column_type()
4261 ** following a type conversion.
4263 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4264 ** routine returns the number of bytes in that BLOB or string.
4265 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4266 ** the string to UTF-8 and then returns the number of bytes.
4267 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4268 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4269 ** the number of bytes in that string.
4270 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4272 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4273 ** routine returns the number of bytes in that BLOB or string.
4274 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4275 ** the string to UTF-16 and then returns the number of bytes.
4276 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4277 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4278 ** the number of bytes in that string.
4279 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4281 ** ^The values returned by [sqlite3_column_bytes()] and
4282 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4283 ** of the string. ^For clarity: the values returned by
4284 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4285 ** bytes in the string, not the number of characters.
4287 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4288 ** even empty strings, are always zero-terminated. ^The return
4289 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4291 ** ^The object returned by [sqlite3_column_value()] is an
4292 ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
4293 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4294 ** If the [unprotected sqlite3_value] object returned by
4295 ** [sqlite3_column_value()] is used in any other way, including calls
4296 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4297 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4299 ** These routines attempt to convert the value where appropriate. ^For
4300 ** example, if the internal representation is FLOAT and a text result
4301 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4302 ** conversion automatically. ^(The following table details the conversions
4303 ** that are applied:
4305 ** <blockquote>
4306 ** <table border="1">
4307 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
4309 ** <tr><td> NULL <td> INTEGER <td> Result is 0
4310 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
4311 ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
4312 ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
4313 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
4314 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
4315 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
4316 ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
4317 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
4318 ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
4319 ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
4320 ** <tr><td> TEXT <td> FLOAT <td> Use atof()
4321 ** <tr><td> TEXT <td> BLOB <td> No change
4322 ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
4323 ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
4324 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
4325 ** </table>
4326 ** </blockquote>)^
4328 ** The table above makes reference to standard C library functions atoi()
4329 ** and atof(). SQLite does not really use these functions. It has its
4330 ** own equivalent internal routines. The atoi() and atof() names are
4331 ** used in the table for brevity and because they are familiar to most
4332 ** C programmers.
4334 ** Note that when type conversions occur, pointers returned by prior
4335 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4336 ** sqlite3_column_text16() may be invalidated.
4337 ** Type conversions and pointer invalidations might occur
4338 ** in the following cases:
4340 ** <ul>
4341 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4342 ** sqlite3_column_text16() is called. A zero-terminator might
4343 ** need to be added to the string.</li>
4344 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4345 ** sqlite3_column_text16() is called. The content must be converted
4346 ** to UTF-16.</li>
4347 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4348 ** sqlite3_column_text() is called. The content must be converted
4349 ** to UTF-8.</li>
4350 ** </ul>
4352 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4353 ** not invalidate a prior pointer, though of course the content of the buffer
4354 ** that the prior pointer references will have been modified. Other kinds
4355 ** of conversion are done in place when it is possible, but sometimes they
4356 ** are not possible and in those cases prior pointers are invalidated.
4358 ** The safest and easiest to remember policy is to invoke these routines
4359 ** in one of the following ways:
4361 ** <ul>
4362 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4363 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4364 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4365 ** </ul>
4367 ** In other words, you should call sqlite3_column_text(),
4368 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4369 ** into the desired format, then invoke sqlite3_column_bytes() or
4370 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
4371 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4372 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4373 ** with calls to sqlite3_column_bytes().
4375 ** ^The pointers returned are valid until a type conversion occurs as
4376 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4377 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
4378 ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
4379 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4380 ** [sqlite3_free()].
4382 ** ^(If a memory allocation error occurs during the evaluation of any
4383 ** of these routines, a default value is returned. The default value
4384 ** is either the integer 0, the floating point number 0.0, or a NULL
4385 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
4386 ** [SQLITE_NOMEM].)^
4388 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4389 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4390 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4391 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4392 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4393 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4394 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4395 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4396 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4397 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4400 ** CAPI3REF: Destroy A Prepared Statement Object
4402 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4403 ** ^If the most recent evaluation of the statement encountered no errors
4404 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4405 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
4406 ** sqlite3_finalize(S) returns the appropriate [error code] or
4407 ** [extended error code].
4409 ** ^The sqlite3_finalize(S) routine can be called at any point during
4410 ** the life cycle of [prepared statement] S:
4411 ** before statement S is ever evaluated, after
4412 ** one or more calls to [sqlite3_reset()], or after any call
4413 ** to [sqlite3_step()] regardless of whether or not the statement has
4414 ** completed execution.
4416 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4418 ** The application must finalize every [prepared statement] in order to avoid
4419 ** resource leaks. It is a grievous error for the application to try to use
4420 ** a prepared statement after it has been finalized. Any use of a prepared
4421 ** statement after it has been finalized can result in undefined and
4422 ** undesirable behavior such as segfaults and heap corruption.
4424 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4427 ** CAPI3REF: Reset A Prepared Statement Object
4429 ** The sqlite3_reset() function is called to reset a [prepared statement]
4430 ** object back to its initial state, ready to be re-executed.
4431 ** ^Any SQL statement variables that had values bound to them using
4432 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4433 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4435 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4436 ** back to the beginning of its program.
4438 ** ^If the most recent call to [sqlite3_step(S)] for the
4439 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4440 ** or if [sqlite3_step(S)] has never before been called on S,
4441 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4443 ** ^If the most recent call to [sqlite3_step(S)] for the
4444 ** [prepared statement] S indicated an error, then
4445 ** [sqlite3_reset(S)] returns an appropriate [error code].
4447 ** ^The [sqlite3_reset(S)] interface does not change the values
4448 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4450 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4453 ** CAPI3REF: Create Or Redefine SQL Functions
4454 ** KEYWORDS: {function creation routines}
4455 ** KEYWORDS: {application-defined SQL function}
4456 ** KEYWORDS: {application-defined SQL functions}
4458 ** ^These functions (collectively known as "function creation routines")
4459 ** are used to add SQL functions or aggregates or to redefine the behavior
4460 ** of existing SQL functions or aggregates. The only differences between
4461 ** these routines are the text encoding expected for
4462 ** the second parameter (the name of the function being created)
4463 ** and the presence or absence of a destructor callback for
4464 ** the application data pointer.
4466 ** ^The first parameter is the [database connection] to which the SQL
4467 ** function is to be added. ^If an application uses more than one database
4468 ** connection then application-defined SQL functions must be added
4469 ** to each database connection separately.
4471 ** ^The second parameter is the name of the SQL function to be created or
4472 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
4473 ** representation, exclusive of the zero-terminator. ^Note that the name
4474 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4475 ** ^Any attempt to create a function with a longer name
4476 ** will result in [SQLITE_MISUSE] being returned.
4478 ** ^The third parameter (nArg)
4479 ** is the number of arguments that the SQL function or
4480 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4481 ** aggregate may take any number of arguments between 0 and the limit
4482 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
4483 ** parameter is less than -1 or greater than 127 then the behavior is
4484 ** undefined.
4486 ** ^The fourth parameter, eTextRep, specifies what
4487 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4488 ** its parameters. Every SQL function implementation must be able to work
4489 ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
4490 ** more efficient with one encoding than another. ^An application may
4491 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4492 ** times with the same function but with different values of eTextRep.
4493 ** ^When multiple implementations of the same function are available, SQLite
4494 ** will pick the one that involves the least amount of data conversion.
4495 ** If there is only a single implementation which does not care what text
4496 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4498 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
4499 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4501 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4502 ** pointers to C-language functions that implement the SQL function or
4503 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4504 ** callback only; NULL pointers must be passed as the xStep and xFinal
4505 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4506 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4507 ** SQL function or aggregate, pass NULL pointers for all three function
4508 ** callbacks.
4510 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4511 ** then it is destructor for the application data pointer.
4512 ** The destructor is invoked when the function is deleted, either by being
4513 ** overloaded or when the database connection closes.)^
4514 ** ^The destructor is also invoked if the call to
4515 ** sqlite3_create_function_v2() fails.
4516 ** ^When the destructor callback of the tenth parameter is invoked, it
4517 ** is passed a single argument which is a copy of the application data
4518 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4520 ** ^It is permitted to register multiple implementations of the same
4521 ** functions with the same name but with either differing numbers of
4522 ** arguments or differing preferred text encodings. ^SQLite will use
4523 ** the implementation that most closely matches the way in which the
4524 ** SQL function is used. ^A function implementation with a non-negative
4525 ** nArg parameter is a better match than a function implementation with
4526 ** a negative nArg. ^A function where the preferred text encoding
4527 ** matches the database encoding is a better
4528 ** match than a function where the encoding is different.
4529 ** ^A function where the encoding difference is between UTF16le and UTF16be
4530 ** is a closer match than a function where the encoding difference is
4531 ** between UTF8 and UTF16.
4533 ** ^Built-in functions may be overloaded by new application-defined functions.
4535 ** ^An application-defined function is permitted to call other
4536 ** SQLite interfaces. However, such calls must not
4537 ** close the database connection nor finalize or reset the prepared
4538 ** statement in which the function is running.
4540 SQLITE_API int sqlite3_create_function(
4541 sqlite3 *db,
4542 const char *zFunctionName,
4543 int nArg,
4544 int eTextRep,
4545 void *pApp,
4546 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4547 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4548 void (*xFinal)(sqlite3_context*)
4550 SQLITE_API int sqlite3_create_function16(
4551 sqlite3 *db,
4552 const void *zFunctionName,
4553 int nArg,
4554 int eTextRep,
4555 void *pApp,
4556 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4557 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4558 void (*xFinal)(sqlite3_context*)
4560 SQLITE_API int sqlite3_create_function_v2(
4561 sqlite3 *db,
4562 const char *zFunctionName,
4563 int nArg,
4564 int eTextRep,
4565 void *pApp,
4566 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4567 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4568 void (*xFinal)(sqlite3_context*),
4569 void(*xDestroy)(void*)
4573 ** CAPI3REF: Text Encodings
4575 ** These constant define integer codes that represent the various
4576 ** text encodings supported by SQLite.
4578 #define SQLITE_UTF8 1
4579 #define SQLITE_UTF16LE 2
4580 #define SQLITE_UTF16BE 3
4581 #define SQLITE_UTF16 4 /* Use native byte order */
4582 #define SQLITE_ANY 5 /* sqlite3_create_function only */
4583 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
4586 ** CAPI3REF: Deprecated Functions
4587 ** DEPRECATED
4589 ** These functions are [deprecated]. In order to maintain
4590 ** backwards compatibility with older code, these functions continue
4591 ** to be supported. However, new applications should avoid
4592 ** the use of these functions. To help encourage people to avoid
4593 ** using these functions, we are not going to tell you what they do.
4595 #ifndef SQLITE_OMIT_DEPRECATED
4596 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4597 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4598 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4599 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4600 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4601 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4602 void*,sqlite3_int64);
4603 #endif
4606 ** CAPI3REF: Obtaining SQL Function Parameter Values
4608 ** The C-language implementation of SQL functions and aggregates uses
4609 ** this set of interface routines to access the parameter values on
4610 ** the function or aggregate.
4612 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4613 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4614 ** define callbacks that implement the SQL functions and aggregates.
4615 ** The 3rd parameter to these callbacks is an array of pointers to
4616 ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
4617 ** each parameter to the SQL function. These routines are used to
4618 ** extract values from the [sqlite3_value] objects.
4620 ** These routines work only with [protected sqlite3_value] objects.
4621 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4622 ** object results in undefined behavior.
4624 ** ^These routines work just like the corresponding [column access functions]
4625 ** except that these routines take a single [protected sqlite3_value] object
4626 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4628 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4629 ** in the native byte-order of the host machine. ^The
4630 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4631 ** extract UTF-16 strings as big-endian and little-endian respectively.
4633 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4634 ** numeric affinity to the value. This means that an attempt is
4635 ** made to convert the value to an integer or floating point. If
4636 ** such a conversion is possible without loss of information (in other
4637 ** words, if the value is a string that looks like a number)
4638 ** then the conversion is performed. Otherwise no conversion occurs.
4639 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4641 ** Please pay particular attention to the fact that the pointer returned
4642 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4643 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4644 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4645 ** or [sqlite3_value_text16()].
4647 ** These routines must be called from the same thread as
4648 ** the SQL function that supplied the [sqlite3_value*] parameters.
4650 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4651 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4652 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4653 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4654 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4655 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4656 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4657 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4658 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4659 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4660 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4661 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4664 ** CAPI3REF: Obtain Aggregate Function Context
4666 ** Implementations of aggregate SQL functions use this
4667 ** routine to allocate memory for storing their state.
4669 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4670 ** for a particular aggregate function, SQLite
4671 ** allocates N of memory, zeroes out that memory, and returns a pointer
4672 ** to the new memory. ^On second and subsequent calls to
4673 ** sqlite3_aggregate_context() for the same aggregate function instance,
4674 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
4675 ** called once for each invocation of the xStep callback and then one
4676 ** last time when the xFinal callback is invoked. ^(When no rows match
4677 ** an aggregate query, the xStep() callback of the aggregate function
4678 ** implementation is never called and xFinal() is called exactly once.
4679 ** In those cases, sqlite3_aggregate_context() might be called for the
4680 ** first time from within xFinal().)^
4682 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4683 ** when first called if N is less than or equal to zero or if a memory
4684 ** allocate error occurs.
4686 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4687 ** determined by the N parameter on first successful call. Changing the
4688 ** value of N in subsequent call to sqlite3_aggregate_context() within
4689 ** the same aggregate function instance will not resize the memory
4690 ** allocation.)^ Within the xFinal callback, it is customary to set
4691 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4692 ** pointless memory allocations occur.
4694 ** ^SQLite automatically frees the memory allocated by
4695 ** sqlite3_aggregate_context() when the aggregate query concludes.
4697 ** The first parameter must be a copy of the
4698 ** [sqlite3_context | SQL function context] that is the first parameter
4699 ** to the xStep or xFinal callback routine that implements the aggregate
4700 ** function.
4702 ** This routine must be called from the same thread in which
4703 ** the aggregate SQL function is running.
4705 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4708 ** CAPI3REF: User Data For Functions
4710 ** ^The sqlite3_user_data() interface returns a copy of
4711 ** the pointer that was the pUserData parameter (the 5th parameter)
4712 ** of the [sqlite3_create_function()]
4713 ** and [sqlite3_create_function16()] routines that originally
4714 ** registered the application defined function.
4716 ** This routine must be called from the same thread in which
4717 ** the application-defined function is running.
4719 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4722 ** CAPI3REF: Database Connection For Functions
4724 ** ^The sqlite3_context_db_handle() interface returns a copy of
4725 ** the pointer to the [database connection] (the 1st parameter)
4726 ** of the [sqlite3_create_function()]
4727 ** and [sqlite3_create_function16()] routines that originally
4728 ** registered the application defined function.
4730 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4733 ** CAPI3REF: Function Auxiliary Data
4735 ** These functions may be used by (non-aggregate) SQL functions to
4736 ** associate metadata with argument values. If the same value is passed to
4737 ** multiple invocations of the same SQL function during query execution, under
4738 ** some circumstances the associated metadata may be preserved. An example
4739 ** of where this might be useful is in a regular-expression matching
4740 ** function. The compiled version of the regular expression can be stored as
4741 ** metadata associated with the pattern string.
4742 ** Then as long as the pattern string remains the same,
4743 ** the compiled regular expression can be reused on multiple
4744 ** invocations of the same function.
4746 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4747 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4748 ** value to the application-defined function. ^If there is no metadata
4749 ** associated with the function argument, this sqlite3_get_auxdata() interface
4750 ** returns a NULL pointer.
4752 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4753 ** argument of the application-defined function. ^Subsequent
4754 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4755 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4756 ** NULL if the metadata has been discarded.
4757 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4758 ** SQLite will invoke the destructor function X with parameter P exactly
4759 ** once, when the metadata is discarded.
4760 ** SQLite is free to discard the metadata at any time, including: <ul>
4761 ** <li> when the corresponding function parameter changes, or
4762 ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4763 ** SQL statement, or
4764 ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
4765 ** <li> during the original sqlite3_set_auxdata() call when a memory
4766 ** allocation error occurs. </ul>)^
4768 ** Note the last bullet in particular. The destructor X in
4769 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4770 ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
4771 ** should be called near the end of the function implementation and the
4772 ** function implementation should not make any use of P after
4773 ** sqlite3_set_auxdata() has been called.
4775 ** ^(In practice, metadata is preserved between function calls for
4776 ** function parameters that are compile-time constants, including literal
4777 ** values and [parameters] and expressions composed from the same.)^
4779 ** These routines must be called from the same thread in which
4780 ** the SQL function is running.
4782 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4783 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4787 ** CAPI3REF: Constants Defining Special Destructor Behavior
4789 ** These are special values for the destructor that is passed in as the
4790 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
4791 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4792 ** and will never change. It does not need to be destroyed. ^The
4793 ** SQLITE_TRANSIENT value means that the content will likely change in
4794 ** the near future and that SQLite should make its own private copy of
4795 ** the content before returning.
4797 ** The typedef is necessary to work around problems in certain
4798 ** C++ compilers.
4800 typedef void (*sqlite3_destructor_type)(void*);
4801 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
4802 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
4805 ** CAPI3REF: Setting The Result Of An SQL Function
4807 ** These routines are used by the xFunc or xFinal callbacks that
4808 ** implement SQL functions and aggregates. See
4809 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4810 ** for additional information.
4812 ** These functions work very much like the [parameter binding] family of
4813 ** functions used to bind values to host parameters in prepared statements.
4814 ** Refer to the [SQL parameter] documentation for additional information.
4816 ** ^The sqlite3_result_blob() interface sets the result from
4817 ** an application-defined function to be the BLOB whose content is pointed
4818 ** to by the second parameter and which is N bytes long where N is the
4819 ** third parameter.
4821 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4822 ** the application-defined function to be a BLOB containing all zero
4823 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4825 ** ^The sqlite3_result_double() interface sets the result from
4826 ** an application-defined function to be a floating point value specified
4827 ** by its 2nd argument.
4829 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4830 ** cause the implemented SQL function to throw an exception.
4831 ** ^SQLite uses the string pointed to by the
4832 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4833 ** as the text of an error message. ^SQLite interprets the error
4834 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4835 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4836 ** byte order. ^If the third parameter to sqlite3_result_error()
4837 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4838 ** message all text up through the first zero character.
4839 ** ^If the third parameter to sqlite3_result_error() or
4840 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4841 ** bytes (not characters) from the 2nd parameter as the error message.
4842 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4843 ** routines make a private copy of the error message text before
4844 ** they return. Hence, the calling function can deallocate or
4845 ** modify the text after they return without harm.
4846 ** ^The sqlite3_result_error_code() function changes the error code
4847 ** returned by SQLite as a result of an error in a function. ^By default,
4848 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
4849 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4851 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4852 ** error indicating that a string or BLOB is too long to represent.
4854 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4855 ** error indicating that a memory allocation failed.
4857 ** ^The sqlite3_result_int() interface sets the return value
4858 ** of the application-defined function to be the 32-bit signed integer
4859 ** value given in the 2nd argument.
4860 ** ^The sqlite3_result_int64() interface sets the return value
4861 ** of the application-defined function to be the 64-bit signed integer
4862 ** value given in the 2nd argument.
4864 ** ^The sqlite3_result_null() interface sets the return value
4865 ** of the application-defined function to be NULL.
4867 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4868 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4869 ** set the return value of the application-defined function to be
4870 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4871 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4872 ** ^SQLite takes the text result from the application from
4873 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4874 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4875 ** is negative, then SQLite takes result text from the 2nd parameter
4876 ** through the first zero character.
4877 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4878 ** is non-negative, then as many bytes (not characters) of the text
4879 ** pointed to by the 2nd parameter are taken as the application-defined
4880 ** function result. If the 3rd parameter is non-negative, then it
4881 ** must be the byte offset into the string where the NUL terminator would
4882 ** appear if the string where NUL terminated. If any NUL characters occur
4883 ** in the string at a byte offset that is less than the value of the 3rd
4884 ** parameter, then the resulting string will contain embedded NULs and the
4885 ** result of expressions operating on strings with embedded NULs is undefined.
4886 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4887 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4888 ** function as the destructor on the text or BLOB result when it has
4889 ** finished using that result.
4890 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4891 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4892 ** assumes that the text or BLOB result is in constant space and does not
4893 ** copy the content of the parameter nor call a destructor on the content
4894 ** when it has finished using that result.
4895 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4896 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4897 ** then SQLite makes a copy of the result into space obtained from
4898 ** from [sqlite3_malloc()] before it returns.
4900 ** ^The sqlite3_result_value() interface sets the result of
4901 ** the application-defined function to be a copy the
4902 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
4903 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4904 ** so that the [sqlite3_value] specified in the parameter may change or
4905 ** be deallocated after sqlite3_result_value() returns without harm.
4906 ** ^A [protected sqlite3_value] object may always be used where an
4907 ** [unprotected sqlite3_value] object is required, so either
4908 ** kind of [sqlite3_value] object can be used with this interface.
4910 ** If these routines are called from within the different thread
4911 ** than the one containing the application-defined function that received
4912 ** the [sqlite3_context] pointer, the results are undefined.
4914 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4915 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4916 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4917 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4918 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4919 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4920 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4921 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4922 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4923 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4924 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4925 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4926 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4927 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4928 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4929 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4932 ** CAPI3REF: Define New Collating Sequences
4934 ** ^These functions add, remove, or modify a [collation] associated
4935 ** with the [database connection] specified as the first argument.
4937 ** ^The name of the collation is a UTF-8 string
4938 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4939 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4940 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4941 ** considered to be the same name.
4943 ** ^(The third argument (eTextRep) must be one of the constants:
4944 ** <ul>
4945 ** <li> [SQLITE_UTF8],
4946 ** <li> [SQLITE_UTF16LE],
4947 ** <li> [SQLITE_UTF16BE],
4948 ** <li> [SQLITE_UTF16], or
4949 ** <li> [SQLITE_UTF16_ALIGNED].
4950 ** </ul>)^
4951 ** ^The eTextRep argument determines the encoding of strings passed
4952 ** to the collating function callback, xCallback.
4953 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4954 ** force strings to be UTF16 with native byte order.
4955 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4956 ** on an even byte address.
4958 ** ^The fourth argument, pArg, is an application data pointer that is passed
4959 ** through as the first argument to the collating function callback.
4961 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4962 ** ^Multiple collating functions can be registered using the same name but
4963 ** with different eTextRep parameters and SQLite will use whichever
4964 ** function requires the least amount of data transformation.
4965 ** ^If the xCallback argument is NULL then the collating function is
4966 ** deleted. ^When all collating functions having the same name are deleted,
4967 ** that collation is no longer usable.
4969 ** ^The collating function callback is invoked with a copy of the pArg
4970 ** application data pointer and with two strings in the encoding specified
4971 ** by the eTextRep argument. The collating function must return an
4972 ** integer that is negative, zero, or positive
4973 ** if the first string is less than, equal to, or greater than the second,
4974 ** respectively. A collating function must always return the same answer
4975 ** given the same inputs. If two or more collating functions are registered
4976 ** to the same collation name (using different eTextRep values) then all
4977 ** must give an equivalent answer when invoked with equivalent strings.
4978 ** The collating function must obey the following properties for all
4979 ** strings A, B, and C:
4981 ** <ol>
4982 ** <li> If A==B then B==A.
4983 ** <li> If A==B and B==C then A==C.
4984 ** <li> If A&lt;B THEN B&gt;A.
4985 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4986 ** </ol>
4988 ** If a collating function fails any of the above constraints and that
4989 ** collating function is registered and used, then the behavior of SQLite
4990 ** is undefined.
4992 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4993 ** with the addition that the xDestroy callback is invoked on pArg when
4994 ** the collating function is deleted.
4995 ** ^Collating functions are deleted when they are overridden by later
4996 ** calls to the collation creation functions or when the
4997 ** [database connection] is closed using [sqlite3_close()].
4999 ** ^The xDestroy callback is <u>not</u> called if the
5000 ** sqlite3_create_collation_v2() function fails. Applications that invoke
5001 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
5002 ** check the return code and dispose of the application data pointer
5003 ** themselves rather than expecting SQLite to deal with it for them.
5004 ** This is different from every other SQLite interface. The inconsistency
5005 ** is unfortunate but cannot be changed without breaking backwards
5006 ** compatibility.
5008 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
5010 SQLITE_API int sqlite3_create_collation(
5011 sqlite3*,
5012 const char *zName,
5013 int eTextRep,
5014 void *pArg,
5015 int(*xCompare)(void*,int,const void*,int,const void*)
5017 SQLITE_API int sqlite3_create_collation_v2(
5018 sqlite3*,
5019 const char *zName,
5020 int eTextRep,
5021 void *pArg,
5022 int(*xCompare)(void*,int,const void*,int,const void*),
5023 void(*xDestroy)(void*)
5025 SQLITE_API int sqlite3_create_collation16(
5026 sqlite3*,
5027 const void *zName,
5028 int eTextRep,
5029 void *pArg,
5030 int(*xCompare)(void*,int,const void*,int,const void*)
5034 ** CAPI3REF: Collation Needed Callbacks
5036 ** ^To avoid having to register all collation sequences before a database
5037 ** can be used, a single callback function may be registered with the
5038 ** [database connection] to be invoked whenever an undefined collation
5039 ** sequence is required.
5041 ** ^If the function is registered using the sqlite3_collation_needed() API,
5042 ** then it is passed the names of undefined collation sequences as strings
5043 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5044 ** the names are passed as UTF-16 in machine native byte order.
5045 ** ^A call to either function replaces the existing collation-needed callback.
5047 ** ^(When the callback is invoked, the first argument passed is a copy
5048 ** of the second argument to sqlite3_collation_needed() or
5049 ** sqlite3_collation_needed16(). The second argument is the database
5050 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5051 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5052 ** sequence function required. The fourth parameter is the name of the
5053 ** required collation sequence.)^
5055 ** The callback function should register the desired collation using
5056 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5057 ** [sqlite3_create_collation_v2()].
5059 SQLITE_API int sqlite3_collation_needed(
5060 sqlite3*,
5061 void*,
5062 void(*)(void*,sqlite3*,int eTextRep,const char*)
5064 SQLITE_API int sqlite3_collation_needed16(
5065 sqlite3*,
5066 void*,
5067 void(*)(void*,sqlite3*,int eTextRep,const void*)
5070 #ifdef SQLITE_HAS_CODEC
5072 ** Specify the key for an encrypted database. This routine should be
5073 ** called right after sqlite3_open().
5075 ** The code to implement this API is not available in the public release
5076 ** of SQLite.
5078 SQLITE_API int sqlite3_key(
5079 sqlite3 *db, /* Database to be rekeyed */
5080 const void *pKey, int nKey /* The key */
5082 SQLITE_API int sqlite3_key_v2(
5083 sqlite3 *db, /* Database to be rekeyed */
5084 const char *zDbName, /* Name of the database */
5085 const void *pKey, int nKey /* The key */
5089 ** Change the key on an open database. If the current database is not
5090 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
5091 ** database is decrypted.
5093 ** The code to implement this API is not available in the public release
5094 ** of SQLite.
5096 SQLITE_API int sqlite3_rekey(
5097 sqlite3 *db, /* Database to be rekeyed */
5098 const void *pKey, int nKey /* The new key */
5100 SQLITE_API int sqlite3_rekey_v2(
5101 sqlite3 *db, /* Database to be rekeyed */
5102 const char *zDbName, /* Name of the database */
5103 const void *pKey, int nKey /* The new key */
5107 ** Specify the activation key for a SEE database. Unless
5108 ** activated, none of the SEE routines will work.
5110 SQLITE_API void sqlite3_activate_see(
5111 const char *zPassPhrase /* Activation phrase */
5113 #endif
5115 #ifdef SQLITE_ENABLE_CEROD
5117 ** Specify the activation key for a CEROD database. Unless
5118 ** activated, none of the CEROD routines will work.
5120 SQLITE_API void sqlite3_activate_cerod(
5121 const char *zPassPhrase /* Activation phrase */
5123 #endif
5126 ** CAPI3REF: Suspend Execution For A Short Time
5128 ** The sqlite3_sleep() function causes the current thread to suspend execution
5129 ** for at least a number of milliseconds specified in its parameter.
5131 ** If the operating system does not support sleep requests with
5132 ** millisecond time resolution, then the time will be rounded up to
5133 ** the nearest second. The number of milliseconds of sleep actually
5134 ** requested from the operating system is returned.
5136 ** ^SQLite implements this interface by calling the xSleep()
5137 ** method of the default [sqlite3_vfs] object. If the xSleep() method
5138 ** of the default VFS is not implemented correctly, or not implemented at
5139 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5140 ** in the previous paragraphs.
5142 SQLITE_API int sqlite3_sleep(int);
5145 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5147 ** ^(If this global variable is made to point to a string which is
5148 ** the name of a folder (a.k.a. directory), then all temporary files
5149 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5150 ** will be placed in that directory.)^ ^If this variable
5151 ** is a NULL pointer, then SQLite performs a search for an appropriate
5152 ** temporary file directory.
5154 ** It is not safe to read or modify this variable in more than one
5155 ** thread at a time. It is not safe to read or modify this variable
5156 ** if a [database connection] is being used at the same time in a separate
5157 ** thread.
5158 ** It is intended that this variable be set once
5159 ** as part of process initialization and before any SQLite interface
5160 ** routines have been called and that this variable remain unchanged
5161 ** thereafter.
5163 ** ^The [temp_store_directory pragma] may modify this variable and cause
5164 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5165 ** the [temp_store_directory pragma] always assumes that any string
5166 ** that this variable points to is held in memory obtained from
5167 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5168 ** using [sqlite3_free].
5169 ** Hence, if this variable is modified directly, either it should be
5170 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5171 ** or else the use of the [temp_store_directory pragma] should be avoided.
5173 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
5174 ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
5175 ** features that require the use of temporary files may fail. Here is an
5176 ** example of how to do this using C++ with the Windows Runtime:
5178 ** <blockquote><pre>
5179 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5180 ** &nbsp; TemporaryFolder->Path->Data();
5181 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5182 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5183 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5184 ** &nbsp; NULL, NULL);
5185 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5186 ** </pre></blockquote>
5188 SQLITE_API char *sqlite3_temp_directory;
5191 ** CAPI3REF: Name Of The Folder Holding Database Files
5193 ** ^(If this global variable is made to point to a string which is
5194 ** the name of a folder (a.k.a. directory), then all database files
5195 ** specified with a relative pathname and created or accessed by
5196 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5197 ** to be relative to that directory.)^ ^If this variable is a NULL
5198 ** pointer, then SQLite assumes that all database files specified
5199 ** with a relative pathname are relative to the current directory
5200 ** for the process. Only the windows VFS makes use of this global
5201 ** variable; it is ignored by the unix VFS.
5203 ** Changing the value of this variable while a database connection is
5204 ** open can result in a corrupt database.
5206 ** It is not safe to read or modify this variable in more than one
5207 ** thread at a time. It is not safe to read or modify this variable
5208 ** if a [database connection] is being used at the same time in a separate
5209 ** thread.
5210 ** It is intended that this variable be set once
5211 ** as part of process initialization and before any SQLite interface
5212 ** routines have been called and that this variable remain unchanged
5213 ** thereafter.
5215 ** ^The [data_store_directory pragma] may modify this variable and cause
5216 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5217 ** the [data_store_directory pragma] always assumes that any string
5218 ** that this variable points to is held in memory obtained from
5219 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5220 ** using [sqlite3_free].
5221 ** Hence, if this variable is modified directly, either it should be
5222 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5223 ** or else the use of the [data_store_directory pragma] should be avoided.
5225 SQLITE_API char *sqlite3_data_directory;
5228 ** CAPI3REF: Test For Auto-Commit Mode
5229 ** KEYWORDS: {autocommit mode}
5231 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5232 ** zero if the given database connection is or is not in autocommit mode,
5233 ** respectively. ^Autocommit mode is on by default.
5234 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5235 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5237 ** If certain kinds of errors occur on a statement within a multi-statement
5238 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5239 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5240 ** transaction might be rolled back automatically. The only way to
5241 ** find out whether SQLite automatically rolled back the transaction after
5242 ** an error is to use this function.
5244 ** If another thread changes the autocommit status of the database
5245 ** connection while this routine is running, then the return value
5246 ** is undefined.
5248 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5251 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5253 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5254 ** to which a [prepared statement] belongs. ^The [database connection]
5255 ** returned by sqlite3_db_handle is the same [database connection]
5256 ** that was the first argument
5257 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5258 ** create the statement in the first place.
5260 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5263 ** CAPI3REF: Return The Filename For A Database Connection
5265 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5266 ** associated with database N of connection D. ^The main database file
5267 ** has the name "main". If there is no attached database N on the database
5268 ** connection D, or if database N is a temporary or in-memory database, then
5269 ** a NULL pointer is returned.
5271 ** ^The filename returned by this function is the output of the
5272 ** xFullPathname method of the [VFS]. ^In other words, the filename
5273 ** will be an absolute pathname, even if the filename used
5274 ** to open the database originally was a URI or relative pathname.
5276 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5279 ** CAPI3REF: Determine if a database is read-only
5281 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5282 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5283 ** the name of a database on connection D.
5285 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5288 ** CAPI3REF: Find the next prepared statement
5290 ** ^This interface returns a pointer to the next [prepared statement] after
5291 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
5292 ** then this interface returns a pointer to the first prepared statement
5293 ** associated with the database connection pDb. ^If no prepared statement
5294 ** satisfies the conditions of this routine, it returns NULL.
5296 ** The [database connection] pointer D in a call to
5297 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5298 ** connection and in particular must not be a NULL pointer.
5300 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5303 ** CAPI3REF: Commit And Rollback Notification Callbacks
5305 ** ^The sqlite3_commit_hook() interface registers a callback
5306 ** function to be invoked whenever a transaction is [COMMIT | committed].
5307 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5308 ** for the same database connection is overridden.
5309 ** ^The sqlite3_rollback_hook() interface registers a callback
5310 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5311 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5312 ** for the same database connection is overridden.
5313 ** ^The pArg argument is passed through to the callback.
5314 ** ^If the callback on a commit hook function returns non-zero,
5315 ** then the commit is converted into a rollback.
5317 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5318 ** return the P argument from the previous call of the same function
5319 ** on the same [database connection] D, or NULL for
5320 ** the first call for each function on D.
5322 ** The commit and rollback hook callbacks are not reentrant.
5323 ** The callback implementation must not do anything that will modify
5324 ** the database connection that invoked the callback. Any actions
5325 ** to modify the database connection must be deferred until after the
5326 ** completion of the [sqlite3_step()] call that triggered the commit
5327 ** or rollback hook in the first place.
5328 ** Note that running any other SQL statements, including SELECT statements,
5329 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5330 ** the database connections for the meaning of "modify" in this paragraph.
5332 ** ^Registering a NULL function disables the callback.
5334 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5335 ** operation is allowed to continue normally. ^If the commit hook
5336 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5337 ** ^The rollback hook is invoked on a rollback that results from a commit
5338 ** hook returning non-zero, just as it would be with any other rollback.
5340 ** ^For the purposes of this API, a transaction is said to have been
5341 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5342 ** an error or constraint causes an implicit rollback to occur.
5343 ** ^The rollback callback is not invoked if a transaction is
5344 ** automatically rolled back because the database connection is closed.
5346 ** See also the [sqlite3_update_hook()] interface.
5348 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5349 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5352 ** CAPI3REF: Data Change Notification Callbacks
5354 ** ^The sqlite3_update_hook() interface registers a callback function
5355 ** with the [database connection] identified by the first argument
5356 ** to be invoked whenever a row is updated, inserted or deleted.
5357 ** ^Any callback set by a previous call to this function
5358 ** for the same database connection is overridden.
5360 ** ^The second argument is a pointer to the function to invoke when a
5361 ** row is updated, inserted or deleted.
5362 ** ^The first argument to the callback is a copy of the third argument
5363 ** to sqlite3_update_hook().
5364 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5365 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5366 ** to be invoked.
5367 ** ^The third and fourth arguments to the callback contain pointers to the
5368 ** database and table name containing the affected row.
5369 ** ^The final callback parameter is the [rowid] of the row.
5370 ** ^In the case of an update, this is the [rowid] after the update takes place.
5372 ** ^(The update hook is not invoked when internal system tables are
5373 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5375 ** ^In the current implementation, the update hook
5376 ** is not invoked when duplication rows are deleted because of an
5377 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
5378 ** invoked when rows are deleted using the [truncate optimization].
5379 ** The exceptions defined in this paragraph might change in a future
5380 ** release of SQLite.
5382 ** The update hook implementation must not do anything that will modify
5383 ** the database connection that invoked the update hook. Any actions
5384 ** to modify the database connection must be deferred until after the
5385 ** completion of the [sqlite3_step()] call that triggered the update hook.
5386 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5387 ** database connections for the meaning of "modify" in this paragraph.
5389 ** ^The sqlite3_update_hook(D,C,P) function
5390 ** returns the P argument from the previous call
5391 ** on the same [database connection] D, or NULL for
5392 ** the first call on D.
5394 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5395 ** interfaces.
5397 SQLITE_API void *sqlite3_update_hook(
5398 sqlite3*,
5399 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5400 void*
5404 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5406 ** ^(This routine enables or disables the sharing of the database cache
5407 ** and schema data structures between [database connection | connections]
5408 ** to the same database. Sharing is enabled if the argument is true
5409 ** and disabled if the argument is false.)^
5411 ** ^Cache sharing is enabled and disabled for an entire process.
5412 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5413 ** sharing was enabled or disabled for each thread separately.
5415 ** ^(The cache sharing mode set by this interface effects all subsequent
5416 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5417 ** Existing database connections continue use the sharing mode
5418 ** that was in effect at the time they were opened.)^
5420 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5421 ** successfully. An [error code] is returned otherwise.)^
5423 ** ^Shared cache is disabled by default. But this might change in
5424 ** future releases of SQLite. Applications that care about shared
5425 ** cache setting should set it explicitly.
5427 ** This interface is threadsafe on processors where writing a
5428 ** 32-bit integer is atomic.
5430 ** See Also: [SQLite Shared-Cache Mode]
5432 SQLITE_API int sqlite3_enable_shared_cache(int);
5435 ** CAPI3REF: Attempt To Free Heap Memory
5437 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5438 ** of heap memory by deallocating non-essential memory allocations
5439 ** held by the database library. Memory used to cache database
5440 ** pages to improve performance is an example of non-essential memory.
5441 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5442 ** which might be more or less than the amount requested.
5443 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5444 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5446 ** See also: [sqlite3_db_release_memory()]
5448 SQLITE_API int sqlite3_release_memory(int);
5451 ** CAPI3REF: Free Memory Used By A Database Connection
5453 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5454 ** memory as possible from database connection D. Unlike the
5455 ** [sqlite3_release_memory()] interface, this interface is effect even
5456 ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5457 ** omitted.
5459 ** See also: [sqlite3_release_memory()]
5461 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5464 ** CAPI3REF: Impose A Limit On Heap Size
5466 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5467 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5468 ** ^SQLite strives to keep heap memory utilization below the soft heap
5469 ** limit by reducing the number of pages held in the page cache
5470 ** as heap memory usages approaches the limit.
5471 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5472 ** below the limit, it will exceed the limit rather than generate
5473 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
5474 ** is advisory only.
5476 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5477 ** the soft heap limit prior to the call, or negative in the case of an
5478 ** error. ^If the argument N is negative
5479 ** then no change is made to the soft heap limit. Hence, the current
5480 ** size of the soft heap limit can be determined by invoking
5481 ** sqlite3_soft_heap_limit64() with a negative argument.
5483 ** ^If the argument N is zero then the soft heap limit is disabled.
5485 ** ^(The soft heap limit is not enforced in the current implementation
5486 ** if one or more of following conditions are true:
5488 ** <ul>
5489 ** <li> The soft heap limit is set to zero.
5490 ** <li> Memory accounting is disabled using a combination of the
5491 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5492 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5493 ** <li> An alternative page cache implementation is specified using
5494 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5495 ** <li> The page cache allocates from its own memory pool supplied
5496 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5497 ** from the heap.
5498 ** </ul>)^
5500 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5501 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5502 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5503 ** the soft heap limit is enforced on every memory allocation. Without
5504 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5505 ** when memory is allocated by the page cache. Testing suggests that because
5506 ** the page cache is the predominate memory user in SQLite, most
5507 ** applications will achieve adequate soft heap limit enforcement without
5508 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5510 ** The circumstances under which SQLite will enforce the soft heap limit may
5511 ** changes in future releases of SQLite.
5513 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5516 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5517 ** DEPRECATED
5519 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5520 ** interface. This routine is provided for historical compatibility
5521 ** only. All new applications should use the
5522 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5524 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5528 ** CAPI3REF: Extract Metadata About A Column Of A Table
5530 ** ^This routine returns metadata about a specific column of a specific
5531 ** database table accessible using the [database connection] handle
5532 ** passed as the first function argument.
5534 ** ^The column is identified by the second, third and fourth parameters to
5535 ** this function. ^The second parameter is either the name of the database
5536 ** (i.e. "main", "temp", or an attached database) containing the specified
5537 ** table or NULL. ^If it is NULL, then all attached databases are searched
5538 ** for the table using the same algorithm used by the database engine to
5539 ** resolve unqualified table references.
5541 ** ^The third and fourth parameters to this function are the table and column
5542 ** name of the desired column, respectively. Neither of these parameters
5543 ** may be NULL.
5545 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5546 ** and subsequent parameters to this function. ^Any of these arguments may be
5547 ** NULL, in which case the corresponding element of metadata is omitted.
5549 ** ^(<blockquote>
5550 ** <table border="1">
5551 ** <tr><th> Parameter <th> Output<br>Type <th> Description
5553 ** <tr><td> 5th <td> const char* <td> Data type
5554 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5555 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
5556 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
5557 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
5558 ** </table>
5559 ** </blockquote>)^
5561 ** ^The memory pointed to by the character pointers returned for the
5562 ** declaration type and collation sequence is valid only until the next
5563 ** call to any SQLite API function.
5565 ** ^If the specified table is actually a view, an [error code] is returned.
5567 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5568 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5569 ** parameters are set for the explicitly declared column. ^(If there is no
5570 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5571 ** parameters are set as follows:
5573 ** <pre>
5574 ** data type: "INTEGER"
5575 ** collation sequence: "BINARY"
5576 ** not null: 0
5577 ** primary key: 1
5578 ** auto increment: 0
5579 ** </pre>)^
5581 ** ^(This function may load one or more schemas from database files. If an
5582 ** error occurs during this process, or if the requested table or column
5583 ** cannot be found, an [error code] is returned and an error message left
5584 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5586 ** ^This API is only available if the library was compiled with the
5587 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5589 SQLITE_API int sqlite3_table_column_metadata(
5590 sqlite3 *db, /* Connection handle */
5591 const char *zDbName, /* Database name or NULL */
5592 const char *zTableName, /* Table name */
5593 const char *zColumnName, /* Column name */
5594 char const **pzDataType, /* OUTPUT: Declared data type */
5595 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
5596 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
5597 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
5598 int *pAutoinc /* OUTPUT: True if column is auto-increment */
5602 ** CAPI3REF: Load An Extension
5604 ** ^This interface loads an SQLite extension library from the named file.
5606 ** ^The sqlite3_load_extension() interface attempts to load an
5607 ** [SQLite extension] library contained in the file zFile. If
5608 ** the file cannot be loaded directly, attempts are made to load
5609 ** with various operating-system specific extensions added.
5610 ** So for example, if "samplelib" cannot be loaded, then names like
5611 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5612 ** be tried also.
5614 ** ^The entry point is zProc.
5615 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5616 ** entry point name on its own. It first tries "sqlite3_extension_init".
5617 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5618 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5619 ** characters in the filename from the last "/" to the first following
5620 ** "." and omitting any initial "lib".)^
5621 ** ^The sqlite3_load_extension() interface returns
5622 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5623 ** ^If an error occurs and pzErrMsg is not 0, then the
5624 ** [sqlite3_load_extension()] interface shall attempt to
5625 ** fill *pzErrMsg with error message text stored in memory
5626 ** obtained from [sqlite3_malloc()]. The calling function
5627 ** should free this memory by calling [sqlite3_free()].
5629 ** ^Extension loading must be enabled using
5630 ** [sqlite3_enable_load_extension()] prior to calling this API,
5631 ** otherwise an error will be returned.
5633 ** See also the [load_extension() SQL function].
5635 SQLITE_API int sqlite3_load_extension(
5636 sqlite3 *db, /* Load the extension into this database connection */
5637 const char *zFile, /* Name of the shared library containing extension */
5638 const char *zProc, /* Entry point. Derived from zFile if 0 */
5639 char **pzErrMsg /* Put error message here if not 0 */
5643 ** CAPI3REF: Enable Or Disable Extension Loading
5645 ** ^So as not to open security holes in older applications that are
5646 ** unprepared to deal with [extension loading], and as a means of disabling
5647 ** [extension loading] while evaluating user-entered SQL, the following API
5648 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5650 ** ^Extension loading is off by default.
5651 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5652 ** to turn extension loading on and call it with onoff==0 to turn
5653 ** it back off again.
5655 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5658 ** CAPI3REF: Automatically Load Statically Linked Extensions
5660 ** ^This interface causes the xEntryPoint() function to be invoked for
5661 ** each new [database connection] that is created. The idea here is that
5662 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5663 ** that is to be automatically loaded into all new database connections.
5665 ** ^(Even though the function prototype shows that xEntryPoint() takes
5666 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5667 ** arguments and expects and integer result as if the signature of the
5668 ** entry point where as follows:
5670 ** <blockquote><pre>
5671 ** &nbsp; int xEntryPoint(
5672 ** &nbsp; sqlite3 *db,
5673 ** &nbsp; const char **pzErrMsg,
5674 ** &nbsp; const struct sqlite3_api_routines *pThunk
5675 ** &nbsp; );
5676 ** </pre></blockquote>)^
5678 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5679 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5680 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
5681 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
5682 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
5683 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5684 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5686 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5687 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5688 ** will be called more than once for each database connection that is opened.
5690 ** See also: [sqlite3_reset_auto_extension()]
5691 ** and [sqlite3_cancel_auto_extension()]
5693 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5696 ** CAPI3REF: Cancel Automatic Extension Loading
5698 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5699 ** initialization routine X that was registered using a prior call to
5700 ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
5701 ** routine returns 1 if initialization routine X was successfully
5702 ** unregistered and it returns 0 if X was not on the list of initialization
5703 ** routines.
5705 SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
5708 ** CAPI3REF: Reset Automatic Extension Loading
5710 ** ^This interface disables all automatic extensions previously
5711 ** registered using [sqlite3_auto_extension()].
5713 SQLITE_API void sqlite3_reset_auto_extension(void);
5716 ** The interface to the virtual-table mechanism is currently considered
5717 ** to be experimental. The interface might change in incompatible ways.
5718 ** If this is a problem for you, do not use the interface at this time.
5720 ** When the virtual-table mechanism stabilizes, we will declare the
5721 ** interface fixed, support it indefinitely, and remove this comment.
5725 ** Structures used by the virtual table interface
5727 typedef struct sqlite3_vtab sqlite3_vtab;
5728 typedef struct sqlite3_index_info sqlite3_index_info;
5729 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5730 typedef struct sqlite3_module sqlite3_module;
5733 ** CAPI3REF: Virtual Table Object
5734 ** KEYWORDS: sqlite3_module {virtual table module}
5736 ** This structure, sometimes called a "virtual table module",
5737 ** defines the implementation of a [virtual tables].
5738 ** This structure consists mostly of methods for the module.
5740 ** ^A virtual table module is created by filling in a persistent
5741 ** instance of this structure and passing a pointer to that instance
5742 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5743 ** ^The registration remains valid until it is replaced by a different
5744 ** module or until the [database connection] closes. The content
5745 ** of this structure must not change while it is registered with
5746 ** any database connection.
5748 struct sqlite3_module {
5749 int iVersion;
5750 int (*xCreate)(sqlite3*, void *pAux,
5751 int argc, const char *const*argv,
5752 sqlite3_vtab **ppVTab, char**);
5753 int (*xConnect)(sqlite3*, void *pAux,
5754 int argc, const char *const*argv,
5755 sqlite3_vtab **ppVTab, char**);
5756 int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5757 int (*xDisconnect)(sqlite3_vtab *pVTab);
5758 int (*xDestroy)(sqlite3_vtab *pVTab);
5759 int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5760 int (*xClose)(sqlite3_vtab_cursor*);
5761 int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5762 int argc, sqlite3_value **argv);
5763 int (*xNext)(sqlite3_vtab_cursor*);
5764 int (*xEof)(sqlite3_vtab_cursor*);
5765 int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5766 int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5767 int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5768 int (*xBegin)(sqlite3_vtab *pVTab);
5769 int (*xSync)(sqlite3_vtab *pVTab);
5770 int (*xCommit)(sqlite3_vtab *pVTab);
5771 int (*xRollback)(sqlite3_vtab *pVTab);
5772 int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5773 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5774 void **ppArg);
5775 int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5776 /* The methods above are in version 1 of the sqlite_module object. Those
5777 ** below are for version 2 and greater. */
5778 int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5779 int (*xRelease)(sqlite3_vtab *pVTab, int);
5780 int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5784 ** CAPI3REF: Virtual Table Indexing Information
5785 ** KEYWORDS: sqlite3_index_info
5787 ** The sqlite3_index_info structure and its substructures is used as part
5788 ** of the [virtual table] interface to
5789 ** pass information into and receive the reply from the [xBestIndex]
5790 ** method of a [virtual table module]. The fields under **Inputs** are the
5791 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
5792 ** results into the **Outputs** fields.
5794 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5796 ** <blockquote>column OP expr</blockquote>
5798 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
5799 ** stored in aConstraint[].op using one of the
5800 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5801 ** ^(The index of the column is stored in
5802 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
5803 ** expr on the right-hand side can be evaluated (and thus the constraint
5804 ** is usable) and false if it cannot.)^
5806 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5807 ** and makes other simplifications to the WHERE clause in an attempt to
5808 ** get as many WHERE clause terms into the form shown above as possible.
5809 ** ^The aConstraint[] array only reports WHERE clause terms that are
5810 ** relevant to the particular virtual table being queried.
5812 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5813 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5815 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5816 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
5817 ** the right-hand side of the corresponding aConstraint[] is evaluated
5818 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
5819 ** is true, then the constraint is assumed to be fully handled by the
5820 ** virtual table and is not checked again by SQLite.)^
5822 ** ^The idxNum and idxPtr values are recorded and passed into the
5823 ** [xFilter] method.
5824 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5825 ** needToFreeIdxPtr is true.
5827 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5828 ** the correct order to satisfy the ORDER BY clause so that no separate
5829 ** sorting step is required.
5831 ** ^The estimatedCost value is an estimate of the cost of doing the
5832 ** particular lookup. A full scan of a table with N entries should have
5833 ** a cost of N. A binary search of a table of N entries should have a
5834 ** cost of approximately log(N).
5836 struct sqlite3_index_info {
5837 /* Inputs */
5838 int nConstraint; /* Number of entries in aConstraint */
5839 struct sqlite3_index_constraint {
5840 int iColumn; /* Column on left-hand side of constraint */
5841 unsigned char op; /* Constraint operator */
5842 unsigned char usable; /* True if this constraint is usable */
5843 int iTermOffset; /* Used internally - xBestIndex should ignore */
5844 } *aConstraint; /* Table of WHERE clause constraints */
5845 int nOrderBy; /* Number of terms in the ORDER BY clause */
5846 struct sqlite3_index_orderby {
5847 int iColumn; /* Column number */
5848 unsigned char desc; /* True for DESC. False for ASC. */
5849 } *aOrderBy; /* The ORDER BY clause */
5850 /* Outputs */
5851 struct sqlite3_index_constraint_usage {
5852 int argvIndex; /* if >0, constraint is part of argv to xFilter */
5853 unsigned char omit; /* Do not code a test for this constraint */
5854 } *aConstraintUsage;
5855 int idxNum; /* Number used to identify the index */
5856 char *idxStr; /* String, possibly obtained from sqlite3_malloc */
5857 int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
5858 int orderByConsumed; /* True if output is already ordered */
5859 double estimatedCost; /* Estimated cost of using this index */
5863 ** CAPI3REF: Virtual Table Constraint Operator Codes
5865 ** These macros defined the allowed values for the
5866 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
5867 ** an operator that is part of a constraint term in the wHERE clause of
5868 ** a query that uses a [virtual table].
5870 #define SQLITE_INDEX_CONSTRAINT_EQ 2
5871 #define SQLITE_INDEX_CONSTRAINT_GT 4
5872 #define SQLITE_INDEX_CONSTRAINT_LE 8
5873 #define SQLITE_INDEX_CONSTRAINT_LT 16
5874 #define SQLITE_INDEX_CONSTRAINT_GE 32
5875 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5878 ** CAPI3REF: Register A Virtual Table Implementation
5880 ** ^These routines are used to register a new [virtual table module] name.
5881 ** ^Module names must be registered before
5882 ** creating a new [virtual table] using the module and before using a
5883 ** preexisting [virtual table] for the module.
5885 ** ^The module name is registered on the [database connection] specified
5886 ** by the first parameter. ^The name of the module is given by the
5887 ** second parameter. ^The third parameter is a pointer to
5888 ** the implementation of the [virtual table module]. ^The fourth
5889 ** parameter is an arbitrary client data pointer that is passed through
5890 ** into the [xCreate] and [xConnect] methods of the virtual table module
5891 ** when a new virtual table is be being created or reinitialized.
5893 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5894 ** is a pointer to a destructor for the pClientData. ^SQLite will
5895 ** invoke the destructor function (if it is not NULL) when SQLite
5896 ** no longer needs the pClientData pointer. ^The destructor will also
5897 ** be invoked if the call to sqlite3_create_module_v2() fails.
5898 ** ^The sqlite3_create_module()
5899 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5900 ** destructor.
5902 SQLITE_API int sqlite3_create_module(
5903 sqlite3 *db, /* SQLite connection to register module with */
5904 const char *zName, /* Name of the module */
5905 const sqlite3_module *p, /* Methods for the module */
5906 void *pClientData /* Client data for xCreate/xConnect */
5908 SQLITE_API int sqlite3_create_module_v2(
5909 sqlite3 *db, /* SQLite connection to register module with */
5910 const char *zName, /* Name of the module */
5911 const sqlite3_module *p, /* Methods for the module */
5912 void *pClientData, /* Client data for xCreate/xConnect */
5913 void(*xDestroy)(void*) /* Module destructor function */
5917 ** CAPI3REF: Virtual Table Instance Object
5918 ** KEYWORDS: sqlite3_vtab
5920 ** Every [virtual table module] implementation uses a subclass
5921 ** of this object to describe a particular instance
5922 ** of the [virtual table]. Each subclass will
5923 ** be tailored to the specific needs of the module implementation.
5924 ** The purpose of this superclass is to define certain fields that are
5925 ** common to all module implementations.
5927 ** ^Virtual tables methods can set an error message by assigning a
5928 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
5929 ** take care that any prior string is freed by a call to [sqlite3_free()]
5930 ** prior to assigning a new string to zErrMsg. ^After the error message
5931 ** is delivered up to the client application, the string will be automatically
5932 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5934 struct sqlite3_vtab {
5935 const sqlite3_module *pModule; /* The module for this virtual table */
5936 int nRef; /* NO LONGER USED */
5937 char *zErrMsg; /* Error message from sqlite3_mprintf() */
5938 /* Virtual table implementations will typically add additional fields */
5942 ** CAPI3REF: Virtual Table Cursor Object
5943 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5945 ** Every [virtual table module] implementation uses a subclass of the
5946 ** following structure to describe cursors that point into the
5947 ** [virtual table] and are used
5948 ** to loop through the virtual table. Cursors are created using the
5949 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5950 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
5951 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5952 ** of the module. Each module implementation will define
5953 ** the content of a cursor structure to suit its own needs.
5955 ** This superclass exists in order to define fields of the cursor that
5956 ** are common to all implementations.
5958 struct sqlite3_vtab_cursor {
5959 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
5960 /* Virtual table implementations will typically add additional fields */
5964 ** CAPI3REF: Declare The Schema Of A Virtual Table
5966 ** ^The [xCreate] and [xConnect] methods of a
5967 ** [virtual table module] call this interface
5968 ** to declare the format (the names and datatypes of the columns) of
5969 ** the virtual tables they implement.
5971 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5974 ** CAPI3REF: Overload A Function For A Virtual Table
5976 ** ^(Virtual tables can provide alternative implementations of functions
5977 ** using the [xFindFunction] method of the [virtual table module].
5978 ** But global versions of those functions
5979 ** must exist in order to be overloaded.)^
5981 ** ^(This API makes sure a global version of a function with a particular
5982 ** name and number of parameters exists. If no such function exists
5983 ** before this API is called, a new function is created.)^ ^The implementation
5984 ** of the new function always causes an exception to be thrown. So
5985 ** the new function is not good for anything by itself. Its only
5986 ** purpose is to be a placeholder function that can be overloaded
5987 ** by a [virtual table].
5989 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5992 ** The interface to the virtual-table mechanism defined above (back up
5993 ** to a comment remarkably similar to this one) is currently considered
5994 ** to be experimental. The interface might change in incompatible ways.
5995 ** If this is a problem for you, do not use the interface at this time.
5997 ** When the virtual-table mechanism stabilizes, we will declare the
5998 ** interface fixed, support it indefinitely, and remove this comment.
6002 ** CAPI3REF: A Handle To An Open BLOB
6003 ** KEYWORDS: {BLOB handle} {BLOB handles}
6005 ** An instance of this object represents an open BLOB on which
6006 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6007 ** ^Objects of this type are created by [sqlite3_blob_open()]
6008 ** and destroyed by [sqlite3_blob_close()].
6009 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6010 ** can be used to read or write small subsections of the BLOB.
6011 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6013 typedef struct sqlite3_blob sqlite3_blob;
6016 ** CAPI3REF: Open A BLOB For Incremental I/O
6018 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6019 ** in row iRow, column zColumn, table zTable in database zDb;
6020 ** in other words, the same BLOB that would be selected by:
6022 ** <pre>
6023 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6024 ** </pre>)^
6026 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
6027 ** and write access. ^If it is zero, the BLOB is opened for read access.
6028 ** ^It is not possible to open a column that is part of an index or primary
6029 ** key for writing. ^If [foreign key constraints] are enabled, it is
6030 ** not possible to open a column that is part of a [child key] for writing.
6032 ** ^Note that the database name is not the filename that contains
6033 ** the database but rather the symbolic name of the database that
6034 ** appears after the AS keyword when the database is connected using [ATTACH].
6035 ** ^For the main database file, the database name is "main".
6036 ** ^For TEMP tables, the database name is "temp".
6038 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
6039 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
6040 ** to be a null pointer.)^
6041 ** ^This function sets the [database connection] error code and message
6042 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
6043 ** functions. ^Note that the *ppBlob variable is always initialized in a
6044 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
6045 ** regardless of the success or failure of this routine.
6047 ** ^(If the row that a BLOB handle points to is modified by an
6048 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6049 ** then the BLOB handle is marked as "expired".
6050 ** This is true if any column of the row is changed, even a column
6051 ** other than the one the BLOB handle is open on.)^
6052 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6053 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6054 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
6055 ** rolled back by the expiration of the BLOB. Such changes will eventually
6056 ** commit if the transaction continues to completion.)^
6058 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6059 ** the opened blob. ^The size of a blob may not be changed by this
6060 ** interface. Use the [UPDATE] SQL command to change the size of a
6061 ** blob.
6063 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6064 ** and the built-in [zeroblob] SQL function can be used, if desired,
6065 ** to create an empty, zero-filled blob in which to read or write using
6066 ** this interface.
6068 ** To avoid a resource leak, every open [BLOB handle] should eventually
6069 ** be released by a call to [sqlite3_blob_close()].
6071 SQLITE_API int sqlite3_blob_open(
6072 sqlite3*,
6073 const char *zDb,
6074 const char *zTable,
6075 const char *zColumn,
6076 sqlite3_int64 iRow,
6077 int flags,
6078 sqlite3_blob **ppBlob
6082 ** CAPI3REF: Move a BLOB Handle to a New Row
6084 ** ^This function is used to move an existing blob handle so that it points
6085 ** to a different row of the same database table. ^The new row is identified
6086 ** by the rowid value passed as the second argument. Only the row can be
6087 ** changed. ^The database, table and column on which the blob handle is open
6088 ** remain the same. Moving an existing blob handle to a new row can be
6089 ** faster than closing the existing handle and opening a new one.
6091 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6092 ** it must exist and there must be either a blob or text value stored in
6093 ** the nominated column.)^ ^If the new row is not present in the table, or if
6094 ** it does not contain a blob or text value, or if another error occurs, an
6095 ** SQLite error code is returned and the blob handle is considered aborted.
6096 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6097 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6098 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6099 ** always returns zero.
6101 ** ^This function sets the database handle error code and message.
6103 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6106 ** CAPI3REF: Close A BLOB Handle
6108 ** ^Closes an open [BLOB handle].
6110 ** ^Closing a BLOB shall cause the current transaction to commit
6111 ** if there are no other BLOBs, no pending prepared statements, and the
6112 ** database connection is in [autocommit mode].
6113 ** ^If any writes were made to the BLOB, they might be held in cache
6114 ** until the close operation if they will fit.
6116 ** ^(Closing the BLOB often forces the changes
6117 ** out to disk and so if any I/O errors occur, they will likely occur
6118 ** at the time when the BLOB is closed. Any errors that occur during
6119 ** closing are reported as a non-zero return value.)^
6121 ** ^(The BLOB is closed unconditionally. Even if this routine returns
6122 ** an error code, the BLOB is still closed.)^
6124 ** ^Calling this routine with a null pointer (such as would be returned
6125 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
6127 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6130 ** CAPI3REF: Return The Size Of An Open BLOB
6132 ** ^Returns the size in bytes of the BLOB accessible via the
6133 ** successfully opened [BLOB handle] in its only argument. ^The
6134 ** incremental blob I/O routines can only read or overwriting existing
6135 ** blob content; they cannot change the size of a blob.
6137 ** This routine only works on a [BLOB handle] which has been created
6138 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6139 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6140 ** to this routine results in undefined and probably undesirable behavior.
6142 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6145 ** CAPI3REF: Read Data From A BLOB Incrementally
6147 ** ^(This function is used to read data from an open [BLOB handle] into a
6148 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6149 ** from the open BLOB, starting at offset iOffset.)^
6151 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6152 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
6153 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6154 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6155 ** can be determined using the [sqlite3_blob_bytes()] interface.
6157 ** ^An attempt to read from an expired [BLOB handle] fails with an
6158 ** error code of [SQLITE_ABORT].
6160 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6161 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6163 ** This routine only works on a [BLOB handle] which has been created
6164 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6165 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6166 ** to this routine results in undefined and probably undesirable behavior.
6168 ** See also: [sqlite3_blob_write()].
6170 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6173 ** CAPI3REF: Write Data Into A BLOB Incrementally
6175 ** ^This function is used to write data into an open [BLOB handle] from a
6176 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
6177 ** into the open BLOB, starting at offset iOffset.
6179 ** ^If the [BLOB handle] passed as the first argument was not opened for
6180 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6181 ** this function returns [SQLITE_READONLY].
6183 ** ^This function may only modify the contents of the BLOB; it is
6184 ** not possible to increase the size of a BLOB using this API.
6185 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6186 ** [SQLITE_ERROR] is returned and no data is written. ^If N is
6187 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6188 ** The size of the BLOB (and hence the maximum value of N+iOffset)
6189 ** can be determined using the [sqlite3_blob_bytes()] interface.
6191 ** ^An attempt to write to an expired [BLOB handle] fails with an
6192 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
6193 ** before the [BLOB handle] expired are not rolled back by the
6194 ** expiration of the handle, though of course those changes might
6195 ** have been overwritten by the statement that expired the BLOB handle
6196 ** or by other independent statements.
6198 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6199 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6201 ** This routine only works on a [BLOB handle] which has been created
6202 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6203 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6204 ** to this routine results in undefined and probably undesirable behavior.
6206 ** See also: [sqlite3_blob_read()].
6208 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6211 ** CAPI3REF: Virtual File System Objects
6213 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6214 ** that SQLite uses to interact
6215 ** with the underlying operating system. Most SQLite builds come with a
6216 ** single default VFS that is appropriate for the host computer.
6217 ** New VFSes can be registered and existing VFSes can be unregistered.
6218 ** The following interfaces are provided.
6220 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6221 ** ^Names are case sensitive.
6222 ** ^Names are zero-terminated UTF-8 strings.
6223 ** ^If there is no match, a NULL pointer is returned.
6224 ** ^If zVfsName is NULL then the default VFS is returned.
6226 ** ^New VFSes are registered with sqlite3_vfs_register().
6227 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6228 ** ^The same VFS can be registered multiple times without injury.
6229 ** ^To make an existing VFS into the default VFS, register it again
6230 ** with the makeDflt flag set. If two different VFSes with the
6231 ** same name are registered, the behavior is undefined. If a
6232 ** VFS is registered with a name that is NULL or an empty string,
6233 ** then the behavior is undefined.
6235 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6236 ** ^(If the default VFS is unregistered, another VFS is chosen as
6237 ** the default. The choice for the new VFS is arbitrary.)^
6239 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6240 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6241 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6244 ** CAPI3REF: Mutexes
6246 ** The SQLite core uses these routines for thread
6247 ** synchronization. Though they are intended for internal
6248 ** use by SQLite, code that links against SQLite is
6249 ** permitted to use any of these routines.
6251 ** The SQLite source code contains multiple implementations
6252 ** of these mutex routines. An appropriate implementation
6253 ** is selected automatically at compile-time. ^(The following
6254 ** implementations are available in the SQLite core:
6256 ** <ul>
6257 ** <li> SQLITE_MUTEX_PTHREADS
6258 ** <li> SQLITE_MUTEX_W32
6259 ** <li> SQLITE_MUTEX_NOOP
6260 ** </ul>)^
6262 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6263 ** that does no real locking and is appropriate for use in
6264 ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
6265 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6266 ** and Windows.
6268 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6269 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6270 ** implementation is included with the library. In this case the
6271 ** application must supply a custom mutex implementation using the
6272 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6273 ** before calling sqlite3_initialize() or any other public sqlite3_
6274 ** function that calls sqlite3_initialize().)^
6276 ** ^The sqlite3_mutex_alloc() routine allocates a new
6277 ** mutex and returns a pointer to it. ^If it returns NULL
6278 ** that means that a mutex could not be allocated. ^SQLite
6279 ** will unwind its stack and return an error. ^(The argument
6280 ** to sqlite3_mutex_alloc() is one of these integer constants:
6282 ** <ul>
6283 ** <li> SQLITE_MUTEX_FAST
6284 ** <li> SQLITE_MUTEX_RECURSIVE
6285 ** <li> SQLITE_MUTEX_STATIC_MASTER
6286 ** <li> SQLITE_MUTEX_STATIC_MEM
6287 ** <li> SQLITE_MUTEX_STATIC_MEM2
6288 ** <li> SQLITE_MUTEX_STATIC_PRNG
6289 ** <li> SQLITE_MUTEX_STATIC_LRU
6290 ** <li> SQLITE_MUTEX_STATIC_LRU2
6291 ** </ul>)^
6293 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6294 ** cause sqlite3_mutex_alloc() to create
6295 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6296 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6297 ** The mutex implementation does not need to make a distinction
6298 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6299 ** not want to. ^SQLite will only request a recursive mutex in
6300 ** cases where it really needs one. ^If a faster non-recursive mutex
6301 ** implementation is available on the host platform, the mutex subsystem
6302 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6304 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6305 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6306 ** a pointer to a static preexisting mutex. ^Six static mutexes are
6307 ** used by the current version of SQLite. Future versions of SQLite
6308 ** may add additional static mutexes. Static mutexes are for internal
6309 ** use by SQLite only. Applications that use SQLite mutexes should
6310 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6311 ** SQLITE_MUTEX_RECURSIVE.
6313 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6314 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6315 ** returns a different mutex on every call. ^But for the static
6316 ** mutex types, the same mutex is returned on every call that has
6317 ** the same type number.
6319 ** ^The sqlite3_mutex_free() routine deallocates a previously
6320 ** allocated dynamic mutex. ^SQLite is careful to deallocate every
6321 ** dynamic mutex that it allocates. The dynamic mutexes must not be in
6322 ** use when they are deallocated. Attempting to deallocate a static
6323 ** mutex results in undefined behavior. ^SQLite never deallocates
6324 ** a static mutex.
6326 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6327 ** to enter a mutex. ^If another thread is already within the mutex,
6328 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6329 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6330 ** upon successful entry. ^(Mutexes created using
6331 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6332 ** In such cases the,
6333 ** mutex must be exited an equal number of times before another thread
6334 ** can enter.)^ ^(If the same thread tries to enter any other
6335 ** kind of mutex more than once, the behavior is undefined.
6336 ** SQLite will never exhibit
6337 ** such behavior in its own use of mutexes.)^
6339 ** ^(Some systems (for example, Windows 95) do not support the operation
6340 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
6341 ** will always return SQLITE_BUSY. The SQLite core only ever uses
6342 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6344 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6345 ** previously entered by the same thread. ^(The behavior
6346 ** is undefined if the mutex is not currently entered by the
6347 ** calling thread or is not currently allocated. SQLite will
6348 ** never do either.)^
6350 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6351 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6352 ** behave as no-ops.
6354 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6356 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6357 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6358 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6359 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6360 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6363 ** CAPI3REF: Mutex Methods Object
6365 ** An instance of this structure defines the low-level routines
6366 ** used to allocate and use mutexes.
6368 ** Usually, the default mutex implementations provided by SQLite are
6369 ** sufficient, however the user has the option of substituting a custom
6370 ** implementation for specialized deployments or systems for which SQLite
6371 ** does not provide a suitable implementation. In this case, the user
6372 ** creates and populates an instance of this structure to pass
6373 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6374 ** Additionally, an instance of this structure can be used as an
6375 ** output variable when querying the system for the current mutex
6376 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6378 ** ^The xMutexInit method defined by this structure is invoked as
6379 ** part of system initialization by the sqlite3_initialize() function.
6380 ** ^The xMutexInit routine is called by SQLite exactly once for each
6381 ** effective call to [sqlite3_initialize()].
6383 ** ^The xMutexEnd method defined by this structure is invoked as
6384 ** part of system shutdown by the sqlite3_shutdown() function. The
6385 ** implementation of this method is expected to release all outstanding
6386 ** resources obtained by the mutex methods implementation, especially
6387 ** those obtained by the xMutexInit method. ^The xMutexEnd()
6388 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6390 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6391 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6392 ** xMutexNotheld) implement the following interfaces (respectively):
6394 ** <ul>
6395 ** <li> [sqlite3_mutex_alloc()] </li>
6396 ** <li> [sqlite3_mutex_free()] </li>
6397 ** <li> [sqlite3_mutex_enter()] </li>
6398 ** <li> [sqlite3_mutex_try()] </li>
6399 ** <li> [sqlite3_mutex_leave()] </li>
6400 ** <li> [sqlite3_mutex_held()] </li>
6401 ** <li> [sqlite3_mutex_notheld()] </li>
6402 ** </ul>)^
6404 ** The only difference is that the public sqlite3_XXX functions enumerated
6405 ** above silently ignore any invocations that pass a NULL pointer instead
6406 ** of a valid mutex handle. The implementations of the methods defined
6407 ** by this structure are not required to handle this case, the results
6408 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6409 ** (i.e. it is acceptable to provide an implementation that segfaults if
6410 ** it is passed a NULL pointer).
6412 ** The xMutexInit() method must be threadsafe. ^It must be harmless to
6413 ** invoke xMutexInit() multiple times within the same process and without
6414 ** intervening calls to xMutexEnd(). Second and subsequent calls to
6415 ** xMutexInit() must be no-ops.
6417 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6418 ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
6419 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
6420 ** memory allocation for a fast or recursive mutex.
6422 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6423 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6424 ** If xMutexInit fails in any way, it is expected to clean up after itself
6425 ** prior to returning.
6427 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6428 struct sqlite3_mutex_methods {
6429 int (*xMutexInit)(void);
6430 int (*xMutexEnd)(void);
6431 sqlite3_mutex *(*xMutexAlloc)(int);
6432 void (*xMutexFree)(sqlite3_mutex *);
6433 void (*xMutexEnter)(sqlite3_mutex *);
6434 int (*xMutexTry)(sqlite3_mutex *);
6435 void (*xMutexLeave)(sqlite3_mutex *);
6436 int (*xMutexHeld)(sqlite3_mutex *);
6437 int (*xMutexNotheld)(sqlite3_mutex *);
6441 ** CAPI3REF: Mutex Verification Routines
6443 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6444 ** are intended for use inside assert() statements. ^The SQLite core
6445 ** never uses these routines except inside an assert() and applications
6446 ** are advised to follow the lead of the core. ^The SQLite core only
6447 ** provides implementations for these routines when it is compiled
6448 ** with the SQLITE_DEBUG flag. ^External mutex implementations
6449 ** are only required to provide these routines if SQLITE_DEBUG is
6450 ** defined and if NDEBUG is not defined.
6452 ** ^These routines should return true if the mutex in their argument
6453 ** is held or not held, respectively, by the calling thread.
6455 ** ^The implementation is not required to provide versions of these
6456 ** routines that actually work. If the implementation does not provide working
6457 ** versions of these routines, it should at least provide stubs that always
6458 ** return true so that one does not get spurious assertion failures.
6460 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6461 ** the routine should return 1. This seems counter-intuitive since
6462 ** clearly the mutex cannot be held if it does not exist. But
6463 ** the reason the mutex does not exist is because the build is not
6464 ** using mutexes. And we do not want the assert() containing the
6465 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6466 ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
6467 ** interface should also return 1 when given a NULL pointer.
6469 #ifndef NDEBUG
6470 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6471 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6472 #endif
6475 ** CAPI3REF: Mutex Types
6477 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6478 ** which is one of these integer constants.
6480 ** The set of static mutexes may change from one SQLite release to the
6481 ** next. Applications that override the built-in mutex logic must be
6482 ** prepared to accommodate additional static mutexes.
6484 #define SQLITE_MUTEX_FAST 0
6485 #define SQLITE_MUTEX_RECURSIVE 1
6486 #define SQLITE_MUTEX_STATIC_MASTER 2
6487 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
6488 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
6489 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
6490 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
6491 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
6492 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
6493 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
6496 ** CAPI3REF: Retrieve the mutex for a database connection
6498 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6499 ** serializes access to the [database connection] given in the argument
6500 ** when the [threading mode] is Serialized.
6501 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6502 ** routine returns a NULL pointer.
6504 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6507 ** CAPI3REF: Low-Level Control Of Database Files
6509 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6510 ** xFileControl method for the [sqlite3_io_methods] object associated
6511 ** with a particular database identified by the second argument. ^The
6512 ** name of the database is "main" for the main database or "temp" for the
6513 ** TEMP database, or the name that appears after the AS keyword for
6514 ** databases that are added using the [ATTACH] SQL command.
6515 ** ^A NULL pointer can be used in place of "main" to refer to the
6516 ** main database file.
6517 ** ^The third and fourth parameters to this routine
6518 ** are passed directly through to the second and third parameters of
6519 ** the xFileControl method. ^The return value of the xFileControl
6520 ** method becomes the return value of this routine.
6522 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6523 ** a pointer to the underlying [sqlite3_file] object to be written into
6524 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
6525 ** case is a short-circuit path which does not actually invoke the
6526 ** underlying sqlite3_io_methods.xFileControl method.
6528 ** ^If the second parameter (zDbName) does not match the name of any
6529 ** open database file, then SQLITE_ERROR is returned. ^This error
6530 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6531 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
6532 ** also return SQLITE_ERROR. There is no way to distinguish between
6533 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6534 ** xFileControl method.
6536 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6538 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6541 ** CAPI3REF: Testing Interface
6543 ** ^The sqlite3_test_control() interface is used to read out internal
6544 ** state of SQLite and to inject faults into SQLite for testing
6545 ** purposes. ^The first parameter is an operation code that determines
6546 ** the number, meaning, and operation of all subsequent parameters.
6548 ** This interface is not for use by applications. It exists solely
6549 ** for verifying the correct operation of the SQLite library. Depending
6550 ** on how the SQLite library is compiled, this interface might not exist.
6552 ** The details of the operation codes, their meanings, the parameters
6553 ** they take, and what they do are all subject to change without notice.
6554 ** Unlike most of the SQLite API, this function is not guaranteed to
6555 ** operate consistently from one release to the next.
6557 SQLITE_API int sqlite3_test_control(int op, ...);
6560 ** CAPI3REF: Testing Interface Operation Codes
6562 ** These constants are the valid operation code parameters used
6563 ** as the first argument to [sqlite3_test_control()].
6565 ** These parameters and their meanings are subject to change
6566 ** without notice. These values are for testing purposes only.
6567 ** Applications should not use any of these parameters or the
6568 ** [sqlite3_test_control()] interface.
6570 #define SQLITE_TESTCTRL_FIRST 5
6571 #define SQLITE_TESTCTRL_PRNG_SAVE 5
6572 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
6573 #define SQLITE_TESTCTRL_PRNG_RESET 7
6574 #define SQLITE_TESTCTRL_BITVEC_TEST 8
6575 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
6576 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
6577 #define SQLITE_TESTCTRL_PENDING_BYTE 11
6578 #define SQLITE_TESTCTRL_ASSERT 12
6579 #define SQLITE_TESTCTRL_ALWAYS 13
6580 #define SQLITE_TESTCTRL_RESERVE 14
6581 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
6582 #define SQLITE_TESTCTRL_ISKEYWORD 16
6583 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
6584 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
6585 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19
6586 #define SQLITE_TESTCTRL_LAST 19
6589 ** CAPI3REF: SQLite Runtime Status
6591 ** ^This interface is used to retrieve runtime status information
6592 ** about the performance of SQLite, and optionally to reset various
6593 ** highwater marks. ^The first argument is an integer code for
6594 ** the specific parameter to measure. ^(Recognized integer codes
6595 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6596 ** ^The current value of the parameter is returned into *pCurrent.
6597 ** ^The highest recorded value is returned in *pHighwater. ^If the
6598 ** resetFlag is true, then the highest record value is reset after
6599 ** *pHighwater is written. ^(Some parameters do not record the highest
6600 ** value. For those parameters
6601 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6602 ** ^(Other parameters record only the highwater mark and not the current
6603 ** value. For these latter parameters nothing is written into *pCurrent.)^
6605 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6606 ** non-zero [error code] on failure.
6608 ** This routine is threadsafe but is not atomic. This routine can be
6609 ** called while other threads are running the same or different SQLite
6610 ** interfaces. However the values returned in *pCurrent and
6611 ** *pHighwater reflect the status of SQLite at different points in time
6612 ** and it is possible that another thread might change the parameter
6613 ** in between the times when *pCurrent and *pHighwater are written.
6615 ** See also: [sqlite3_db_status()]
6617 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6621 ** CAPI3REF: Status Parameters
6622 ** KEYWORDS: {status parameters}
6624 ** These integer constants designate various run-time status parameters
6625 ** that can be returned by [sqlite3_status()].
6627 ** <dl>
6628 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6629 ** <dd>This parameter is the current amount of memory checked out
6630 ** using [sqlite3_malloc()], either directly or indirectly. The
6631 ** figure includes calls made to [sqlite3_malloc()] by the application
6632 ** and internal memory usage by the SQLite library. Scratch memory
6633 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6634 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6635 ** this parameter. The amount returned is the sum of the allocation
6636 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6638 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6639 ** <dd>This parameter records the largest memory allocation request
6640 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6641 ** internal equivalents). Only the value returned in the
6642 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6643 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6645 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6646 ** <dd>This parameter records the number of separate memory allocations
6647 ** currently checked out.</dd>)^
6649 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6650 ** <dd>This parameter returns the number of pages used out of the
6651 ** [pagecache memory allocator] that was configured using
6652 ** [SQLITE_CONFIG_PAGECACHE]. The
6653 ** value returned is in pages, not in bytes.</dd>)^
6655 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6656 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6657 ** <dd>This parameter returns the number of bytes of page cache
6658 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6659 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
6660 ** returned value includes allocations that overflowed because they
6661 ** where too large (they were larger than the "sz" parameter to
6662 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6663 ** no space was left in the page cache.</dd>)^
6665 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6666 ** <dd>This parameter records the largest memory allocation request
6667 ** handed to [pagecache memory allocator]. Only the value returned in the
6668 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6669 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6671 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6672 ** <dd>This parameter returns the number of allocations used out of the
6673 ** [scratch memory allocator] configured using
6674 ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
6675 ** in bytes. Since a single thread may only have one scratch allocation
6676 ** outstanding at time, this parameter also reports the number of threads
6677 ** using scratch memory at the same time.</dd>)^
6679 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6680 ** <dd>This parameter returns the number of bytes of scratch memory
6681 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6682 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
6683 ** returned include overflows because the requested allocation was too
6684 ** larger (that is, because the requested allocation was larger than the
6685 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6686 ** slots were available.
6687 ** </dd>)^
6689 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6690 ** <dd>This parameter records the largest memory allocation request
6691 ** handed to [scratch memory allocator]. Only the value returned in the
6692 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6693 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6695 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6696 ** <dd>This parameter records the deepest parser stack. It is only
6697 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6698 ** </dl>
6700 ** New status parameters may be added from time to time.
6702 #define SQLITE_STATUS_MEMORY_USED 0
6703 #define SQLITE_STATUS_PAGECACHE_USED 1
6704 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
6705 #define SQLITE_STATUS_SCRATCH_USED 3
6706 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
6707 #define SQLITE_STATUS_MALLOC_SIZE 5
6708 #define SQLITE_STATUS_PARSER_STACK 6
6709 #define SQLITE_STATUS_PAGECACHE_SIZE 7
6710 #define SQLITE_STATUS_SCRATCH_SIZE 8
6711 #define SQLITE_STATUS_MALLOC_COUNT 9
6714 ** CAPI3REF: Database Connection Status
6716 ** ^This interface is used to retrieve runtime status information
6717 ** about a single [database connection]. ^The first argument is the
6718 ** database connection object to be interrogated. ^The second argument
6719 ** is an integer constant, taken from the set of
6720 ** [SQLITE_DBSTATUS options], that
6721 ** determines the parameter to interrogate. The set of
6722 ** [SQLITE_DBSTATUS options] is likely
6723 ** to grow in future releases of SQLite.
6725 ** ^The current value of the requested parameter is written into *pCur
6726 ** and the highest instantaneous value is written into *pHiwtr. ^If
6727 ** the resetFlg is true, then the highest instantaneous value is
6728 ** reset back down to the current value.
6730 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6731 ** non-zero [error code] on failure.
6733 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6735 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6738 ** CAPI3REF: Status Parameters for database connections
6739 ** KEYWORDS: {SQLITE_DBSTATUS options}
6741 ** These constants are the available integer "verbs" that can be passed as
6742 ** the second argument to the [sqlite3_db_status()] interface.
6744 ** New verbs may be added in future releases of SQLite. Existing verbs
6745 ** might be discontinued. Applications should check the return code from
6746 ** [sqlite3_db_status()] to make sure that the call worked.
6747 ** The [sqlite3_db_status()] interface will return a non-zero error code
6748 ** if a discontinued or unsupported verb is invoked.
6750 ** <dl>
6751 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6752 ** <dd>This parameter returns the number of lookaside memory slots currently
6753 ** checked out.</dd>)^
6755 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6756 ** <dd>This parameter returns the number malloc attempts that were
6757 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6758 ** the current value is always zero.)^
6760 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6761 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6762 ** <dd>This parameter returns the number malloc attempts that might have
6763 ** been satisfied using lookaside memory but failed due to the amount of
6764 ** memory requested being larger than the lookaside slot size.
6765 ** Only the high-water value is meaningful;
6766 ** the current value is always zero.)^
6768 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6769 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6770 ** <dd>This parameter returns the number malloc attempts that might have
6771 ** been satisfied using lookaside memory but failed due to all lookaside
6772 ** memory already being in use.
6773 ** Only the high-water value is meaningful;
6774 ** the current value is always zero.)^
6776 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6777 ** <dd>This parameter returns the approximate number of of bytes of heap
6778 ** memory used by all pager caches associated with the database connection.)^
6779 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6781 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6782 ** <dd>This parameter returns the approximate number of of bytes of heap
6783 ** memory used to store the schema for all databases associated
6784 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6785 ** ^The full amount of memory used by the schemas is reported, even if the
6786 ** schema memory is shared with other database connections due to
6787 ** [shared cache mode] being enabled.
6788 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6790 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6791 ** <dd>This parameter returns the approximate number of of bytes of heap
6792 ** and lookaside memory used by all prepared statements associated with
6793 ** the database connection.)^
6794 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6795 ** </dd>
6797 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6798 ** <dd>This parameter returns the number of pager cache hits that have
6799 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6800 ** is always 0.
6801 ** </dd>
6803 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6804 ** <dd>This parameter returns the number of pager cache misses that have
6805 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6806 ** is always 0.
6807 ** </dd>
6809 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6810 ** <dd>This parameter returns the number of dirty cache entries that have
6811 ** been written to disk. Specifically, the number of pages written to the
6812 ** wal file in wal mode databases, or the number of pages written to the
6813 ** database file in rollback mode databases. Any pages written as part of
6814 ** transaction rollback or database recovery operations are not included.
6815 ** If an IO or other error occurs while writing a page to disk, the effect
6816 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6817 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6818 ** </dd>
6820 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
6821 ** <dd>This parameter returns zero for the current value if and only if
6822 ** all foreign key constraints (deferred or immediate) have been
6823 ** resolved.)^ ^The highwater mark is always 0.
6824 ** </dd>
6825 ** </dl>
6827 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
6828 #define SQLITE_DBSTATUS_CACHE_USED 1
6829 #define SQLITE_DBSTATUS_SCHEMA_USED 2
6830 #define SQLITE_DBSTATUS_STMT_USED 3
6831 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
6832 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
6833 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
6834 #define SQLITE_DBSTATUS_CACHE_HIT 7
6835 #define SQLITE_DBSTATUS_CACHE_MISS 8
6836 #define SQLITE_DBSTATUS_CACHE_WRITE 9
6837 #define SQLITE_DBSTATUS_DEFERRED_FKS 10
6838 #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
6842 ** CAPI3REF: Prepared Statement Status
6844 ** ^(Each prepared statement maintains various
6845 ** [SQLITE_STMTSTATUS counters] that measure the number
6846 ** of times it has performed specific operations.)^ These counters can
6847 ** be used to monitor the performance characteristics of the prepared
6848 ** statements. For example, if the number of table steps greatly exceeds
6849 ** the number of table searches or result rows, that would tend to indicate
6850 ** that the prepared statement is using a full table scan rather than
6851 ** an index.
6853 ** ^(This interface is used to retrieve and reset counter values from
6854 ** a [prepared statement]. The first argument is the prepared statement
6855 ** object to be interrogated. The second argument
6856 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6857 ** to be interrogated.)^
6858 ** ^The current value of the requested counter is returned.
6859 ** ^If the resetFlg is true, then the counter is reset to zero after this
6860 ** interface call returns.
6862 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6864 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6867 ** CAPI3REF: Status Parameters for prepared statements
6868 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6870 ** These preprocessor macros define integer codes that name counter
6871 ** values associated with the [sqlite3_stmt_status()] interface.
6872 ** The meanings of the various counters are as follows:
6874 ** <dl>
6875 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6876 ** <dd>^This is the number of times that SQLite has stepped forward in
6877 ** a table as part of a full table scan. Large numbers for this counter
6878 ** may indicate opportunities for performance improvement through
6879 ** careful use of indices.</dd>
6881 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6882 ** <dd>^This is the number of sort operations that have occurred.
6883 ** A non-zero value in this counter may indicate an opportunity to
6884 ** improvement performance through careful use of indices.</dd>
6886 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6887 ** <dd>^This is the number of rows inserted into transient indices that
6888 ** were created automatically in order to help joins run faster.
6889 ** A non-zero value in this counter may indicate an opportunity to
6890 ** improvement performance by adding permanent indices that do not
6891 ** need to be reinitialized each time the statement is run.</dd>
6893 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
6894 ** <dd>^This is the number of virtual machine operations executed
6895 ** by the prepared statement if that number is less than or equal
6896 ** to 2147483647. The number of virtual machine operations can be
6897 ** used as a proxy for the total work done by the prepared statement.
6898 ** If the number of virtual machine operations exceeds 2147483647
6899 ** then the value returned by this statement status code is undefined.
6900 ** </dd>
6901 ** </dl>
6903 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
6904 #define SQLITE_STMTSTATUS_SORT 2
6905 #define SQLITE_STMTSTATUS_AUTOINDEX 3
6906 #define SQLITE_STMTSTATUS_VM_STEP 4
6909 ** CAPI3REF: Custom Page Cache Object
6911 ** The sqlite3_pcache type is opaque. It is implemented by
6912 ** the pluggable module. The SQLite core has no knowledge of
6913 ** its size or internal structure and never deals with the
6914 ** sqlite3_pcache object except by holding and passing pointers
6915 ** to the object.
6917 ** See [sqlite3_pcache_methods2] for additional information.
6919 typedef struct sqlite3_pcache sqlite3_pcache;
6922 ** CAPI3REF: Custom Page Cache Object
6924 ** The sqlite3_pcache_page object represents a single page in the
6925 ** page cache. The page cache will allocate instances of this
6926 ** object. Various methods of the page cache use pointers to instances
6927 ** of this object as parameters or as their return value.
6929 ** See [sqlite3_pcache_methods2] for additional information.
6931 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6932 struct sqlite3_pcache_page {
6933 void *pBuf; /* The content of the page */
6934 void *pExtra; /* Extra information associated with the page */
6938 ** CAPI3REF: Application Defined Page Cache.
6939 ** KEYWORDS: {page cache}
6941 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6942 ** register an alternative page cache implementation by passing in an
6943 ** instance of the sqlite3_pcache_methods2 structure.)^
6944 ** In many applications, most of the heap memory allocated by
6945 ** SQLite is used for the page cache.
6946 ** By implementing a
6947 ** custom page cache using this API, an application can better control
6948 ** the amount of memory consumed by SQLite, the way in which
6949 ** that memory is allocated and released, and the policies used to
6950 ** determine exactly which parts of a database file are cached and for
6951 ** how long.
6953 ** The alternative page cache mechanism is an
6954 ** extreme measure that is only needed by the most demanding applications.
6955 ** The built-in page cache is recommended for most uses.
6957 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6958 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
6959 ** the application may discard the parameter after the call to
6960 ** [sqlite3_config()] returns.)^
6962 ** [[the xInit() page cache method]]
6963 ** ^(The xInit() method is called once for each effective
6964 ** call to [sqlite3_initialize()])^
6965 ** (usually only once during the lifetime of the process). ^(The xInit()
6966 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6967 ** The intent of the xInit() method is to set up global data structures
6968 ** required by the custom page cache implementation.
6969 ** ^(If the xInit() method is NULL, then the
6970 ** built-in default page cache is used instead of the application defined
6971 ** page cache.)^
6973 ** [[the xShutdown() page cache method]]
6974 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6975 ** It can be used to clean up
6976 ** any outstanding resources before process shutdown, if required.
6977 ** ^The xShutdown() method may be NULL.
6979 ** ^SQLite automatically serializes calls to the xInit method,
6980 ** so the xInit method need not be threadsafe. ^The
6981 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6982 ** not need to be threadsafe either. All other methods must be threadsafe
6983 ** in multithreaded applications.
6985 ** ^SQLite will never invoke xInit() more than once without an intervening
6986 ** call to xShutdown().
6988 ** [[the xCreate() page cache methods]]
6989 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6990 ** SQLite will typically create one cache instance for each open database file,
6991 ** though this is not guaranteed. ^The
6992 ** first parameter, szPage, is the size in bytes of the pages that must
6993 ** be allocated by the cache. ^szPage will always a power of two. ^The
6994 ** second parameter szExtra is a number of bytes of extra storage
6995 ** associated with each page cache entry. ^The szExtra parameter will
6996 ** a number less than 250. SQLite will use the
6997 ** extra szExtra bytes on each page to store metadata about the underlying
6998 ** database page on disk. The value passed into szExtra depends
6999 ** on the SQLite version, the target platform, and how SQLite was compiled.
7000 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
7001 ** created will be used to cache database pages of a file stored on disk, or
7002 ** false if it is used for an in-memory database. The cache implementation
7003 ** does not have to do anything special based with the value of bPurgeable;
7004 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
7005 ** never invoke xUnpin() except to deliberately delete a page.
7006 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
7007 ** false will always have the "discard" flag set to true.
7008 ** ^Hence, a cache created with bPurgeable false will
7009 ** never contain any unpinned pages.
7011 ** [[the xCachesize() page cache method]]
7012 ** ^(The xCachesize() method may be called at any time by SQLite to set the
7013 ** suggested maximum cache-size (number of pages stored by) the cache
7014 ** instance passed as the first argument. This is the value configured using
7015 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
7016 ** parameter, the implementation is not required to do anything with this
7017 ** value; it is advisory only.
7019 ** [[the xPagecount() page cache methods]]
7020 ** The xPagecount() method must return the number of pages currently
7021 ** stored in the cache, both pinned and unpinned.
7023 ** [[the xFetch() page cache methods]]
7024 ** The xFetch() method locates a page in the cache and returns a pointer to
7025 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
7026 ** The pBuf element of the returned sqlite3_pcache_page object will be a
7027 ** pointer to a buffer of szPage bytes used to store the content of a
7028 ** single database page. The pExtra element of sqlite3_pcache_page will be
7029 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
7030 ** for each entry in the page cache.
7032 ** The page to be fetched is determined by the key. ^The minimum key value
7033 ** is 1. After it has been retrieved using xFetch, the page is considered
7034 ** to be "pinned".
7036 ** If the requested page is already in the page cache, then the page cache
7037 ** implementation must return a pointer to the page buffer with its content
7038 ** intact. If the requested page is not already in the cache, then the
7039 ** cache implementation should use the value of the createFlag
7040 ** parameter to help it determined what action to take:
7042 ** <table border=1 width=85% align=center>
7043 ** <tr><th> createFlag <th> Behavior when page is not already in cache
7044 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
7045 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7046 ** Otherwise return NULL.
7047 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
7048 ** NULL if allocating a new page is effectively impossible.
7049 ** </table>
7051 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
7052 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
7053 ** failed.)^ In between the to xFetch() calls, SQLite may
7054 ** attempt to unpin one or more cache pages by spilling the content of
7055 ** pinned pages to disk and synching the operating system disk cache.
7057 ** [[the xUnpin() page cache method]]
7058 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7059 ** as its second argument. If the third parameter, discard, is non-zero,
7060 ** then the page must be evicted from the cache.
7061 ** ^If the discard parameter is
7062 ** zero, then the page may be discarded or retained at the discretion of
7063 ** page cache implementation. ^The page cache implementation
7064 ** may choose to evict unpinned pages at any time.
7066 ** The cache must not perform any reference counting. A single
7067 ** call to xUnpin() unpins the page regardless of the number of prior calls
7068 ** to xFetch().
7070 ** [[the xRekey() page cache methods]]
7071 ** The xRekey() method is used to change the key value associated with the
7072 ** page passed as the second argument. If the cache
7073 ** previously contains an entry associated with newKey, it must be
7074 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7075 ** to be pinned.
7077 ** When SQLite calls the xTruncate() method, the cache must discard all
7078 ** existing cache entries with page numbers (keys) greater than or equal
7079 ** to the value of the iLimit parameter passed to xTruncate(). If any
7080 ** of these pages are pinned, they are implicitly unpinned, meaning that
7081 ** they can be safely discarded.
7083 ** [[the xDestroy() page cache method]]
7084 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7085 ** All resources associated with the specified cache should be freed. ^After
7086 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7087 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7088 ** functions.
7090 ** [[the xShrink() page cache method]]
7091 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7092 ** free up as much of heap memory as possible. The page cache implementation
7093 ** is not obligated to free any memory, but well-behaved implementations should
7094 ** do their best.
7096 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7097 struct sqlite3_pcache_methods2 {
7098 int iVersion;
7099 void *pArg;
7100 int (*xInit)(void*);
7101 void (*xShutdown)(void*);
7102 sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7103 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7104 int (*xPagecount)(sqlite3_pcache*);
7105 sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7106 void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7107 void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7108 unsigned oldKey, unsigned newKey);
7109 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7110 void (*xDestroy)(sqlite3_pcache*);
7111 void (*xShrink)(sqlite3_pcache*);
7115 ** This is the obsolete pcache_methods object that has now been replaced
7116 ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
7117 ** retained in the header file for backwards compatibility only.
7119 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7120 struct sqlite3_pcache_methods {
7121 void *pArg;
7122 int (*xInit)(void*);
7123 void (*xShutdown)(void*);
7124 sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7125 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7126 int (*xPagecount)(sqlite3_pcache*);
7127 void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7128 void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7129 void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7130 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7131 void (*xDestroy)(sqlite3_pcache*);
7136 ** CAPI3REF: Online Backup Object
7138 ** The sqlite3_backup object records state information about an ongoing
7139 ** online backup operation. ^The sqlite3_backup object is created by
7140 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7141 ** [sqlite3_backup_finish()].
7143 ** See Also: [Using the SQLite Online Backup API]
7145 typedef struct sqlite3_backup sqlite3_backup;
7148 ** CAPI3REF: Online Backup API.
7150 ** The backup API copies the content of one database into another.
7151 ** It is useful either for creating backups of databases or
7152 ** for copying in-memory databases to or from persistent files.
7154 ** See Also: [Using the SQLite Online Backup API]
7156 ** ^SQLite holds a write transaction open on the destination database file
7157 ** for the duration of the backup operation.
7158 ** ^The source database is read-locked only while it is being read;
7159 ** it is not locked continuously for the entire backup operation.
7160 ** ^Thus, the backup may be performed on a live source database without
7161 ** preventing other database connections from
7162 ** reading or writing to the source database while the backup is underway.
7164 ** ^(To perform a backup operation:
7165 ** <ol>
7166 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
7167 ** backup,
7168 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7169 ** the data between the two databases, and finally
7170 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
7171 ** associated with the backup operation.
7172 ** </ol>)^
7173 ** There should be exactly one call to sqlite3_backup_finish() for each
7174 ** successful call to sqlite3_backup_init().
7176 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7178 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7179 ** [database connection] associated with the destination database
7180 ** and the database name, respectively.
7181 ** ^The database name is "main" for the main database, "temp" for the
7182 ** temporary database, or the name specified after the AS keyword in
7183 ** an [ATTACH] statement for an attached database.
7184 ** ^The S and M arguments passed to
7185 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7186 ** and database name of the source database, respectively.
7187 ** ^The source and destination [database connections] (parameters S and D)
7188 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7189 ** an error.
7191 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7192 ** returned and an error code and error message are stored in the
7193 ** destination [database connection] D.
7194 ** ^The error code and message for the failed call to sqlite3_backup_init()
7195 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7196 ** [sqlite3_errmsg16()] functions.
7197 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7198 ** [sqlite3_backup] object.
7199 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7200 ** sqlite3_backup_finish() functions to perform the specified backup
7201 ** operation.
7203 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7205 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7206 ** the source and destination databases specified by [sqlite3_backup] object B.
7207 ** ^If N is negative, all remaining source pages are copied.
7208 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7209 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7210 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7211 ** from source to destination, then it returns [SQLITE_DONE].
7212 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7213 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7214 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7215 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7216 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7218 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7219 ** <ol>
7220 ** <li> the destination database was opened read-only, or
7221 ** <li> the destination database is using write-ahead-log journaling
7222 ** and the destination and source page sizes differ, or
7223 ** <li> the destination database is an in-memory database and the
7224 ** destination and source page sizes differ.
7225 ** </ol>)^
7227 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7228 ** the [sqlite3_busy_handler | busy-handler function]
7229 ** is invoked (if one is specified). ^If the
7230 ** busy-handler returns non-zero before the lock is available, then
7231 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7232 ** sqlite3_backup_step() can be retried later. ^If the source
7233 ** [database connection]
7234 ** is being used to write to the source database when sqlite3_backup_step()
7235 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7236 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7237 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7238 ** [SQLITE_READONLY] is returned, then
7239 ** there is no point in retrying the call to sqlite3_backup_step(). These
7240 ** errors are considered fatal.)^ The application must accept
7241 ** that the backup operation has failed and pass the backup operation handle
7242 ** to the sqlite3_backup_finish() to release associated resources.
7244 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7245 ** on the destination file. ^The exclusive lock is not released until either
7246 ** sqlite3_backup_finish() is called or the backup operation is complete
7247 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
7248 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7249 ** lasts for the duration of the sqlite3_backup_step() call.
7250 ** ^Because the source database is not locked between calls to
7251 ** sqlite3_backup_step(), the source database may be modified mid-way
7252 ** through the backup process. ^If the source database is modified by an
7253 ** external process or via a database connection other than the one being
7254 ** used by the backup operation, then the backup will be automatically
7255 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7256 ** database is modified by the using the same database connection as is used
7257 ** by the backup operation, then the backup database is automatically
7258 ** updated at the same time.
7260 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7262 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7263 ** application wishes to abandon the backup operation, the application
7264 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7265 ** ^The sqlite3_backup_finish() interfaces releases all
7266 ** resources associated with the [sqlite3_backup] object.
7267 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7268 ** active write-transaction on the destination database is rolled back.
7269 ** The [sqlite3_backup] object is invalid
7270 ** and may not be used following a call to sqlite3_backup_finish().
7272 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7273 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7274 ** sqlite3_backup_step() completed.
7275 ** ^If an out-of-memory condition or IO error occurred during any prior
7276 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7277 ** sqlite3_backup_finish() returns the corresponding [error code].
7279 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7280 ** is not a permanent error and does not affect the return value of
7281 ** sqlite3_backup_finish().
7283 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7284 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7286 ** ^Each call to sqlite3_backup_step() sets two values inside
7287 ** the [sqlite3_backup] object: the number of pages still to be backed
7288 ** up and the total number of pages in the source database file.
7289 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7290 ** retrieve these two values, respectively.
7292 ** ^The values returned by these functions are only updated by
7293 ** sqlite3_backup_step(). ^If the source database is modified during a backup
7294 ** operation, then the values are not updated to account for any extra
7295 ** pages that need to be updated or the size of the source database file
7296 ** changing.
7298 ** <b>Concurrent Usage of Database Handles</b>
7300 ** ^The source [database connection] may be used by the application for other
7301 ** purposes while a backup operation is underway or being initialized.
7302 ** ^If SQLite is compiled and configured to support threadsafe database
7303 ** connections, then the source database connection may be used concurrently
7304 ** from within other threads.
7306 ** However, the application must guarantee that the destination
7307 ** [database connection] is not passed to any other API (by any thread) after
7308 ** sqlite3_backup_init() is called and before the corresponding call to
7309 ** sqlite3_backup_finish(). SQLite does not currently check to see
7310 ** if the application incorrectly accesses the destination [database connection]
7311 ** and so no error code is reported, but the operations may malfunction
7312 ** nevertheless. Use of the destination database connection while a
7313 ** backup is in progress might also also cause a mutex deadlock.
7315 ** If running in [shared cache mode], the application must
7316 ** guarantee that the shared cache used by the destination database
7317 ** is not accessed while the backup is running. In practice this means
7318 ** that the application must guarantee that the disk file being
7319 ** backed up to is not accessed by any connection within the process,
7320 ** not just the specific connection that was passed to sqlite3_backup_init().
7322 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7323 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7324 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7325 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7326 ** same time as another thread is invoking sqlite3_backup_step() it is
7327 ** possible that they return invalid values.
7329 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7330 sqlite3 *pDest, /* Destination database handle */
7331 const char *zDestName, /* Destination database name */
7332 sqlite3 *pSource, /* Source database handle */
7333 const char *zSourceName /* Source database name */
7335 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7336 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7337 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7338 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7341 ** CAPI3REF: Unlock Notification
7343 ** ^When running in shared-cache mode, a database operation may fail with
7344 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7345 ** individual tables within the shared-cache cannot be obtained. See
7346 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7347 ** ^This API may be used to register a callback that SQLite will invoke
7348 ** when the connection currently holding the required lock relinquishes it.
7349 ** ^This API is only available if the library was compiled with the
7350 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7352 ** See Also: [Using the SQLite Unlock Notification Feature].
7354 ** ^Shared-cache locks are released when a database connection concludes
7355 ** its current transaction, either by committing it or rolling it back.
7357 ** ^When a connection (known as the blocked connection) fails to obtain a
7358 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7359 ** identity of the database connection (the blocking connection) that
7360 ** has locked the required resource is stored internally. ^After an
7361 ** application receives an SQLITE_LOCKED error, it may call the
7362 ** sqlite3_unlock_notify() method with the blocked connection handle as
7363 ** the first argument to register for a callback that will be invoked
7364 ** when the blocking connections current transaction is concluded. ^The
7365 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7366 ** call that concludes the blocking connections transaction.
7368 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7369 ** there is a chance that the blocking connection will have already
7370 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7371 ** If this happens, then the specified callback is invoked immediately,
7372 ** from within the call to sqlite3_unlock_notify().)^
7374 ** ^If the blocked connection is attempting to obtain a write-lock on a
7375 ** shared-cache table, and more than one other connection currently holds
7376 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7377 ** the other connections to use as the blocking connection.
7379 ** ^(There may be at most one unlock-notify callback registered by a
7380 ** blocked connection. If sqlite3_unlock_notify() is called when the
7381 ** blocked connection already has a registered unlock-notify callback,
7382 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7383 ** called with a NULL pointer as its second argument, then any existing
7384 ** unlock-notify callback is canceled. ^The blocked connections
7385 ** unlock-notify callback may also be canceled by closing the blocked
7386 ** connection using [sqlite3_close()].
7388 ** The unlock-notify callback is not reentrant. If an application invokes
7389 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7390 ** crash or deadlock may be the result.
7392 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7393 ** returns SQLITE_OK.
7395 ** <b>Callback Invocation Details</b>
7397 ** When an unlock-notify callback is registered, the application provides a
7398 ** single void* pointer that is passed to the callback when it is invoked.
7399 ** However, the signature of the callback function allows SQLite to pass
7400 ** it an array of void* context pointers. The first argument passed to
7401 ** an unlock-notify callback is a pointer to an array of void* pointers,
7402 ** and the second is the number of entries in the array.
7404 ** When a blocking connections transaction is concluded, there may be
7405 ** more than one blocked connection that has registered for an unlock-notify
7406 ** callback. ^If two or more such blocked connections have specified the
7407 ** same callback function, then instead of invoking the callback function
7408 ** multiple times, it is invoked once with the set of void* context pointers
7409 ** specified by the blocked connections bundled together into an array.
7410 ** This gives the application an opportunity to prioritize any actions
7411 ** related to the set of unblocked database connections.
7413 ** <b>Deadlock Detection</b>
7415 ** Assuming that after registering for an unlock-notify callback a
7416 ** database waits for the callback to be issued before taking any further
7417 ** action (a reasonable assumption), then using this API may cause the
7418 ** application to deadlock. For example, if connection X is waiting for
7419 ** connection Y's transaction to be concluded, and similarly connection
7420 ** Y is waiting on connection X's transaction, then neither connection
7421 ** will proceed and the system may remain deadlocked indefinitely.
7423 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7424 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7425 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7426 ** unlock-notify callback is registered. The system is said to be in
7427 ** a deadlocked state if connection A has registered for an unlock-notify
7428 ** callback on the conclusion of connection B's transaction, and connection
7429 ** B has itself registered for an unlock-notify callback when connection
7430 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7431 ** the system is also considered to be deadlocked if connection B has
7432 ** registered for an unlock-notify callback on the conclusion of connection
7433 ** C's transaction, where connection C is waiting on connection A. ^Any
7434 ** number of levels of indirection are allowed.
7436 ** <b>The "DROP TABLE" Exception</b>
7438 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7439 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7440 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7441 ** SQLite checks if there are any currently executing SELECT statements
7442 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7443 ** returned. In this case there is no "blocking connection", so invoking
7444 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7445 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7446 ** or "DROP INDEX" query, an infinite loop might be the result.
7448 ** One way around this problem is to check the extended error code returned
7449 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7450 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7451 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7452 ** SQLITE_LOCKED.)^
7454 SQLITE_API int sqlite3_unlock_notify(
7455 sqlite3 *pBlocked, /* Waiting connection */
7456 void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
7457 void *pNotifyArg /* Argument to pass to xNotify */
7462 ** CAPI3REF: String Comparison
7464 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7465 ** and extensions to compare the contents of two buffers containing UTF-8
7466 ** strings in a case-independent fashion, using the same definition of "case
7467 ** independence" that SQLite uses internally when comparing identifiers.
7469 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7470 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7473 ** CAPI3REF: String Globbing
7475 ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
7476 ** the glob pattern P, and it returns non-zero if string X does not match
7477 ** the glob pattern P. ^The definition of glob pattern matching used in
7478 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7479 ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
7480 ** sensitive.
7482 ** Note that this routine returns zero on a match and non-zero if the strings
7483 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7485 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
7488 ** CAPI3REF: Error Logging Interface
7490 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7491 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7492 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7493 ** used with [sqlite3_snprintf()] to generate the final output string.
7495 ** The sqlite3_log() interface is intended for use by extensions such as
7496 ** virtual tables, collating functions, and SQL functions. While there is
7497 ** nothing to prevent an application from calling sqlite3_log(), doing so
7498 ** is considered bad form.
7500 ** The zFormat string must not be NULL.
7502 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7503 ** will not use dynamically allocated memory. The log message is stored in
7504 ** a fixed-length buffer on the stack. If the log message is longer than
7505 ** a few hundred characters, it will be truncated to the length of the
7506 ** buffer.
7508 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7511 ** CAPI3REF: Write-Ahead Log Commit Hook
7513 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7514 ** will be invoked each time a database connection commits data to a
7515 ** [write-ahead log] (i.e. whenever a transaction is committed in
7516 ** [journal_mode | journal_mode=WAL mode]).
7518 ** ^The callback is invoked by SQLite after the commit has taken place and
7519 ** the associated write-lock on the database released, so the implementation
7520 ** may read, write or [checkpoint] the database as required.
7522 ** ^The first parameter passed to the callback function when it is invoked
7523 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7524 ** registering the callback. ^The second is a copy of the database handle.
7525 ** ^The third parameter is the name of the database that was written to -
7526 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7527 ** is the number of pages currently in the write-ahead log file,
7528 ** including those that were just committed.
7530 ** The callback function should normally return [SQLITE_OK]. ^If an error
7531 ** code is returned, that error will propagate back up through the
7532 ** SQLite code base to cause the statement that provoked the callback
7533 ** to report an error, though the commit will have still occurred. If the
7534 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7535 ** that does not correspond to any valid SQLite error code, the results
7536 ** are undefined.
7538 ** A single database handle may have at most a single write-ahead log callback
7539 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7540 ** previously registered write-ahead log callback. ^Note that the
7541 ** [sqlite3_wal_autocheckpoint()] interface and the
7542 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7543 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7545 SQLITE_API void *sqlite3_wal_hook(
7546 sqlite3*,
7547 int(*)(void *,sqlite3*,const char*,int),
7548 void*
7552 ** CAPI3REF: Configure an auto-checkpoint
7554 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7555 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7556 ** to automatically [checkpoint]
7557 ** after committing a transaction if there are N or
7558 ** more frames in the [write-ahead log] file. ^Passing zero or
7559 ** a negative value as the nFrame parameter disables automatic
7560 ** checkpoints entirely.
7562 ** ^The callback registered by this function replaces any existing callback
7563 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
7564 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7565 ** configured by this function.
7567 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7568 ** from SQL.
7570 ** ^Every new [database connection] defaults to having the auto-checkpoint
7571 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7572 ** pages. The use of this interface
7573 ** is only necessary if the default setting is found to be suboptimal
7574 ** for a particular application.
7576 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7579 ** CAPI3REF: Checkpoint a database
7581 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7582 ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
7583 ** empty string, then a checkpoint is run on all databases of
7584 ** connection D. ^If the database connection D is not in
7585 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7587 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7588 ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
7589 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7590 ** run whenever the WAL reaches a certain size threshold.
7592 ** See also: [sqlite3_wal_checkpoint_v2()]
7594 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7597 ** CAPI3REF: Checkpoint a database
7599 ** Run a checkpoint operation on WAL database zDb attached to database
7600 ** handle db. The specific operation is determined by the value of the
7601 ** eMode parameter:
7603 ** <dl>
7604 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7605 ** Checkpoint as many frames as possible without waiting for any database
7606 ** readers or writers to finish. Sync the db file if all frames in the log
7607 ** are checkpointed. This mode is the same as calling
7608 ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7610 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7611 ** This mode blocks (calls the busy-handler callback) until there is no
7612 ** database writer and all readers are reading from the most recent database
7613 ** snapshot. It then checkpoints all frames in the log file and syncs the
7614 ** database file. This call blocks database writers while it is running,
7615 ** but not database readers.
7617 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7618 ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7619 ** checkpointing the log file it blocks (calls the busy-handler callback)
7620 ** until all readers are reading from the database file only. This ensures
7621 ** that the next client to write to the database file restarts the log file
7622 ** from the beginning. This call blocks database writers while it is running,
7623 ** but not database readers.
7624 ** </dl>
7626 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7627 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7628 ** the total number of checkpointed frames (including any that were already
7629 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7630 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7631 ** If no values are available because of an error, they are both set to -1
7632 ** before returning to communicate this to the caller.
7634 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7635 ** any other process is running a checkpoint operation at the same time, the
7636 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7637 ** busy-handler configured, it will not be invoked in this case.
7639 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7640 ** "writer" lock on the database file. If the writer lock cannot be obtained
7641 ** immediately, and a busy-handler is configured, it is invoked and the writer
7642 ** lock retried until either the busy-handler returns 0 or the lock is
7643 ** successfully obtained. The busy-handler is also invoked while waiting for
7644 ** database readers as described above. If the busy-handler returns 0 before
7645 ** the writer lock is obtained or while waiting for database readers, the
7646 ** checkpoint operation proceeds from that point in the same way as
7647 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7648 ** without blocking any further. SQLITE_BUSY is returned in this case.
7650 ** If parameter zDb is NULL or points to a zero length string, then the
7651 ** specified operation is attempted on all WAL databases. In this case the
7652 ** values written to output parameters *pnLog and *pnCkpt are undefined. If
7653 ** an SQLITE_BUSY error is encountered when processing one or more of the
7654 ** attached WAL databases, the operation is still attempted on any remaining
7655 ** attached databases and SQLITE_BUSY is returned to the caller. If any other
7656 ** error occurs while processing an attached database, processing is abandoned
7657 ** and the error code returned to the caller immediately. If no error
7658 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7659 ** databases, SQLITE_OK is returned.
7661 ** If database zDb is the name of an attached database that is not in WAL
7662 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7663 ** zDb is not NULL (or a zero length string) and is not the name of any
7664 ** attached database, SQLITE_ERROR is returned to the caller.
7666 SQLITE_API int sqlite3_wal_checkpoint_v2(
7667 sqlite3 *db, /* Database handle */
7668 const char *zDb, /* Name of attached database (or NULL) */
7669 int eMode, /* SQLITE_CHECKPOINT_* value */
7670 int *pnLog, /* OUT: Size of WAL log in frames */
7671 int *pnCkpt /* OUT: Total number of frames checkpointed */
7675 ** CAPI3REF: Checkpoint operation parameters
7677 ** These constants can be used as the 3rd parameter to
7678 ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
7679 ** documentation for additional information about the meaning and use of
7680 ** each of these values.
7682 #define SQLITE_CHECKPOINT_PASSIVE 0
7683 #define SQLITE_CHECKPOINT_FULL 1
7684 #define SQLITE_CHECKPOINT_RESTART 2
7687 ** CAPI3REF: Virtual Table Interface Configuration
7689 ** This function may be called by either the [xConnect] or [xCreate] method
7690 ** of a [virtual table] implementation to configure
7691 ** various facets of the virtual table interface.
7693 ** If this interface is invoked outside the context of an xConnect or
7694 ** xCreate virtual table method then the behavior is undefined.
7696 ** At present, there is only one option that may be configured using
7697 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
7698 ** may be added in the future.
7700 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7703 ** CAPI3REF: Virtual Table Configuration Options
7705 ** These macros define the various options to the
7706 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7707 ** can use to customize and optimize their behavior.
7709 ** <dl>
7710 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7711 ** <dd>Calls of the form
7712 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7713 ** where X is an integer. If X is zero, then the [virtual table] whose
7714 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7715 ** support constraints. In this configuration (which is the default) if
7716 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7717 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7718 ** specified as part of the users SQL statement, regardless of the actual
7719 ** ON CONFLICT mode specified.
7721 ** If X is non-zero, then the virtual table implementation guarantees
7722 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7723 ** any modifications to internal or persistent data structures have been made.
7724 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7725 ** is able to roll back a statement or database transaction, and abandon
7726 ** or continue processing the current SQL statement as appropriate.
7727 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7728 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7729 ** had been ABORT.
7731 ** Virtual table implementations that are required to handle OR REPLACE
7732 ** must do so within the [xUpdate] method. If a call to the
7733 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7734 ** CONFLICT policy is REPLACE, the virtual table implementation should
7735 ** silently replace the appropriate rows within the xUpdate callback and
7736 ** return SQLITE_OK. Or, if this is not possible, it may return
7737 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7738 ** constraint handling.
7739 ** </dl>
7741 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7744 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7746 ** This function may only be called from within a call to the [xUpdate] method
7747 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7748 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7749 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7750 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7751 ** [virtual table].
7753 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7756 ** CAPI3REF: Conflict resolution modes
7758 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7759 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7760 ** is for the SQL statement being evaluated.
7762 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7763 ** return value from the [sqlite3_set_authorizer()] callback and that
7764 ** [SQLITE_ABORT] is also a [result code].
7766 #define SQLITE_ROLLBACK 1
7767 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7768 #define SQLITE_FAIL 3
7769 /* #define SQLITE_ABORT 4 // Also an error code */
7770 #define SQLITE_REPLACE 5
7775 ** Undo the hack that converts floating point types to integer for
7776 ** builds on processors without floating point support.
7778 #ifdef SQLITE_OMIT_FLOATING_POINT
7779 # undef double
7780 #endif
7782 #if 0
7783 } /* End of the 'extern "C"' block */
7784 #endif
7785 #endif /* _SQLITE3_H_ */
7788 ** 2010 August 30
7790 ** The author disclaims copyright to this source code. In place of
7791 ** a legal notice, here is a blessing:
7793 ** May you do good and not evil.
7794 ** May you find forgiveness for yourself and forgive others.
7795 ** May you share freely, never taking more than you give.
7797 *************************************************************************
7800 #ifndef _SQLITE3RTREE_H_
7801 #define _SQLITE3RTREE_H_
7804 #if 0
7805 extern "C" {
7806 #endif
7808 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7811 ** Register a geometry callback named zGeom that can be used as part of an
7812 ** R-Tree geometry query as follows:
7814 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7816 SQLITE_API int sqlite3_rtree_geometry_callback(
7817 sqlite3 *db,
7818 const char *zGeom,
7819 #ifdef SQLITE_RTREE_INT_ONLY
7820 int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
7821 #else
7822 int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
7823 #endif
7824 void *pContext
7829 ** A pointer to a structure of the following type is passed as the first
7830 ** argument to callbacks registered using rtree_geometry_callback().
7832 struct sqlite3_rtree_geometry {
7833 void *pContext; /* Copy of pContext passed to s_r_g_c() */
7834 int nParam; /* Size of array aParam[] */
7835 double *aParam; /* Parameters passed to SQL geom function */
7836 void *pUser; /* Callback implementation user data */
7837 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
7841 #if 0
7842 } /* end of the 'extern "C"' block */
7843 #endif
7845 #endif /* ifndef _SQLITE3RTREE_H_ */
7848 /************** End of sqlite3.h *********************************************/
7849 /************** Continuing where we left off in sqliteInt.h ******************/
7850 /************** Include hash.h in the middle of sqliteInt.h ******************/
7851 /************** Begin file hash.h ********************************************/
7853 ** 2001 September 22
7855 ** The author disclaims copyright to this source code. In place of
7856 ** a legal notice, here is a blessing:
7858 ** May you do good and not evil.
7859 ** May you find forgiveness for yourself and forgive others.
7860 ** May you share freely, never taking more than you give.
7862 *************************************************************************
7863 ** This is the header file for the generic hash-table implementation
7864 ** used in SQLite.
7866 #ifndef _SQLITE_HASH_H_
7867 #define _SQLITE_HASH_H_
7869 /* Forward declarations of structures. */
7870 typedef struct Hash Hash;
7871 typedef struct HashElem HashElem;
7873 /* A complete hash table is an instance of the following structure.
7874 ** The internals of this structure are intended to be opaque -- client
7875 ** code should not attempt to access or modify the fields of this structure
7876 ** directly. Change this structure only by using the routines below.
7877 ** However, some of the "procedures" and "functions" for modifying and
7878 ** accessing this structure are really macros, so we can't really make
7879 ** this structure opaque.
7881 ** All elements of the hash table are on a single doubly-linked list.
7882 ** Hash.first points to the head of this list.
7884 ** There are Hash.htsize buckets. Each bucket points to a spot in
7885 ** the global doubly-linked list. The contents of the bucket are the
7886 ** element pointed to plus the next _ht.count-1 elements in the list.
7888 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
7889 ** by a linear search of the global list. For small tables, the
7890 ** Hash.ht table is never allocated because if there are few elements
7891 ** in the table, it is faster to do a linear search than to manage
7892 ** the hash table.
7894 struct Hash {
7895 unsigned int htsize; /* Number of buckets in the hash table */
7896 unsigned int count; /* Number of entries in this table */
7897 HashElem *first; /* The first element of the array */
7898 struct _ht { /* the hash table */
7899 int count; /* Number of entries with this hash */
7900 HashElem *chain; /* Pointer to first entry with this hash */
7901 } *ht;
7904 /* Each element in the hash table is an instance of the following
7905 ** structure. All elements are stored on a single doubly-linked list.
7907 ** Again, this structure is intended to be opaque, but it can't really
7908 ** be opaque because it is used by macros.
7910 struct HashElem {
7911 HashElem *next, *prev; /* Next and previous elements in the table */
7912 void *data; /* Data associated with this element */
7913 const char *pKey; int nKey; /* Key associated with this element */
7917 ** Access routines. To delete, insert a NULL pointer.
7919 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7920 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7921 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7922 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7925 ** Macros for looping over all elements of a hash table. The idiom is
7926 ** like this:
7928 ** Hash h;
7929 ** HashElem *p;
7930 ** ...
7931 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7932 ** SomeStructure *pData = sqliteHashData(p);
7933 ** // do something with pData
7934 ** }
7936 #define sqliteHashFirst(H) ((H)->first)
7937 #define sqliteHashNext(E) ((E)->next)
7938 #define sqliteHashData(E) ((E)->data)
7939 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
7940 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
7943 ** Number of entries in a hash table
7945 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
7947 #endif /* _SQLITE_HASH_H_ */
7949 /************** End of hash.h ************************************************/
7950 /************** Continuing where we left off in sqliteInt.h ******************/
7951 /************** Include parse.h in the middle of sqliteInt.h *****************/
7952 /************** Begin file parse.h *******************************************/
7953 #define TK_SEMI 1
7954 #define TK_EXPLAIN 2
7955 #define TK_QUERY 3
7956 #define TK_PLAN 4
7957 #define TK_BEGIN 5
7958 #define TK_TRANSACTION 6
7959 #define TK_DEFERRED 7
7960 #define TK_IMMEDIATE 8
7961 #define TK_EXCLUSIVE 9
7962 #define TK_COMMIT 10
7963 #define TK_END 11
7964 #define TK_ROLLBACK 12
7965 #define TK_SAVEPOINT 13
7966 #define TK_RELEASE 14
7967 #define TK_TO 15
7968 #define TK_TABLE 16
7969 #define TK_CREATE 17
7970 #define TK_IF 18
7971 #define TK_NOT 19
7972 #define TK_EXISTS 20
7973 #define TK_TEMP 21
7974 #define TK_LP 22
7975 #define TK_RP 23
7976 #define TK_AS 24
7977 #define TK_COMMA 25
7978 #define TK_ID 26
7979 #define TK_INDEXED 27
7980 #define TK_ABORT 28
7981 #define TK_ACTION 29
7982 #define TK_AFTER 30
7983 #define TK_ANALYZE 31
7984 #define TK_ASC 32
7985 #define TK_ATTACH 33
7986 #define TK_BEFORE 34
7987 #define TK_BY 35
7988 #define TK_CASCADE 36
7989 #define TK_CAST 37
7990 #define TK_COLUMNKW 38
7991 #define TK_CONFLICT 39
7992 #define TK_DATABASE 40
7993 #define TK_DESC 41
7994 #define TK_DETACH 42
7995 #define TK_EACH 43
7996 #define TK_FAIL 44
7997 #define TK_FOR 45
7998 #define TK_IGNORE 46
7999 #define TK_INITIALLY 47
8000 #define TK_INSTEAD 48
8001 #define TK_LIKE_KW 49
8002 #define TK_MATCH 50
8003 #define TK_NO 51
8004 #define TK_KEY 52
8005 #define TK_OF 53
8006 #define TK_OFFSET 54
8007 #define TK_PRAGMA 55
8008 #define TK_RAISE 56
8009 #define TK_REPLACE 57
8010 #define TK_RESTRICT 58
8011 #define TK_ROW 59
8012 #define TK_TRIGGER 60
8013 #define TK_VACUUM 61
8014 #define TK_VIEW 62
8015 #define TK_VIRTUAL 63
8016 #define TK_REINDEX 64
8017 #define TK_RENAME 65
8018 #define TK_CTIME_KW 66
8019 #define TK_ANY 67
8020 #define TK_OR 68
8021 #define TK_AND 69
8022 #define TK_IS 70
8023 #define TK_BETWEEN 71
8024 #define TK_IN 72
8025 #define TK_ISNULL 73
8026 #define TK_NOTNULL 74
8027 #define TK_NE 75
8028 #define TK_EQ 76
8029 #define TK_GT 77
8030 #define TK_LE 78
8031 #define TK_LT 79
8032 #define TK_GE 80
8033 #define TK_ESCAPE 81
8034 #define TK_BITAND 82
8035 #define TK_BITOR 83
8036 #define TK_LSHIFT 84
8037 #define TK_RSHIFT 85
8038 #define TK_PLUS 86
8039 #define TK_MINUS 87
8040 #define TK_STAR 88
8041 #define TK_SLASH 89
8042 #define TK_REM 90
8043 #define TK_CONCAT 91
8044 #define TK_COLLATE 92
8045 #define TK_BITNOT 93
8046 #define TK_STRING 94
8047 #define TK_JOIN_KW 95
8048 #define TK_CONSTRAINT 96
8049 #define TK_DEFAULT 97
8050 #define TK_NULL 98
8051 #define TK_PRIMARY 99
8052 #define TK_UNIQUE 100
8053 #define TK_CHECK 101
8054 #define TK_REFERENCES 102
8055 #define TK_AUTOINCR 103
8056 #define TK_ON 104
8057 #define TK_INSERT 105
8058 #define TK_DELETE 106
8059 #define TK_UPDATE 107
8060 #define TK_SET 108
8061 #define TK_DEFERRABLE 109
8062 #define TK_FOREIGN 110
8063 #define TK_DROP 111
8064 #define TK_UNION 112
8065 #define TK_ALL 113
8066 #define TK_EXCEPT 114
8067 #define TK_INTERSECT 115
8068 #define TK_SELECT 116
8069 #define TK_DISTINCT 117
8070 #define TK_DOT 118
8071 #define TK_FROM 119
8072 #define TK_JOIN 120
8073 #define TK_USING 121
8074 #define TK_ORDER 122
8075 #define TK_GROUP 123
8076 #define TK_HAVING 124
8077 #define TK_LIMIT 125
8078 #define TK_WHERE 126
8079 #define TK_INTO 127
8080 #define TK_VALUES 128
8081 #define TK_INTEGER 129
8082 #define TK_FLOAT 130
8083 #define TK_BLOB 131
8084 #define TK_REGISTER 132
8085 #define TK_VARIABLE 133
8086 #define TK_CASE 134
8087 #define TK_WHEN 135
8088 #define TK_THEN 136
8089 #define TK_ELSE 137
8090 #define TK_INDEX 138
8091 #define TK_ALTER 139
8092 #define TK_ADD 140
8093 #define TK_TO_TEXT 141
8094 #define TK_TO_BLOB 142
8095 #define TK_TO_NUMERIC 143
8096 #define TK_TO_INT 144
8097 #define TK_TO_REAL 145
8098 #define TK_ISNOT 146
8099 #define TK_END_OF_FILE 147
8100 #define TK_ILLEGAL 148
8101 #define TK_SPACE 149
8102 #define TK_UNCLOSED_STRING 150
8103 #define TK_FUNCTION 151
8104 #define TK_COLUMN 152
8105 #define TK_AGG_FUNCTION 153
8106 #define TK_AGG_COLUMN 154
8107 #define TK_CONST_FUNC 155
8108 #define TK_UMINUS 156
8109 #define TK_UPLUS 157
8111 /************** End of parse.h ***********************************************/
8112 /************** Continuing where we left off in sqliteInt.h ******************/
8113 #include <stdio.h>
8114 #include <stdlib.h>
8115 #include <string.h>
8116 #include <assert.h>
8117 #include <stddef.h>
8120 ** If compiling for a processor that lacks floating point support,
8121 ** substitute integer for floating-point
8123 #ifdef SQLITE_OMIT_FLOATING_POINT
8124 # define double sqlite_int64
8125 # define float sqlite_int64
8126 # define LONGDOUBLE_TYPE sqlite_int64
8127 # ifndef SQLITE_BIG_DBL
8128 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8129 # endif
8130 # define SQLITE_OMIT_DATETIME_FUNCS 1
8131 # define SQLITE_OMIT_TRACE 1
8132 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8133 # undef SQLITE_HAVE_ISNAN
8134 #endif
8135 #ifndef SQLITE_BIG_DBL
8136 # define SQLITE_BIG_DBL (1e99)
8137 #endif
8140 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8141 ** afterward. Having this macro allows us to cause the C compiler
8142 ** to omit code used by TEMP tables without messy #ifndef statements.
8144 #ifdef SQLITE_OMIT_TEMPDB
8145 #define OMIT_TEMPDB 1
8146 #else
8147 #define OMIT_TEMPDB 0
8148 #endif
8151 ** The "file format" number is an integer that is incremented whenever
8152 ** the VDBE-level file format changes. The following macros define the
8153 ** the default file format for new databases and the maximum file format
8154 ** that the library can read.
8156 #define SQLITE_MAX_FILE_FORMAT 4
8157 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8158 # define SQLITE_DEFAULT_FILE_FORMAT 4
8159 #endif
8162 ** Determine whether triggers are recursive by default. This can be
8163 ** changed at run-time using a pragma.
8165 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8166 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8167 #endif
8170 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8171 ** on the command-line
8173 #ifndef SQLITE_TEMP_STORE
8174 # define SQLITE_TEMP_STORE 1
8175 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
8176 #endif
8179 ** GCC does not define the offsetof() macro so we'll have to do it
8180 ** ourselves.
8182 #ifndef offsetof
8183 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8184 #endif
8187 ** Macros to compute minimum and maximum of two numbers.
8189 #define MIN(A,B) ((A)<(B)?(A):(B))
8190 #define MAX(A,B) ((A)>(B)?(A):(B))
8193 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
8194 ** not, there are still machines out there that use EBCDIC.)
8196 #if 'A' == '\301'
8197 # define SQLITE_EBCDIC 1
8198 #else
8199 # define SQLITE_ASCII 1
8200 #endif
8203 ** Integers of known sizes. These typedefs might change for architectures
8204 ** where the sizes very. Preprocessor macros are available so that the
8205 ** types can be conveniently redefined at compile-type. Like this:
8207 ** cc '-DUINTPTR_TYPE=long long int' ...
8209 #ifndef UINT32_TYPE
8210 # ifdef HAVE_UINT32_T
8211 # define UINT32_TYPE uint32_t
8212 # else
8213 # define UINT32_TYPE unsigned int
8214 # endif
8215 #endif
8216 #ifndef UINT16_TYPE
8217 # ifdef HAVE_UINT16_T
8218 # define UINT16_TYPE uint16_t
8219 # else
8220 # define UINT16_TYPE unsigned short int
8221 # endif
8222 #endif
8223 #ifndef INT16_TYPE
8224 # ifdef HAVE_INT16_T
8225 # define INT16_TYPE int16_t
8226 # else
8227 # define INT16_TYPE short int
8228 # endif
8229 #endif
8230 #ifndef UINT8_TYPE
8231 # ifdef HAVE_UINT8_T
8232 # define UINT8_TYPE uint8_t
8233 # else
8234 # define UINT8_TYPE unsigned char
8235 # endif
8236 #endif
8237 #ifndef INT8_TYPE
8238 # ifdef HAVE_INT8_T
8239 # define INT8_TYPE int8_t
8240 # else
8241 # define INT8_TYPE signed char
8242 # endif
8243 #endif
8244 #ifndef LONGDOUBLE_TYPE
8245 # define LONGDOUBLE_TYPE long double
8246 #endif
8247 typedef sqlite_int64 i64; /* 8-byte signed integer */
8248 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
8249 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
8250 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
8251 typedef INT16_TYPE i16; /* 2-byte signed integer */
8252 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
8253 typedef INT8_TYPE i8; /* 1-byte signed integer */
8256 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8257 ** that can be stored in a u32 without loss of data. The value
8258 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
8259 ** have to specify the value in the less intuitive manner shown:
8261 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
8264 ** The datatype used to store estimates of the number of rows in a
8265 ** table or index. This is an unsigned integer type. For 99.9% of
8266 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
8267 ** can be used at compile-time if desired.
8269 #ifdef SQLITE_64BIT_STATS
8270 typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
8271 #else
8272 typedef u32 tRowcnt; /* 32-bit is the default */
8273 #endif
8276 ** Macros to determine whether the machine is big or little endian,
8277 ** evaluated at runtime.
8279 #ifdef SQLITE_AMALGAMATION
8280 SQLITE_PRIVATE const int sqlite3one = 1;
8281 #else
8282 SQLITE_PRIVATE const int sqlite3one;
8283 #endif
8284 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
8285 || defined(__x86_64) || defined(__x86_64__)
8286 # define SQLITE_BIGENDIAN 0
8287 # define SQLITE_LITTLEENDIAN 1
8288 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
8289 #else
8290 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
8291 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8292 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8293 #endif
8296 ** Constants for the largest and smallest possible 64-bit signed integers.
8297 ** These macros are designed to work correctly on both 32-bit and 64-bit
8298 ** compilers.
8300 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
8301 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8304 ** Round up a number to the next larger multiple of 8. This is used
8305 ** to force 8-byte alignment on 64-bit architectures.
8307 #define ROUND8(x) (((x)+7)&~7)
8310 ** Round down to the nearest multiple of 8
8312 #define ROUNDDOWN8(x) ((x)&~7)
8315 ** Assert that the pointer X is aligned to an 8-byte boundary. This
8316 ** macro is used only within assert() to verify that the code gets
8317 ** all alignment restrictions correct.
8319 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8320 ** underlying malloc() implemention might return us 4-byte aligned
8321 ** pointers. In that case, only verify 4-byte alignment.
8323 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8324 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
8325 #else
8326 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
8327 #endif
8330 ** Disable MMAP on platforms where it is known to not work
8332 #if defined(__OpenBSD__) || defined(__QNXNTO__)
8333 # undef SQLITE_MAX_MMAP_SIZE
8334 # define SQLITE_MAX_MMAP_SIZE 0
8335 #endif
8338 ** Default maximum size of memory used by memory-mapped I/O in the VFS
8340 #ifdef __APPLE__
8341 # include <TargetConditionals.h>
8342 # if TARGET_OS_IPHONE
8343 # undef SQLITE_MAX_MMAP_SIZE
8344 # define SQLITE_MAX_MMAP_SIZE 0
8345 # endif
8346 #endif
8347 #ifndef SQLITE_MAX_MMAP_SIZE
8348 # if defined(__linux__) \
8349 || defined(_WIN32) \
8350 || (defined(__APPLE__) && defined(__MACH__)) \
8351 || defined(__sun)
8352 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
8353 # else
8354 # define SQLITE_MAX_MMAP_SIZE 0
8355 # endif
8356 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
8357 #endif
8360 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
8361 ** default MMAP_SIZE is specified at compile-time, make sure that it does
8362 ** not exceed the maximum mmap size.
8364 #ifndef SQLITE_DEFAULT_MMAP_SIZE
8365 # define SQLITE_DEFAULT_MMAP_SIZE 0
8366 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
8367 #endif
8368 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
8369 # undef SQLITE_DEFAULT_MMAP_SIZE
8370 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
8371 #endif
8374 ** An instance of the following structure is used to store the busy-handler
8375 ** callback for a given sqlite handle.
8377 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8378 ** callback for the database handle. Each pager opened via the sqlite
8379 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8380 ** callback is currently invoked only from within pager.c.
8382 typedef struct BusyHandler BusyHandler;
8383 struct BusyHandler {
8384 int (*xFunc)(void *,int); /* The busy callback */
8385 void *pArg; /* First arg to busy callback */
8386 int nBusy; /* Incremented with each busy call */
8390 ** Name of the master database table. The master database table
8391 ** is a special table that holds the names and attributes of all
8392 ** user tables and indices.
8394 #define MASTER_NAME "sqlite_master"
8395 #define TEMP_MASTER_NAME "sqlite_temp_master"
8398 ** The root-page of the master database table.
8400 #define MASTER_ROOT 1
8403 ** The name of the schema table.
8405 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8408 ** A convenience macro that returns the number of elements in
8409 ** an array.
8411 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
8414 ** Determine if the argument is a power of two
8416 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
8419 ** The following value as a destructor means to use sqlite3DbFree().
8420 ** The sqlite3DbFree() routine requires two parameters instead of the
8421 ** one parameter that destructors normally want. So we have to introduce
8422 ** this magic value that the code knows to handle differently. Any
8423 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8424 ** and SQLITE_TRANSIENT.
8426 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
8429 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8430 ** not support Writable Static Data (WSD) such as global and static variables.
8431 ** All variables must either be on the stack or dynamically allocated from
8432 ** the heap. When WSD is unsupported, the variable declarations scattered
8433 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
8434 ** macro is used for this purpose. And instead of referencing the variable
8435 ** directly, we use its constant as a key to lookup the run-time allocated
8436 ** buffer that holds real variable. The constant is also the initializer
8437 ** for the run-time allocated buffer.
8439 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8440 ** macros become no-ops and have zero performance impact.
8442 #ifdef SQLITE_OMIT_WSD
8443 #define SQLITE_WSD const
8444 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8445 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8446 SQLITE_API int sqlite3_wsd_init(int N, int J);
8447 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
8448 #else
8449 #define SQLITE_WSD
8450 #define GLOBAL(t,v) v
8451 #define sqlite3GlobalConfig sqlite3Config
8452 #endif
8455 ** The following macros are used to suppress compiler warnings and to
8456 ** make it clear to human readers when a function parameter is deliberately
8457 ** left unused within the body of a function. This usually happens when
8458 ** a function is called via a function pointer. For example the
8459 ** implementation of an SQL aggregate step callback may not use the
8460 ** parameter indicating the number of arguments passed to the aggregate,
8461 ** if it knows that this is enforced elsewhere.
8463 ** When a function parameter is not used at all within the body of a function,
8464 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8465 ** However, these macros may also be used to suppress warnings related to
8466 ** parameters that may or may not be used depending on compilation options.
8467 ** For example those parameters only used in assert() statements. In these
8468 ** cases the parameters are named as per the usual conventions.
8470 #define UNUSED_PARAMETER(x) (void)(x)
8471 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8474 ** Forward references to structures
8476 typedef struct AggInfo AggInfo;
8477 typedef struct AuthContext AuthContext;
8478 typedef struct AutoincInfo AutoincInfo;
8479 typedef struct Bitvec Bitvec;
8480 typedef struct CollSeq CollSeq;
8481 typedef struct Column Column;
8482 typedef struct Db Db;
8483 typedef struct Schema Schema;
8484 typedef struct Expr Expr;
8485 typedef struct ExprList ExprList;
8486 typedef struct ExprSpan ExprSpan;
8487 typedef struct FKey FKey;
8488 typedef struct FuncDestructor FuncDestructor;
8489 typedef struct FuncDef FuncDef;
8490 typedef struct FuncDefHash FuncDefHash;
8491 typedef struct IdList IdList;
8492 typedef struct Index Index;
8493 typedef struct IndexSample IndexSample;
8494 typedef struct KeyClass KeyClass;
8495 typedef struct KeyInfo KeyInfo;
8496 typedef struct Lookaside Lookaside;
8497 typedef struct LookasideSlot LookasideSlot;
8498 typedef struct Module Module;
8499 typedef struct NameContext NameContext;
8500 typedef struct Parse Parse;
8501 typedef struct RowSet RowSet;
8502 typedef struct Savepoint Savepoint;
8503 typedef struct Select Select;
8504 typedef struct SelectDest SelectDest;
8505 typedef struct SrcList SrcList;
8506 typedef struct StrAccum StrAccum;
8507 typedef struct Table Table;
8508 typedef struct TableLock TableLock;
8509 typedef struct Token Token;
8510 typedef struct Trigger Trigger;
8511 typedef struct TriggerPrg TriggerPrg;
8512 typedef struct TriggerStep TriggerStep;
8513 typedef struct UnpackedRecord UnpackedRecord;
8514 typedef struct VTable VTable;
8515 typedef struct VtabCtx VtabCtx;
8516 typedef struct Walker Walker;
8517 typedef struct WhereInfo WhereInfo;
8520 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
8521 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8522 ** pointer types (i.e. FuncDef) defined above.
8524 /************** Include btree.h in the middle of sqliteInt.h *****************/
8525 /************** Begin file btree.h *******************************************/
8527 ** 2001 September 15
8529 ** The author disclaims copyright to this source code. In place of
8530 ** a legal notice, here is a blessing:
8532 ** May you do good and not evil.
8533 ** May you find forgiveness for yourself and forgive others.
8534 ** May you share freely, never taking more than you give.
8536 *************************************************************************
8537 ** This header file defines the interface that the sqlite B-Tree file
8538 ** subsystem. See comments in the source code for a detailed description
8539 ** of what each interface routine does.
8541 #ifndef _BTREE_H_
8542 #define _BTREE_H_
8544 /* TODO: This definition is just included so other modules compile. It
8545 ** needs to be revisited.
8547 #define SQLITE_N_BTREE_META 10
8550 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8551 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8553 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8554 #define SQLITE_DEFAULT_AUTOVACUUM 0
8555 #endif
8557 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
8558 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
8559 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
8562 ** Forward declarations of structure
8564 typedef struct Btree Btree;
8565 typedef struct BtCursor BtCursor;
8566 typedef struct BtShared BtShared;
8569 SQLITE_PRIVATE int sqlite3BtreeOpen(
8570 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
8571 const char *zFilename, /* Name of database file to open */
8572 sqlite3 *db, /* Associated database connection */
8573 Btree **ppBtree, /* Return open Btree* here */
8574 int flags, /* Flags */
8575 int vfsFlags /* Flags passed through to VFS open */
8578 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8579 ** following values.
8581 ** NOTE: These values must match the corresponding PAGER_ values in
8582 ** pager.h.
8584 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
8585 #define BTREE_MEMORY 2 /* This is an in-memory DB */
8586 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
8587 #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
8589 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8590 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8591 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
8592 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
8593 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8594 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8595 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8596 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8597 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8598 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8599 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8600 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
8601 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
8602 #endif
8603 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8604 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8605 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8606 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8607 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8608 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8609 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8610 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8611 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8612 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8613 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8614 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8615 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8616 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8617 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8618 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8620 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8621 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8622 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8624 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8626 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8627 ** of the flags shown below.
8629 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8630 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8631 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
8632 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8633 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
8634 ** indices.)
8636 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
8637 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
8639 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8640 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8641 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8643 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8644 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8646 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
8649 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8650 ** should be one of the following values. The integer values are assigned
8651 ** to constants so that the offset of the corresponding field in an
8652 ** SQLite database header may be found using the following formula:
8654 ** offset = 36 + (idx * 4)
8656 ** For example, the free-page-count field is located at byte offset 36 of
8657 ** the database file header. The incr-vacuum-flag field is located at
8658 ** byte offset 64 (== 36+4*7).
8660 #define BTREE_FREE_PAGE_COUNT 0
8661 #define BTREE_SCHEMA_VERSION 1
8662 #define BTREE_FILE_FORMAT 2
8663 #define BTREE_DEFAULT_CACHE_SIZE 3
8664 #define BTREE_LARGEST_ROOT_PAGE 4
8665 #define BTREE_TEXT_ENCODING 5
8666 #define BTREE_USER_VERSION 6
8667 #define BTREE_INCR_VACUUM 7
8668 #define BTREE_APPLICATION_ID 8
8671 ** Values that may be OR'd together to form the second argument of an
8672 ** sqlite3BtreeCursorHints() call.
8674 #define BTREE_BULKLOAD 0x00000001
8676 SQLITE_PRIVATE int sqlite3BtreeCursor(
8677 Btree*, /* BTree containing table to open */
8678 int iTable, /* Index of root page */
8679 int wrFlag, /* 1 for writing. 0 for read-only */
8680 struct KeyInfo*, /* First argument to compare function */
8681 BtCursor *pCursor /* Space to write cursor structure */
8683 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8684 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8686 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8687 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8688 BtCursor*,
8689 UnpackedRecord *pUnKey,
8690 i64 intKey,
8691 int bias,
8692 int *pRes
8694 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8695 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8696 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8697 const void *pData, int nData,
8698 int nZero, int bias, int seekResult);
8699 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8700 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8701 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8702 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8703 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8704 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8705 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8706 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8707 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8708 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8709 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8710 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8711 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8713 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8714 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8716 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8717 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8718 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8719 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8720 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
8722 #ifndef NDEBUG
8723 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8724 #endif
8726 #ifndef SQLITE_OMIT_BTREECOUNT
8727 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8728 #endif
8730 #ifdef SQLITE_TEST
8731 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8732 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8733 #endif
8735 #ifndef SQLITE_OMIT_WAL
8736 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8737 #endif
8740 ** If we are not using shared cache, then there is no need to
8741 ** use mutexes to access the BtShared structures. So make the
8742 ** Enter and Leave procedures no-ops.
8744 #ifndef SQLITE_OMIT_SHARED_CACHE
8745 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
8746 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
8747 #else
8748 # define sqlite3BtreeEnter(X)
8749 # define sqlite3BtreeEnterAll(X)
8750 #endif
8752 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8753 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
8754 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
8755 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
8756 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
8757 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
8758 #ifndef NDEBUG
8759 /* These routines are used inside assert() statements only. */
8760 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
8761 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8762 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8763 #endif
8764 #else
8766 # define sqlite3BtreeSharable(X) 0
8767 # define sqlite3BtreeLeave(X)
8768 # define sqlite3BtreeEnterCursor(X)
8769 # define sqlite3BtreeLeaveCursor(X)
8770 # define sqlite3BtreeLeaveAll(X)
8772 # define sqlite3BtreeHoldsMutex(X) 1
8773 # define sqlite3BtreeHoldsAllMutexes(X) 1
8774 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8775 #endif
8778 #endif /* _BTREE_H_ */
8780 /************** End of btree.h ***********************************************/
8781 /************** Continuing where we left off in sqliteInt.h ******************/
8782 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8783 /************** Begin file vdbe.h ********************************************/
8785 ** 2001 September 15
8787 ** The author disclaims copyright to this source code. In place of
8788 ** a legal notice, here is a blessing:
8790 ** May you do good and not evil.
8791 ** May you find forgiveness for yourself and forgive others.
8792 ** May you share freely, never taking more than you give.
8794 *************************************************************************
8795 ** Header file for the Virtual DataBase Engine (VDBE)
8797 ** This header defines the interface to the virtual database engine
8798 ** or VDBE. The VDBE implements an abstract machine that runs a
8799 ** simple program to access and modify the underlying database.
8801 #ifndef _SQLITE_VDBE_H_
8802 #define _SQLITE_VDBE_H_
8803 /* #include <stdio.h> */
8806 ** A single VDBE is an opaque structure named "Vdbe". Only routines
8807 ** in the source file sqliteVdbe.c are allowed to see the insides
8808 ** of this structure.
8810 typedef struct Vdbe Vdbe;
8813 ** The names of the following types declared in vdbeInt.h are required
8814 ** for the VdbeOp definition.
8816 typedef struct Mem Mem;
8817 typedef struct SubProgram SubProgram;
8820 ** A single instruction of the virtual machine has an opcode
8821 ** and as many as three operands. The instruction is recorded
8822 ** as an instance of the following structure:
8824 struct VdbeOp {
8825 u8 opcode; /* What operation to perform */
8826 signed char p4type; /* One of the P4_xxx constants for p4 */
8827 u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
8828 u8 p5; /* Fifth parameter is an unsigned character */
8829 int p1; /* First operand */
8830 int p2; /* Second parameter (often the jump destination) */
8831 int p3; /* The third parameter */
8832 union { /* fourth parameter */
8833 int i; /* Integer value if p4type==P4_INT32 */
8834 void *p; /* Generic pointer */
8835 char *z; /* Pointer to data for string (char array) types */
8836 i64 *pI64; /* Used when p4type is P4_INT64 */
8837 double *pReal; /* Used when p4type is P4_REAL */
8838 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
8839 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
8840 Mem *pMem; /* Used when p4type is P4_MEM */
8841 VTable *pVtab; /* Used when p4type is P4_VTAB */
8842 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
8843 int *ai; /* Used when p4type is P4_INTARRAY */
8844 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
8845 int (*xAdvance)(BtCursor *, int *);
8846 } p4;
8847 #ifdef SQLITE_DEBUG
8848 char *zComment; /* Comment to improve readability */
8849 #endif
8850 #ifdef VDBE_PROFILE
8851 int cnt; /* Number of times this instruction was executed */
8852 u64 cycles; /* Total time spent executing this instruction */
8853 #endif
8855 typedef struct VdbeOp VdbeOp;
8859 ** A sub-routine used to implement a trigger program.
8861 struct SubProgram {
8862 VdbeOp *aOp; /* Array of opcodes for sub-program */
8863 int nOp; /* Elements in aOp[] */
8864 int nMem; /* Number of memory cells required */
8865 int nCsr; /* Number of cursors required */
8866 int nOnce; /* Number of OP_Once instructions */
8867 void *token; /* id that may be used to recursive triggers */
8868 SubProgram *pNext; /* Next sub-program already visited */
8872 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8873 ** it takes up less space.
8875 struct VdbeOpList {
8876 u8 opcode; /* What operation to perform */
8877 signed char p1; /* First operand */
8878 signed char p2; /* Second parameter (often the jump destination) */
8879 signed char p3; /* Third parameter */
8881 typedef struct VdbeOpList VdbeOpList;
8884 ** Allowed values of VdbeOp.p4type
8886 #define P4_NOTUSED 0 /* The P4 parameter is not used */
8887 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
8888 #define P4_STATIC (-2) /* Pointer to a static string */
8889 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
8890 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
8891 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
8892 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
8893 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
8894 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8895 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8896 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
8897 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
8898 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
8899 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8900 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
8901 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8903 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8904 ** is made. That copy is freed when the Vdbe is finalized. But if the
8905 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
8906 ** gets freed when the Vdbe is finalized so it still should be obtained
8907 ** from a single sqliteMalloc(). But no copy is made and the calling
8908 ** function should *not* try to free the KeyInfo.
8910 #define P4_KEYINFO_HANDOFF (-16)
8911 #define P4_KEYINFO_STATIC (-17)
8914 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
8915 ** number of columns of data returned by the statement.
8917 #define COLNAME_NAME 0
8918 #define COLNAME_DECLTYPE 1
8919 #define COLNAME_DATABASE 2
8920 #define COLNAME_TABLE 3
8921 #define COLNAME_COLUMN 4
8922 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8923 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
8924 #else
8925 # ifdef SQLITE_OMIT_DECLTYPE
8926 # define COLNAME_N 1 /* Store only the name */
8927 # else
8928 # define COLNAME_N 2 /* Store the name and decltype */
8929 # endif
8930 #endif
8933 ** The following macro converts a relative address in the p2 field
8934 ** of a VdbeOp structure into a negative number so that
8935 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
8936 ** the macro again restores the address.
8938 #define ADDR(X) (-1-(X))
8941 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8942 ** header file that defines a number for each opcode used by the VDBE.
8944 /************** Include opcodes.h in the middle of vdbe.h ********************/
8945 /************** Begin file opcodes.h *****************************************/
8946 /* Automatically generated. Do not edit */
8947 /* See the mkopcodeh.awk script for details */
8948 #define OP_Function 1
8949 #define OP_Savepoint 2
8950 #define OP_AutoCommit 3
8951 #define OP_Transaction 4
8952 #define OP_SorterNext 5
8953 #define OP_Prev 6
8954 #define OP_Next 7
8955 #define OP_AggStep 8
8956 #define OP_Checkpoint 9
8957 #define OP_JournalMode 10
8958 #define OP_Vacuum 11
8959 #define OP_VFilter 12
8960 #define OP_VUpdate 13
8961 #define OP_Goto 14
8962 #define OP_Gosub 15
8963 #define OP_Return 16
8964 #define OP_Yield 17
8965 #define OP_HaltIfNull 18
8966 #define OP_Not 19 /* same as TK_NOT */
8967 #define OP_Halt 20
8968 #define OP_Integer 21
8969 #define OP_Int64 22
8970 #define OP_String 23
8971 #define OP_Null 24
8972 #define OP_Blob 25
8973 #define OP_Variable 26
8974 #define OP_Move 27
8975 #define OP_Copy 28
8976 #define OP_SCopy 29
8977 #define OP_ResultRow 30
8978 #define OP_CollSeq 31
8979 #define OP_AddImm 32
8980 #define OP_MustBeInt 33
8981 #define OP_RealAffinity 34
8982 #define OP_Permutation 35
8983 #define OP_Compare 36
8984 #define OP_Jump 37
8985 #define OP_Once 38
8986 #define OP_If 39
8987 #define OP_IfNot 40
8988 #define OP_Column 41
8989 #define OP_Affinity 42
8990 #define OP_MakeRecord 43
8991 #define OP_Count 44
8992 #define OP_ReadCookie 45
8993 #define OP_SetCookie 46
8994 #define OP_VerifyCookie 47
8995 #define OP_OpenRead 48
8996 #define OP_OpenWrite 49
8997 #define OP_OpenAutoindex 50
8998 #define OP_OpenEphemeral 51
8999 #define OP_SorterOpen 52
9000 #define OP_OpenPseudo 53
9001 #define OP_Close 54
9002 #define OP_SeekLt 55
9003 #define OP_SeekLe 56
9004 #define OP_SeekGe 57
9005 #define OP_SeekGt 58
9006 #define OP_Seek 59
9007 #define OP_NotFound 60
9008 #define OP_Found 61
9009 #define OP_IsUnique 62
9010 #define OP_NotExists 63
9011 #define OP_Sequence 64
9012 #define OP_NewRowid 65
9013 #define OP_Insert 66
9014 #define OP_InsertInt 67
9015 #define OP_Or 68 /* same as TK_OR */
9016 #define OP_And 69 /* same as TK_AND */
9017 #define OP_Delete 70
9018 #define OP_ResetCount 71
9019 #define OP_SorterCompare 72
9020 #define OP_IsNull 73 /* same as TK_ISNULL */
9021 #define OP_NotNull 74 /* same as TK_NOTNULL */
9022 #define OP_Ne 75 /* same as TK_NE */
9023 #define OP_Eq 76 /* same as TK_EQ */
9024 #define OP_Gt 77 /* same as TK_GT */
9025 #define OP_Le 78 /* same as TK_LE */
9026 #define OP_Lt 79 /* same as TK_LT */
9027 #define OP_Ge 80 /* same as TK_GE */
9028 #define OP_SorterData 81
9029 #define OP_BitAnd 82 /* same as TK_BITAND */
9030 #define OP_BitOr 83 /* same as TK_BITOR */
9031 #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
9032 #define OP_ShiftRight 85 /* same as TK_RSHIFT */
9033 #define OP_Add 86 /* same as TK_PLUS */
9034 #define OP_Subtract 87 /* same as TK_MINUS */
9035 #define OP_Multiply 88 /* same as TK_STAR */
9036 #define OP_Divide 89 /* same as TK_SLASH */
9037 #define OP_Remainder 90 /* same as TK_REM */
9038 #define OP_Concat 91 /* same as TK_CONCAT */
9039 #define OP_RowKey 92
9040 #define OP_BitNot 93 /* same as TK_BITNOT */
9041 #define OP_String8 94 /* same as TK_STRING */
9042 #define OP_RowData 95
9043 #define OP_Rowid 96
9044 #define OP_NullRow 97
9045 #define OP_Last 98
9046 #define OP_SorterSort 99
9047 #define OP_Sort 100
9048 #define OP_Rewind 101
9049 #define OP_SorterInsert 102
9050 #define OP_IdxInsert 103
9051 #define OP_IdxDelete 104
9052 #define OP_IdxRowid 105
9053 #define OP_IdxLT 106
9054 #define OP_IdxGE 107
9055 #define OP_Destroy 108
9056 #define OP_Clear 109
9057 #define OP_CreateIndex 110
9058 #define OP_CreateTable 111
9059 #define OP_ParseSchema 112
9060 #define OP_LoadAnalysis 113
9061 #define OP_DropTable 114
9062 #define OP_DropIndex 115
9063 #define OP_DropTrigger 116
9064 #define OP_IntegrityCk 117
9065 #define OP_RowSetAdd 118
9066 #define OP_RowSetRead 119
9067 #define OP_RowSetTest 120
9068 #define OP_Program 121
9069 #define OP_Param 122
9070 #define OP_FkCounter 123
9071 #define OP_FkIfZero 124
9072 #define OP_MemMax 125
9073 #define OP_IfPos 126
9074 #define OP_IfNeg 127
9075 #define OP_IfZero 128
9076 #define OP_AggFinal 129
9077 #define OP_Real 130 /* same as TK_FLOAT */
9078 #define OP_IncrVacuum 131
9079 #define OP_Expire 132
9080 #define OP_TableLock 133
9081 #define OP_VBegin 134
9082 #define OP_VCreate 135
9083 #define OP_VDestroy 136
9084 #define OP_VOpen 137
9085 #define OP_VColumn 138
9086 #define OP_VNext 139
9087 #define OP_VRename 140
9088 #define OP_ToText 141 /* same as TK_TO_TEXT */
9089 #define OP_ToBlob 142 /* same as TK_TO_BLOB */
9090 #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
9091 #define OP_ToInt 144 /* same as TK_TO_INT */
9092 #define OP_ToReal 145 /* same as TK_TO_REAL */
9093 #define OP_Pagecount 146
9094 #define OP_MaxPgcnt 147
9095 #define OP_Trace 148
9096 #define OP_Noop 149
9097 #define OP_Explain 150
9100 /* Properties such as "out2" or "jump" that are specified in
9101 ** comments following the "case" for each opcode in the vdbe.c
9102 ** are encoded into bitvectors as follows:
9104 #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
9105 #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
9106 #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
9107 #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
9108 #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
9109 #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
9110 #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
9111 #define OPFLG_INITIALIZER {\
9112 /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
9113 /* 8 */ 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x01, 0x01,\
9114 /* 16 */ 0x04, 0x04, 0x10, 0x24, 0x00, 0x02, 0x02, 0x02,\
9115 /* 24 */ 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x00, 0x00,\
9116 /* 32 */ 0x04, 0x05, 0x04, 0x00, 0x00, 0x01, 0x01, 0x05,\
9117 /* 40 */ 0x05, 0x00, 0x00, 0x00, 0x02, 0x02, 0x10, 0x00,\
9118 /* 48 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,\
9119 /* 56 */ 0x11, 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11,\
9120 /* 64 */ 0x02, 0x02, 0x00, 0x00, 0x4c, 0x4c, 0x00, 0x00,\
9121 /* 72 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
9122 /* 80 */ 0x15, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
9123 /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x00, 0x24, 0x02, 0x00,\
9124 /* 96 */ 0x02, 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08,\
9125 /* 104 */ 0x00, 0x02, 0x01, 0x01, 0x02, 0x00, 0x02, 0x02,\
9126 /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x45,\
9127 /* 120 */ 0x15, 0x01, 0x02, 0x00, 0x01, 0x08, 0x05, 0x05,\
9128 /* 128 */ 0x05, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00,\
9129 /* 136 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x04, 0x04,\
9130 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
9132 /************** End of opcodes.h *********************************************/
9133 /************** Continuing where we left off in vdbe.h ***********************/
9136 ** Prototypes for the VDBE interface. See comments on the implementation
9137 ** for a description of what each of these routines does.
9139 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
9140 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
9141 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
9142 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
9143 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
9144 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
9145 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
9146 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
9147 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9148 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9149 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9150 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9151 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9152 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9153 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9154 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9155 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9156 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9157 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9158 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9159 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9160 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9161 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9162 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9163 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9164 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9165 #ifdef SQLITE_DEBUG
9166 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9167 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
9168 #endif
9169 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9170 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9171 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9172 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9173 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9174 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9175 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9176 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9177 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9178 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9179 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
9180 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9181 #ifndef SQLITE_OMIT_TRACE
9182 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9183 #endif
9185 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9186 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9187 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9189 #ifndef SQLITE_OMIT_TRIGGER
9190 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9191 #endif
9194 #ifndef NDEBUG
9195 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
9196 # define VdbeComment(X) sqlite3VdbeComment X
9197 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9198 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
9199 #else
9200 # define VdbeComment(X)
9201 # define VdbeNoopComment(X)
9202 #endif
9204 #endif
9206 /************** End of vdbe.h ************************************************/
9207 /************** Continuing where we left off in sqliteInt.h ******************/
9208 /************** Include pager.h in the middle of sqliteInt.h *****************/
9209 /************** Begin file pager.h *******************************************/
9211 ** 2001 September 15
9213 ** The author disclaims copyright to this source code. In place of
9214 ** a legal notice, here is a blessing:
9216 ** May you do good and not evil.
9217 ** May you find forgiveness for yourself and forgive others.
9218 ** May you share freely, never taking more than you give.
9220 *************************************************************************
9221 ** This header file defines the interface that the sqlite page cache
9222 ** subsystem. The page cache subsystem reads and writes a file a page
9223 ** at a time and provides a journal for rollback.
9226 #ifndef _PAGER_H_
9227 #define _PAGER_H_
9230 ** Default maximum size for persistent journal files. A negative
9231 ** value means no limit. This value may be overridden using the
9232 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9234 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9235 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9236 #endif
9239 ** The type used to represent a page number. The first page in a file
9240 ** is called page 1. 0 is used to represent "not a page".
9242 typedef u32 Pgno;
9245 ** Each open file is managed by a separate instance of the "Pager" structure.
9247 typedef struct Pager Pager;
9250 ** Handle type for pages.
9252 typedef struct PgHdr DbPage;
9255 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9256 ** reserved for working around a windows/posix incompatibility). It is
9257 ** used in the journal to signify that the remainder of the journal file
9258 ** is devoted to storing a master journal name - there are no more pages to
9259 ** roll back. See comments for function writeMasterJournal() in pager.c
9260 ** for details.
9262 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9265 ** Allowed values for the flags parameter to sqlite3PagerOpen().
9267 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9269 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
9270 #define PAGER_MEMORY 0x0002 /* In-memory database */
9273 ** Valid values for the second argument to sqlite3PagerLockingMode().
9275 #define PAGER_LOCKINGMODE_QUERY -1
9276 #define PAGER_LOCKINGMODE_NORMAL 0
9277 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
9280 ** Numeric constants that encode the journalmode.
9282 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
9283 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
9284 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
9285 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
9286 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
9287 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
9288 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
9291 ** Flags that make up the mask passed to sqlite3PagerAcquire().
9293 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
9294 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
9297 ** Flags for sqlite3PagerSetFlags()
9299 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
9300 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
9301 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
9302 #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
9303 #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
9304 #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
9305 #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
9306 #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
9309 ** The remainder of this file contains the declarations of the functions
9310 ** that make up the Pager sub-system API. See source code comments for
9311 ** a detailed description of each routine.
9314 /* Open and close a Pager connection. */
9315 SQLITE_PRIVATE int sqlite3PagerOpen(
9316 sqlite3_vfs*,
9317 Pager **ppPager,
9318 const char*,
9319 int,
9320 int,
9321 int,
9322 void(*)(DbPage*)
9324 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9325 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9327 /* Functions used to configure a Pager object. */
9328 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9329 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9330 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9331 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9332 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
9333 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9334 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
9335 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9336 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9337 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9338 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9339 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9340 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9342 /* Functions used to obtain and release page references. */
9343 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9344 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9345 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9346 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9347 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9349 /* Operations on page references. */
9350 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9351 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9352 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9353 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9354 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
9355 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
9357 /* Functions used to manage pager transactions and savepoints. */
9358 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9359 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9360 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9361 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9362 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
9363 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9364 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9365 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9366 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9367 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9369 #ifndef SQLITE_OMIT_WAL
9370 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9371 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
9372 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
9373 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9374 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
9375 #endif
9377 #ifdef SQLITE_ENABLE_ZIPVFS
9378 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
9379 #endif
9381 /* Functions used to query pager state and configuration. */
9382 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9383 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9384 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9385 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9386 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9387 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9388 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9389 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9390 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9391 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9392 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9393 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9394 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9396 /* Functions used to truncate the database file. */
9397 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9399 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9400 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9401 #endif
9403 /* Functions to support testing and debugging. */
9404 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9405 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
9406 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
9407 #endif
9408 #ifdef SQLITE_TEST
9409 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
9410 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
9411 void disable_simulated_io_errors(void);
9412 void enable_simulated_io_errors(void);
9413 #else
9414 # define disable_simulated_io_errors()
9415 # define enable_simulated_io_errors()
9416 #endif
9418 #endif /* _PAGER_H_ */
9420 /************** End of pager.h ***********************************************/
9421 /************** Continuing where we left off in sqliteInt.h ******************/
9422 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9423 /************** Begin file pcache.h ******************************************/
9425 ** 2008 August 05
9427 ** The author disclaims copyright to this source code. In place of
9428 ** a legal notice, here is a blessing:
9430 ** May you do good and not evil.
9431 ** May you find forgiveness for yourself and forgive others.
9432 ** May you share freely, never taking more than you give.
9434 *************************************************************************
9435 ** This header file defines the interface that the sqlite page cache
9436 ** subsystem.
9439 #ifndef _PCACHE_H_
9441 typedef struct PgHdr PgHdr;
9442 typedef struct PCache PCache;
9445 ** Every page in the cache is controlled by an instance of the following
9446 ** structure.
9448 struct PgHdr {
9449 sqlite3_pcache_page *pPage; /* Pcache object page handle */
9450 void *pData; /* Page data */
9451 void *pExtra; /* Extra content */
9452 PgHdr *pDirty; /* Transient list of dirty pages */
9453 Pager *pPager; /* The pager this page is part of */
9454 Pgno pgno; /* Page number for this page */
9455 #ifdef SQLITE_CHECK_PAGES
9456 u32 pageHash; /* Hash of page content */
9457 #endif
9458 u16 flags; /* PGHDR flags defined below */
9460 /**********************************************************************
9461 ** Elements above are public. All that follows is private to pcache.c
9462 ** and should not be accessed by other modules.
9464 i16 nRef; /* Number of users of this page */
9465 PCache *pCache; /* Cache that owns this page */
9467 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
9468 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
9471 /* Bit values for PgHdr.flags */
9472 #define PGHDR_DIRTY 0x002 /* Page has changed */
9473 #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
9474 ** writing this page to the database */
9475 #define PGHDR_NEED_READ 0x008 /* Content is unread */
9476 #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
9477 #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
9479 #define PGHDR_MMAP 0x040 /* This is an mmap page object */
9481 /* Initialize and shutdown the page cache subsystem */
9482 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9483 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9485 /* Page cache buffer management:
9486 ** These routines implement SQLITE_CONFIG_PAGECACHE.
9488 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9490 /* Create a new pager cache.
9491 ** Under memory stress, invoke xStress to try to make pages clean.
9492 ** Only clean and unpinned pages can be reclaimed.
9494 SQLITE_PRIVATE void sqlite3PcacheOpen(
9495 int szPage, /* Size of every page */
9496 int szExtra, /* Extra space associated with each page */
9497 int bPurgeable, /* True if pages are on backing store */
9498 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9499 void *pStress, /* Argument to xStress */
9500 PCache *pToInit /* Preallocated space for the PCache */
9503 /* Modify the page-size after the cache has been created. */
9504 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9506 /* Return the size in bytes of a PCache object. Used to preallocate
9507 ** storage space.
9509 SQLITE_PRIVATE int sqlite3PcacheSize(void);
9511 /* One release per successful fetch. Page is pinned until released.
9512 ** Reference counted.
9514 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9515 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9517 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
9518 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
9519 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
9520 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
9522 /* Change a page number. Used by incr-vacuum. */
9523 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9525 /* Remove all pages with pgno>x. Reset the cache if x==0 */
9526 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9528 /* Get a list of all dirty pages in the cache, sorted by page number */
9529 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9531 /* Reset and close the cache object */
9532 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9534 /* Clear flags from pages of the page cache */
9535 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9537 /* Discard the contents of the cache */
9538 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9540 /* Return the total number of outstanding page references */
9541 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9543 /* Increment the reference count of an existing page */
9544 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9546 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9548 /* Return the total number of pages stored in the cache */
9549 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9551 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9552 /* Iterate through all dirty pages currently stored in the cache. This
9553 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
9554 ** library is built.
9556 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9557 #endif
9559 /* Set and get the suggested cache-size for the specified pager-cache.
9561 ** If no global maximum is configured, then the system attempts to limit
9562 ** the total number of pages cached by purgeable pager-caches to the sum
9563 ** of the suggested cache-sizes.
9565 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9566 #ifdef SQLITE_TEST
9567 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9568 #endif
9570 /* Free up as much memory as possible from the page cache */
9571 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9573 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9574 /* Try to return memory used by the pcache module to the main memory heap */
9575 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9576 #endif
9578 #ifdef SQLITE_TEST
9579 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9580 #endif
9582 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9584 #endif /* _PCACHE_H_ */
9586 /************** End of pcache.h **********************************************/
9587 /************** Continuing where we left off in sqliteInt.h ******************/
9589 /************** Include os.h in the middle of sqliteInt.h ********************/
9590 /************** Begin file os.h **********************************************/
9592 ** 2001 September 16
9594 ** The author disclaims copyright to this source code. In place of
9595 ** a legal notice, here is a blessing:
9597 ** May you do good and not evil.
9598 ** May you find forgiveness for yourself and forgive others.
9599 ** May you share freely, never taking more than you give.
9601 ******************************************************************************
9603 ** This header file (together with is companion C source-code file
9604 ** "os.c") attempt to abstract the underlying operating system so that
9605 ** the SQLite library will work on both POSIX and windows systems.
9607 ** This header file is #include-ed by sqliteInt.h and thus ends up
9608 ** being included by every source file.
9610 #ifndef _SQLITE_OS_H_
9611 #define _SQLITE_OS_H_
9614 ** Figure out if we are dealing with Unix, Windows, or some other
9615 ** operating system. After the following block of preprocess macros,
9616 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
9617 ** will defined to either 1 or 0. One of the four will be 1. The other
9618 ** three will be 0.
9620 #if defined(SQLITE_OS_OTHER)
9621 # if SQLITE_OS_OTHER==1
9622 # undef SQLITE_OS_UNIX
9623 # define SQLITE_OS_UNIX 0
9624 # undef SQLITE_OS_WIN
9625 # define SQLITE_OS_WIN 0
9626 # else
9627 # undef SQLITE_OS_OTHER
9628 # endif
9629 #endif
9630 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9631 # define SQLITE_OS_OTHER 0
9632 # ifndef SQLITE_OS_WIN
9633 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9634 # define SQLITE_OS_WIN 1
9635 # define SQLITE_OS_UNIX 0
9636 # else
9637 # define SQLITE_OS_WIN 0
9638 # define SQLITE_OS_UNIX 1
9639 # endif
9640 # else
9641 # define SQLITE_OS_UNIX 0
9642 # endif
9643 #else
9644 # ifndef SQLITE_OS_WIN
9645 # define SQLITE_OS_WIN 0
9646 # endif
9647 #endif
9649 #if SQLITE_OS_WIN
9650 # include <windows.h>
9651 #endif
9654 ** Determine if we are dealing with Windows NT.
9656 ** We ought to be able to determine if we are compiling for win98 or winNT
9657 ** using the _WIN32_WINNT macro as follows:
9659 ** #if defined(_WIN32_WINNT)
9660 ** # define SQLITE_OS_WINNT 1
9661 ** #else
9662 ** # define SQLITE_OS_WINNT 0
9663 ** #endif
9665 ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9666 ** so the above test does not work. We'll just assume that everything is
9667 ** winNT unless the programmer explicitly says otherwise by setting
9668 ** SQLITE_OS_WINNT to 0.
9670 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9671 # define SQLITE_OS_WINNT 1
9672 #endif
9675 ** Determine if we are dealing with WindowsCE - which has a much
9676 ** reduced API.
9678 #if defined(_WIN32_WCE)
9679 # define SQLITE_OS_WINCE 1
9680 #else
9681 # define SQLITE_OS_WINCE 0
9682 #endif
9685 ** Determine if we are dealing with WinRT, which provides only a subset of
9686 ** the full Win32 API.
9688 #if !defined(SQLITE_OS_WINRT)
9689 # define SQLITE_OS_WINRT 0
9690 #endif
9692 /* If the SET_FULLSYNC macro is not defined above, then make it
9693 ** a no-op
9695 #ifndef SET_FULLSYNC
9696 # define SET_FULLSYNC(x,y)
9697 #endif
9700 ** The default size of a disk sector
9702 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9703 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
9704 #endif
9707 ** Temporary files are named starting with this prefix followed by 16 random
9708 ** alphanumeric characters, and no file extension. They are stored in the
9709 ** OS's standard temporary file directory, and are deleted prior to exit.
9710 ** If sqlite is being embedded in another program, you may wish to change the
9711 ** prefix to reflect your program's name, so that if your program exits
9712 ** prematurely, old temporary files can be easily identified. This can be done
9713 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9715 ** 2006-10-31: The default prefix used to be "sqlite_". But then
9716 ** Mcafee started using SQLite in their anti-virus product and it
9717 ** started putting files with the "sqlite" name in the c:/temp folder.
9718 ** This annoyed many windows users. Those users would then do a
9719 ** Google search for "sqlite", find the telephone numbers of the
9720 ** developers and call to wake them up at night and complain.
9721 ** For this reason, the default name prefix is changed to be "sqlite"
9722 ** spelled backwards. So the temp files are still identified, but
9723 ** anybody smart enough to figure out the code is also likely smart
9724 ** enough to know that calling the developer will not help get rid
9725 ** of the file.
9727 #ifndef SQLITE_TEMP_FILE_PREFIX
9728 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9729 #endif
9732 ** The following values may be passed as the second argument to
9733 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9735 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
9736 ** RESERVED: A single process may hold a RESERVED lock on a file at
9737 ** any time. Other processes may hold and obtain new SHARED locks.
9738 ** PENDING: A single process may hold a PENDING lock on a file at
9739 ** any one time. Existing SHARED locks may persist, but no new
9740 ** SHARED locks may be obtained by other processes.
9741 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9743 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9744 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9745 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9746 ** sqlite3OsLock().
9748 #define NO_LOCK 0
9749 #define SHARED_LOCK 1
9750 #define RESERVED_LOCK 2
9751 #define PENDING_LOCK 3
9752 #define EXCLUSIVE_LOCK 4
9755 ** File Locking Notes: (Mostly about windows but also some info for Unix)
9757 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9758 ** those functions are not available. So we use only LockFile() and
9759 ** UnlockFile().
9761 ** LockFile() prevents not just writing but also reading by other processes.
9762 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
9763 ** byte out of a specific range of bytes. The lock byte is obtained at
9764 ** random so two separate readers can probably access the file at the
9765 ** same time, unless they are unlucky and choose the same lock byte.
9766 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9767 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
9768 ** a single byte of the file that is designated as the reserved lock byte.
9769 ** A PENDING_LOCK is obtained by locking a designated byte different from
9770 ** the RESERVED_LOCK byte.
9772 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9773 ** which means we can use reader/writer locks. When reader/writer locks
9774 ** are used, the lock is placed on the same range of bytes that is used
9775 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
9776 ** will support two or more Win95 readers or two or more WinNT readers.
9777 ** But a single Win95 reader will lock out all WinNT readers and a single
9778 ** WinNT reader will lock out all other Win95 readers.
9780 ** The following #defines specify the range of bytes used for locking.
9781 ** SHARED_SIZE is the number of bytes available in the pool from which
9782 ** a random byte is selected for a shared lock. The pool of bytes for
9783 ** shared locks begins at SHARED_FIRST.
9785 ** The same locking strategy and
9786 ** byte ranges are used for Unix. This leaves open the possiblity of having
9787 ** clients on win95, winNT, and unix all talking to the same shared file
9788 ** and all locking correctly. To do so would require that samba (or whatever
9789 ** tool is being used for file sharing) implements locks correctly between
9790 ** windows and unix. I'm guessing that isn't likely to happen, but by
9791 ** using the same locking range we are at least open to the possibility.
9793 ** Locking in windows is manditory. For this reason, we cannot store
9794 ** actual data in the bytes used for locking. The pager never allocates
9795 ** the pages involved in locking therefore. SHARED_SIZE is selected so
9796 ** that all locks will fit on a single page even at the minimum page size.
9797 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
9798 ** is set high so that we don't have to allocate an unused page except
9799 ** for very large databases. But one should test the page skipping logic
9800 ** by setting PENDING_BYTE low and running the entire regression suite.
9802 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9803 ** file format. Depending on how it is changed, you might not notice
9804 ** the incompatibility right away, even running a full regression test.
9805 ** The default location of PENDING_BYTE is the first byte past the
9806 ** 1GB boundary.
9809 #ifdef SQLITE_OMIT_WSD
9810 # define PENDING_BYTE (0x40000000)
9811 #else
9812 # define PENDING_BYTE sqlite3PendingByte
9813 #endif
9814 #define RESERVED_BYTE (PENDING_BYTE+1)
9815 #define SHARED_FIRST (PENDING_BYTE+2)
9816 #define SHARED_SIZE 510
9819 ** Wrapper around OS specific sqlite3_os_init() function.
9821 SQLITE_PRIVATE int sqlite3OsInit(void);
9824 ** Functions for accessing sqlite3_file methods
9826 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9827 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9828 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9829 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9830 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9831 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9832 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9833 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9834 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9835 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9836 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
9837 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9838 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9839 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9840 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9841 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9842 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9843 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9844 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
9845 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
9849 ** Functions for accessing sqlite3_vfs methods
9851 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9852 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9853 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9854 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9855 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9856 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9857 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9858 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9859 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9860 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9861 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9862 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9863 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9866 ** Convenience functions for opening and closing files using
9867 ** sqlite3_malloc() to obtain space for the file-handle structure.
9869 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9870 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9872 #endif /* _SQLITE_OS_H_ */
9874 /************** End of os.h **************************************************/
9875 /************** Continuing where we left off in sqliteInt.h ******************/
9876 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9877 /************** Begin file mutex.h *******************************************/
9879 ** 2007 August 28
9881 ** The author disclaims copyright to this source code. In place of
9882 ** a legal notice, here is a blessing:
9884 ** May you do good and not evil.
9885 ** May you find forgiveness for yourself and forgive others.
9886 ** May you share freely, never taking more than you give.
9888 *************************************************************************
9890 ** This file contains the common header for all mutex implementations.
9891 ** The sqliteInt.h header #includes this file so that it is available
9892 ** to all source files. We break it out in an effort to keep the code
9893 ** better organized.
9895 ** NOTE: source files should *not* #include this header file directly.
9896 ** Source files should #include the sqliteInt.h file and let that file
9897 ** include this one indirectly.
9902 ** Figure out what version of the code to use. The choices are
9904 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
9905 ** mutexes implemention cannot be overridden
9906 ** at start-time.
9908 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
9909 ** mutual exclusion is provided. But this
9910 ** implementation can be overridden at
9911 ** start-time.
9913 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
9915 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
9917 #if !SQLITE_THREADSAFE
9918 # define SQLITE_MUTEX_OMIT
9919 #endif
9920 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9921 # if SQLITE_OS_UNIX
9922 # define SQLITE_MUTEX_PTHREADS
9923 # elif SQLITE_OS_WIN
9924 # define SQLITE_MUTEX_W32
9925 # else
9926 # define SQLITE_MUTEX_NOOP
9927 # endif
9928 #endif
9930 #ifdef SQLITE_MUTEX_OMIT
9932 ** If this is a no-op implementation, implement everything as macros.
9934 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
9935 #define sqlite3_mutex_free(X)
9936 #define sqlite3_mutex_enter(X)
9937 #define sqlite3_mutex_try(X) SQLITE_OK
9938 #define sqlite3_mutex_leave(X)
9939 #define sqlite3_mutex_held(X) ((void)(X),1)
9940 #define sqlite3_mutex_notheld(X) ((void)(X),1)
9941 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
9942 #define sqlite3MutexInit() SQLITE_OK
9943 #define sqlite3MutexEnd()
9944 #define MUTEX_LOGIC(X)
9945 #else
9946 #define MUTEX_LOGIC(X) X
9947 #endif /* defined(SQLITE_MUTEX_OMIT) */
9949 /************** End of mutex.h ***********************************************/
9950 /************** Continuing where we left off in sqliteInt.h ******************/
9954 ** Each database file to be accessed by the system is an instance
9955 ** of the following structure. There are normally two of these structures
9956 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
9957 ** aDb[1] is the database file used to hold temporary tables. Additional
9958 ** databases may be attached.
9960 struct Db {
9961 char *zName; /* Name of this database */
9962 Btree *pBt; /* The B*Tree structure for this database file */
9963 u8 safety_level; /* How aggressive at syncing data to disk */
9964 Schema *pSchema; /* Pointer to database schema (possibly shared) */
9968 ** An instance of the following structure stores a database schema.
9970 ** Most Schema objects are associated with a Btree. The exception is
9971 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9972 ** In shared cache mode, a single Schema object can be shared by multiple
9973 ** Btrees that refer to the same underlying BtShared object.
9975 ** Schema objects are automatically deallocated when the last Btree that
9976 ** references them is destroyed. The TEMP Schema is manually freed by
9977 ** sqlite3_close().
9979 ** A thread must be holding a mutex on the corresponding Btree in order
9980 ** to access Schema content. This implies that the thread must also be
9981 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9982 ** For a TEMP Schema, only the connection mutex is required.
9984 struct Schema {
9985 int schema_cookie; /* Database schema version number for this file */
9986 int iGeneration; /* Generation counter. Incremented with each change */
9987 Hash tblHash; /* All tables indexed by name */
9988 Hash idxHash; /* All (named) indices indexed by name */
9989 Hash trigHash; /* All triggers indexed by name */
9990 Hash fkeyHash; /* All foreign keys by referenced table name */
9991 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
9992 u8 file_format; /* Schema format version for this file */
9993 u8 enc; /* Text encoding used by this database */
9994 u16 flags; /* Flags associated with this schema */
9995 int cache_size; /* Number of pages to use in the cache */
9999 ** These macros can be used to test, set, or clear bits in the
10000 ** Db.pSchema->flags field.
10002 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
10003 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
10004 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
10005 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
10008 ** Allowed values for the DB.pSchema->flags field.
10010 ** The DB_SchemaLoaded flag is set after the database schema has been
10011 ** read into internal hash tables.
10013 ** DB_UnresetViews means that one or more views have column names that
10014 ** have been filled out. If the schema changes, these column names might
10015 ** changes and so the view will need to be reset.
10017 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
10018 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
10019 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
10022 ** The number of different kinds of things that can be limited
10023 ** using the sqlite3_limit() interface.
10025 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
10028 ** Lookaside malloc is a set of fixed-size buffers that can be used
10029 ** to satisfy small transient memory allocation requests for objects
10030 ** associated with a particular database connection. The use of
10031 ** lookaside malloc provides a significant performance enhancement
10032 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
10033 ** SQL statements.
10035 ** The Lookaside structure holds configuration information about the
10036 ** lookaside malloc subsystem. Each available memory allocation in
10037 ** the lookaside subsystem is stored on a linked list of LookasideSlot
10038 ** objects.
10040 ** Lookaside allocations are only allowed for objects that are associated
10041 ** with a particular database connection. Hence, schema information cannot
10042 ** be stored in lookaside because in shared cache mode the schema information
10043 ** is shared by multiple database connections. Therefore, while parsing
10044 ** schema information, the Lookaside.bEnabled flag is cleared so that
10045 ** lookaside allocations are not used to construct the schema objects.
10047 struct Lookaside {
10048 u16 sz; /* Size of each buffer in bytes */
10049 u8 bEnabled; /* False to disable new lookaside allocations */
10050 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
10051 int nOut; /* Number of buffers currently checked out */
10052 int mxOut; /* Highwater mark for nOut */
10053 int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
10054 LookasideSlot *pFree; /* List of available buffers */
10055 void *pStart; /* First byte of available memory space */
10056 void *pEnd; /* First byte past end of available space */
10058 struct LookasideSlot {
10059 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
10063 ** A hash table for function definitions.
10065 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10066 ** Collisions are on the FuncDef.pHash chain.
10068 struct FuncDefHash {
10069 FuncDef *a[23]; /* Hash table for functions */
10073 ** Each database connection is an instance of the following structure.
10075 struct sqlite3 {
10076 sqlite3_vfs *pVfs; /* OS Interface */
10077 struct Vdbe *pVdbe; /* List of active virtual machines */
10078 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
10079 sqlite3_mutex *mutex; /* Connection mutex */
10080 Db *aDb; /* All backends */
10081 int nDb; /* Number of backends currently in use */
10082 int flags; /* Miscellaneous flags. See below */
10083 i64 lastRowid; /* ROWID of most recent insert (see above) */
10084 i64 szMmap; /* Default mmap_size setting */
10085 unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
10086 int errCode; /* Most recent error code (SQLITE_*) */
10087 int errMask; /* & result codes with this before returning */
10088 u16 dbOptFlags; /* Flags to enable/disable optimizations */
10089 u8 autoCommit; /* The auto-commit flag. */
10090 u8 temp_store; /* 1: file 2: memory 0: default */
10091 u8 mallocFailed; /* True if we have seen a malloc failure */
10092 u8 dfltLockMode; /* Default locking-mode for attached dbs */
10093 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
10094 u8 suppressErr; /* Do not issue error messages if true */
10095 u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
10096 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
10097 int nextPagesize; /* Pagesize after VACUUM if >0 */
10098 u32 magic; /* Magic number for detect library misuse */
10099 int nChange; /* Value returned by sqlite3_changes() */
10100 int nTotalChange; /* Value returned by sqlite3_total_changes() */
10101 int aLimit[SQLITE_N_LIMIT]; /* Limits */
10102 struct sqlite3InitInfo { /* Information used during initialization */
10103 int newTnum; /* Rootpage of table being initialized */
10104 u8 iDb; /* Which db file is being initialized */
10105 u8 busy; /* TRUE if currently initializing */
10106 u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
10107 } init;
10108 int nVdbeActive; /* Number of VDBEs currently running */
10109 int nVdbeRead; /* Number of active VDBEs that read or write */
10110 int nVdbeWrite; /* Number of active VDBEs that read and write */
10111 int nVdbeExec; /* Number of nested calls to VdbeExec() */
10112 int nExtension; /* Number of loaded extensions */
10113 void **aExtension; /* Array of shared library handles */
10114 void (*xTrace)(void*,const char*); /* Trace function */
10115 void *pTraceArg; /* Argument to the trace function */
10116 void (*xProfile)(void*,const char*,u64); /* Profiling function */
10117 void *pProfileArg; /* Argument to profile function */
10118 void *pCommitArg; /* Argument to xCommitCallback() */
10119 int (*xCommitCallback)(void*); /* Invoked at every commit. */
10120 void *pRollbackArg; /* Argument to xRollbackCallback() */
10121 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
10122 void *pUpdateArg;
10123 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
10124 #ifndef SQLITE_OMIT_WAL
10125 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
10126 void *pWalArg;
10127 #endif
10128 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
10129 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
10130 void *pCollNeededArg;
10131 sqlite3_value *pErr; /* Most recent error message */
10132 char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
10133 char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
10134 union {
10135 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
10136 double notUsed1; /* Spacer */
10137 } u1;
10138 Lookaside lookaside; /* Lookaside malloc configuration */
10139 #ifndef SQLITE_OMIT_AUTHORIZATION
10140 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
10141 /* Access authorization function */
10142 void *pAuthArg; /* 1st argument to the access auth function */
10143 #endif
10144 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10145 int (*xProgress)(void *); /* The progress callback */
10146 void *pProgressArg; /* Argument to the progress callback */
10147 unsigned nProgressOps; /* Number of opcodes for progress callback */
10148 #endif
10149 #ifndef SQLITE_OMIT_VIRTUALTABLE
10150 int nVTrans; /* Allocated size of aVTrans */
10151 Hash aModule; /* populated by sqlite3_create_module() */
10152 VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
10153 VTable **aVTrans; /* Virtual tables with open transactions */
10154 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
10155 #endif
10156 FuncDefHash aFunc; /* Hash table of connection functions */
10157 Hash aCollSeq; /* All collating sequences */
10158 BusyHandler busyHandler; /* Busy callback */
10159 Db aDbStatic[2]; /* Static space for the 2 default backends */
10160 Savepoint *pSavepoint; /* List of active savepoints */
10161 int busyTimeout; /* Busy handler timeout, in msec */
10162 int nSavepoint; /* Number of non-transaction savepoints */
10163 int nStatement; /* Number of nested statement-transactions */
10164 i64 nDeferredCons; /* Net deferred constraints this transaction. */
10165 i64 nDeferredImmCons; /* Net deferred immediate constraints */
10166 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
10168 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10169 /* The following variables are all protected by the STATIC_MASTER
10170 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
10172 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10173 ** unlock so that it can proceed.
10175 ** When X.pBlockingConnection==Y, that means that something that X tried
10176 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10177 ** held by Y.
10179 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10180 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
10181 void *pUnlockArg; /* Argument to xUnlockNotify */
10182 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
10183 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
10184 #endif
10188 ** A macro to discover the encoding of a database.
10190 #define ENC(db) ((db)->aDb[0].pSchema->enc)
10193 ** Possible values for the sqlite3.flags.
10195 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
10196 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
10197 #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
10198 #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
10199 #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
10200 #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
10201 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
10202 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
10203 /* DELETE, or UPDATE and return */
10204 /* the count using a callback. */
10205 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
10206 /* result set is empty */
10207 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
10208 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
10209 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
10210 #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
10211 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
10212 #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
10213 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
10214 #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
10215 #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
10216 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
10217 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
10218 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
10219 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
10220 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
10221 #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
10222 #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
10223 #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
10227 ** Bits of the sqlite3.dbOptFlags field that are used by the
10228 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10229 ** selectively disable various optimizations.
10231 #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
10232 #define SQLITE_ColumnCache 0x0002 /* Column cache */
10233 #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
10234 #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
10235 #define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */
10236 #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
10237 #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
10238 #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
10239 #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
10240 #define SQLITE_Transitive 0x0200 /* Transitive constraints */
10241 #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
10242 #define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */
10243 #define SQLITE_AllOpts 0xffff /* All optimizations */
10246 ** Macros for testing whether or not optimizations are enabled or disabled.
10248 #ifndef SQLITE_OMIT_BUILTIN_TEST
10249 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
10250 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
10251 #else
10252 #define OptimizationDisabled(db, mask) 0
10253 #define OptimizationEnabled(db, mask) 1
10254 #endif
10257 ** Possible values for the sqlite.magic field.
10258 ** The numbers are obtained at random and have no special meaning, other
10259 ** than being distinct from one another.
10261 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
10262 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
10263 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
10264 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
10265 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
10266 #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
10269 ** Each SQL function is defined by an instance of the following
10270 ** structure. A pointer to this structure is stored in the sqlite.aFunc
10271 ** hash table. When multiple functions have the same name, the hash table
10272 ** points to a linked list of these structures.
10274 struct FuncDef {
10275 i16 nArg; /* Number of arguments. -1 means unlimited */
10276 u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
10277 u8 flags; /* Some combination of SQLITE_FUNC_* */
10278 void *pUserData; /* User data parameter */
10279 FuncDef *pNext; /* Next function with same name */
10280 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10281 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10282 void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
10283 char *zName; /* SQL name of the function. */
10284 FuncDef *pHash; /* Next with a different name but the same hash */
10285 FuncDestructor *pDestructor; /* Reference counted destructor function */
10289 ** This structure encapsulates a user-function destructor callback (as
10290 ** configured using create_function_v2()) and a reference counter. When
10291 ** create_function_v2() is called to create a function with a destructor,
10292 ** a single object of this type is allocated. FuncDestructor.nRef is set to
10293 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10294 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10295 ** member of each of the new FuncDef objects is set to point to the allocated
10296 ** FuncDestructor.
10298 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10299 ** count on this object is decremented. When it reaches 0, the destructor
10300 ** is invoked and the FuncDestructor structure freed.
10302 struct FuncDestructor {
10303 int nRef;
10304 void (*xDestroy)(void *);
10305 void *pUserData;
10309 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
10310 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
10311 ** are assert() statements in the code to verify this.
10313 #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
10314 #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
10315 #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
10316 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
10317 #define SQLITE_FUNC_COUNT 0x10 /* Built-in count(*) aggregate */
10318 #define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */
10319 #define SQLITE_FUNC_LENGTH 0x40 /* Built-in length() function */
10320 #define SQLITE_FUNC_TYPEOF 0x80 /* Built-in typeof() function */
10323 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10324 ** used to create the initializers for the FuncDef structures.
10326 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
10327 ** Used to create a scalar function definition of a function zName
10328 ** implemented by C function xFunc that accepts nArg arguments. The
10329 ** value passed as iArg is cast to a (void*) and made available
10330 ** as the user-data (sqlite3_user_data()) for the function. If
10331 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10333 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10334 ** Used to create an aggregate function definition implemented by
10335 ** the C functions xStep and xFinal. The first four parameters
10336 ** are interpreted in the same way as the first 4 parameters to
10337 ** FUNCTION().
10339 ** LIKEFUNC(zName, nArg, pArg, flags)
10340 ** Used to create a scalar function definition of a function zName
10341 ** that accepts nArg arguments and is implemented by a call to C
10342 ** function likeFunc. Argument pArg is cast to a (void *) and made
10343 ** available as the function user-data (sqlite3_user_data()). The
10344 ** FuncDef.flags variable is set to the value passed as the flags
10345 ** parameter.
10347 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10348 {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \
10349 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10350 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10351 {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10352 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10353 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10354 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
10355 pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10356 #define LIKEFUNC(zName, nArg, arg, flags) \
10357 {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10358 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10359 {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
10360 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10363 ** All current savepoints are stored in a linked list starting at
10364 ** sqlite3.pSavepoint. The first element in the list is the most recently
10365 ** opened savepoint. Savepoints are added to the list by the vdbe
10366 ** OP_Savepoint instruction.
10368 struct Savepoint {
10369 char *zName; /* Savepoint name (nul-terminated) */
10370 i64 nDeferredCons; /* Number of deferred fk violations */
10371 i64 nDeferredImmCons; /* Number of deferred imm fk. */
10372 Savepoint *pNext; /* Parent savepoint (if any) */
10376 ** The following are used as the second parameter to sqlite3Savepoint(),
10377 ** and as the P1 argument to the OP_Savepoint instruction.
10379 #define SAVEPOINT_BEGIN 0
10380 #define SAVEPOINT_RELEASE 1
10381 #define SAVEPOINT_ROLLBACK 2
10385 ** Each SQLite module (virtual table definition) is defined by an
10386 ** instance of the following structure, stored in the sqlite3.aModule
10387 ** hash table.
10389 struct Module {
10390 const sqlite3_module *pModule; /* Callback pointers */
10391 const char *zName; /* Name passed to create_module() */
10392 void *pAux; /* pAux passed to create_module() */
10393 void (*xDestroy)(void *); /* Module destructor function */
10397 ** information about each column of an SQL table is held in an instance
10398 ** of this structure.
10400 struct Column {
10401 char *zName; /* Name of this column */
10402 Expr *pDflt; /* Default value of this column */
10403 char *zDflt; /* Original text of the default value */
10404 char *zType; /* Data type for this column */
10405 char *zColl; /* Collating sequence. If NULL, use the default */
10406 u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
10407 char affinity; /* One of the SQLITE_AFF_... values */
10408 u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */
10411 /* Allowed values for Column.colFlags:
10413 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
10414 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
10417 ** A "Collating Sequence" is defined by an instance of the following
10418 ** structure. Conceptually, a collating sequence consists of a name and
10419 ** a comparison routine that defines the order of that sequence.
10421 ** If CollSeq.xCmp is NULL, it means that the
10422 ** collating sequence is undefined. Indices built on an undefined
10423 ** collating sequence may not be read or written.
10425 struct CollSeq {
10426 char *zName; /* Name of the collating sequence, UTF-8 encoded */
10427 u8 enc; /* Text encoding handled by xCmp() */
10428 void *pUser; /* First argument to xCmp() */
10429 int (*xCmp)(void*,int, const void*, int, const void*);
10430 void (*xDel)(void*); /* Destructor for pUser */
10434 ** A sort order can be either ASC or DESC.
10436 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
10437 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
10440 ** Column affinity types.
10442 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10443 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
10444 ** the speed a little by numbering the values consecutively.
10446 ** But rather than start with 0 or 1, we begin with 'a'. That way,
10447 ** when multiple affinity types are concatenated into a string and
10448 ** used as the P4 operand, they will be more readable.
10450 ** Note also that the numeric types are grouped together so that testing
10451 ** for a numeric type is a single comparison.
10453 #define SQLITE_AFF_TEXT 'a'
10454 #define SQLITE_AFF_NONE 'b'
10455 #define SQLITE_AFF_NUMERIC 'c'
10456 #define SQLITE_AFF_INTEGER 'd'
10457 #define SQLITE_AFF_REAL 'e'
10459 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
10462 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10463 ** affinity value.
10465 #define SQLITE_AFF_MASK 0x67
10468 ** Additional bit values that can be ORed with an affinity without
10469 ** changing the affinity.
10471 #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
10472 #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
10473 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
10476 ** An object of this type is created for each virtual table present in
10477 ** the database schema.
10479 ** If the database schema is shared, then there is one instance of this
10480 ** structure for each database connection (sqlite3*) that uses the shared
10481 ** schema. This is because each database connection requires its own unique
10482 ** instance of the sqlite3_vtab* handle used to access the virtual table
10483 ** implementation. sqlite3_vtab* handles can not be shared between
10484 ** database connections, even when the rest of the in-memory database
10485 ** schema is shared, as the implementation often stores the database
10486 ** connection handle passed to it via the xConnect() or xCreate() method
10487 ** during initialization internally. This database connection handle may
10488 ** then be used by the virtual table implementation to access real tables
10489 ** within the database. So that they appear as part of the callers
10490 ** transaction, these accesses need to be made via the same database
10491 ** connection as that used to execute SQL operations on the virtual table.
10493 ** All VTable objects that correspond to a single table in a shared
10494 ** database schema are initially stored in a linked-list pointed to by
10495 ** the Table.pVTable member variable of the corresponding Table object.
10496 ** When an sqlite3_prepare() operation is required to access the virtual
10497 ** table, it searches the list for the VTable that corresponds to the
10498 ** database connection doing the preparing so as to use the correct
10499 ** sqlite3_vtab* handle in the compiled query.
10501 ** When an in-memory Table object is deleted (for example when the
10502 ** schema is being reloaded for some reason), the VTable objects are not
10503 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
10504 ** immediately. Instead, they are moved from the Table.pVTable list to
10505 ** another linked list headed by the sqlite3.pDisconnect member of the
10506 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
10507 ** next time a statement is prepared using said sqlite3*. This is done
10508 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10509 ** Refer to comments above function sqlite3VtabUnlockList() for an
10510 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10511 ** list without holding the corresponding sqlite3.mutex mutex.
10513 ** The memory for objects of this type is always allocated by
10514 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
10515 ** the first argument.
10517 struct VTable {
10518 sqlite3 *db; /* Database connection associated with this table */
10519 Module *pMod; /* Pointer to module implementation */
10520 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
10521 int nRef; /* Number of pointers to this structure */
10522 u8 bConstraint; /* True if constraints are supported */
10523 int iSavepoint; /* Depth of the SAVEPOINT stack */
10524 VTable *pNext; /* Next in linked list (see above) */
10528 ** Each SQL table is represented in memory by an instance of the
10529 ** following structure.
10531 ** Table.zName is the name of the table. The case of the original
10532 ** CREATE TABLE statement is stored, but case is not significant for
10533 ** comparisons.
10535 ** Table.nCol is the number of columns in this table. Table.aCol is a
10536 ** pointer to an array of Column structures, one for each column.
10538 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10539 ** the column that is that key. Otherwise Table.iPKey is negative. Note
10540 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10541 ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
10542 ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
10543 ** is generated for each row of the table. TF_HasPrimaryKey is set if
10544 ** the table has any PRIMARY KEY, INTEGER or otherwise.
10546 ** Table.tnum is the page number for the root BTree page of the table in the
10547 ** database file. If Table.iDb is the index of the database table backend
10548 ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
10549 ** holds temporary tables and indices. If TF_Ephemeral is set
10550 ** then the table is stored in a file that is automatically deleted
10551 ** when the VDBE cursor to the table is closed. In this case Table.tnum
10552 ** refers VDBE cursor number that holds the table open, not to the root
10553 ** page number. Transient tables are used to hold the results of a
10554 ** sub-query that appears instead of a real table name in the FROM clause
10555 ** of a SELECT statement.
10557 struct Table {
10558 char *zName; /* Name of the table or view */
10559 Column *aCol; /* Information about each column */
10560 Index *pIndex; /* List of SQL indexes on this table. */
10561 Select *pSelect; /* NULL for tables. Points to definition if a view. */
10562 FKey *pFKey; /* Linked list of all foreign keys in this table */
10563 char *zColAff; /* String defining the affinity of each column */
10564 #ifndef SQLITE_OMIT_CHECK
10565 ExprList *pCheck; /* All CHECK constraints */
10566 #endif
10567 tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
10568 int tnum; /* Root BTree node for this table (see note above) */
10569 i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
10570 i16 nCol; /* Number of columns in this table */
10571 u16 nRef; /* Number of pointers to this Table */
10572 u8 tabFlags; /* Mask of TF_* values */
10573 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
10574 #ifndef SQLITE_OMIT_ALTERTABLE
10575 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
10576 #endif
10577 #ifndef SQLITE_OMIT_VIRTUALTABLE
10578 int nModuleArg; /* Number of arguments to the module */
10579 char **azModuleArg; /* Text of all module args. [0] is module name */
10580 VTable *pVTable; /* List of VTable objects. */
10581 #endif
10582 Trigger *pTrigger; /* List of triggers stored in pSchema */
10583 Schema *pSchema; /* Schema that contains this table */
10584 Table *pNextZombie; /* Next on the Parse.pZombieTab list */
10588 ** Allowed values for Tabe.tabFlags.
10590 #define TF_Readonly 0x01 /* Read-only system table */
10591 #define TF_Ephemeral 0x02 /* An ephemeral table */
10592 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
10593 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
10594 #define TF_Virtual 0x10 /* Is a virtual table */
10598 ** Test to see whether or not a table is a virtual table. This is
10599 ** done as a macro so that it will be optimized out when virtual
10600 ** table support is omitted from the build.
10602 #ifndef SQLITE_OMIT_VIRTUALTABLE
10603 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
10604 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
10605 #else
10606 # define IsVirtual(X) 0
10607 # define IsHiddenColumn(X) 0
10608 #endif
10611 ** Each foreign key constraint is an instance of the following structure.
10613 ** A foreign key is associated with two tables. The "from" table is
10614 ** the table that contains the REFERENCES clause that creates the foreign
10615 ** key. The "to" table is the table that is named in the REFERENCES clause.
10616 ** Consider this example:
10618 ** CREATE TABLE ex1(
10619 ** a INTEGER PRIMARY KEY,
10620 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10621 ** );
10623 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10625 ** Each REFERENCES clause generates an instance of the following structure
10626 ** which is attached to the from-table. The to-table need not exist when
10627 ** the from-table is created. The existence of the to-table is not checked.
10629 struct FKey {
10630 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
10631 FKey *pNextFrom; /* Next foreign key in pFrom */
10632 char *zTo; /* Name of table that the key points to (aka: Parent) */
10633 FKey *pNextTo; /* Next foreign key on table named zTo */
10634 FKey *pPrevTo; /* Previous foreign key on table named zTo */
10635 int nCol; /* Number of columns in this key */
10636 /* EV: R-30323-21917 */
10637 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
10638 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
10639 Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
10640 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
10641 int iFrom; /* Index of column in pFrom */
10642 char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
10643 } aCol[1]; /* One entry for each of nCol column s */
10647 ** SQLite supports many different ways to resolve a constraint
10648 ** error. ROLLBACK processing means that a constraint violation
10649 ** causes the operation in process to fail and for the current transaction
10650 ** to be rolled back. ABORT processing means the operation in process
10651 ** fails and any prior changes from that one operation are backed out,
10652 ** but the transaction is not rolled back. FAIL processing means that
10653 ** the operation in progress stops and returns an error code. But prior
10654 ** changes due to the same operation are not backed out and no rollback
10655 ** occurs. IGNORE means that the particular row that caused the constraint
10656 ** error is not inserted or updated. Processing continues and no error
10657 ** is returned. REPLACE means that preexisting database rows that caused
10658 ** a UNIQUE constraint violation are removed so that the new insert or
10659 ** update can proceed. Processing continues and no error is reported.
10661 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10662 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10663 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
10664 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
10665 ** referenced table row is propagated into the row that holds the
10666 ** foreign key.
10668 ** The following symbolic values are used to record which type
10669 ** of action to take.
10671 #define OE_None 0 /* There is no constraint to check */
10672 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
10673 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
10674 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
10675 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
10676 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
10678 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10679 #define OE_SetNull 7 /* Set the foreign key value to NULL */
10680 #define OE_SetDflt 8 /* Set the foreign key value to its default */
10681 #define OE_Cascade 9 /* Cascade the changes */
10683 #define OE_Default 99 /* Do whatever the default action is */
10687 ** An instance of the following structure is passed as the first
10688 ** argument to sqlite3VdbeKeyCompare and is used to control the
10689 ** comparison of the two index keys.
10691 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
10692 ** are nField slots for the columns of an index then one extra slot
10693 ** for the rowid at the end.
10695 struct KeyInfo {
10696 sqlite3 *db; /* The database connection */
10697 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
10698 u16 nField; /* Maximum index for aColl[] and aSortOrder[] */
10699 u8 *aSortOrder; /* Sort order for each column. */
10700 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
10704 ** An instance of the following structure holds information about a
10705 ** single index record that has already been parsed out into individual
10706 ** values.
10708 ** A record is an object that contains one or more fields of data.
10709 ** Records are used to store the content of a table row and to store
10710 ** the key of an index. A blob encoding of a record is created by
10711 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10712 ** OP_Column opcode.
10714 ** This structure holds a record that has already been disassembled
10715 ** into its constituent fields.
10717 struct UnpackedRecord {
10718 KeyInfo *pKeyInfo; /* Collation and sort-order information */
10719 u16 nField; /* Number of entries in apMem[] */
10720 u8 flags; /* Boolean settings. UNPACKED_... below */
10721 i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
10722 Mem *aMem; /* Values */
10726 ** Allowed values of UnpackedRecord.flags
10728 #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
10729 #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
10730 #define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */
10733 ** Each SQL index is represented in memory by an
10734 ** instance of the following structure.
10736 ** The columns of the table that are to be indexed are described
10737 ** by the aiColumn[] field of this structure. For example, suppose
10738 ** we have the following table and index:
10740 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10741 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
10743 ** In the Table structure describing Ex1, nCol==3 because there are
10744 ** three columns in the table. In the Index structure describing
10745 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10746 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
10747 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10748 ** The second column to be indexed (c1) has an index of 0 in
10749 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10751 ** The Index.onError field determines whether or not the indexed columns
10752 ** must be unique and what to do if they are not. When Index.onError=OE_None,
10753 ** it means this is not a unique index. Otherwise it is a unique index
10754 ** and the value of Index.onError indicate the which conflict resolution
10755 ** algorithm to employ whenever an attempt is made to insert a non-unique
10756 ** element.
10758 struct Index {
10759 char *zName; /* Name of this index */
10760 int *aiColumn; /* Which columns are used by this index. 1st is 0 */
10761 tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */
10762 Table *pTable; /* The SQL table being indexed */
10763 char *zColAff; /* String defining the affinity of each column */
10764 Index *pNext; /* The next index associated with the same table */
10765 Schema *pSchema; /* Schema containing this index */
10766 u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
10767 char **azColl; /* Array of collation sequence names for index */
10768 Expr *pPartIdxWhere; /* WHERE clause for partial indices */
10769 int tnum; /* DB Page containing root of this index */
10770 u16 nColumn; /* Number of columns in table used by this index */
10771 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10772 unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
10773 unsigned bUnordered:1; /* Use this index for == or IN queries only */
10774 unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
10775 #ifdef SQLITE_ENABLE_STAT3
10776 int nSample; /* Number of elements in aSample[] */
10777 tRowcnt avgEq; /* Average nEq value for key values not in aSample */
10778 IndexSample *aSample; /* Samples of the left-most key */
10779 #endif
10783 ** Each sample stored in the sqlite_stat3 table is represented in memory
10784 ** using a structure of this type. See documentation at the top of the
10785 ** analyze.c source file for additional information.
10787 struct IndexSample {
10788 union {
10789 char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10790 double r; /* Value if eType is SQLITE_FLOAT */
10791 i64 i; /* Value if eType is SQLITE_INTEGER */
10792 } u;
10793 u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10794 int nByte; /* Size in byte of text or blob. */
10795 tRowcnt nEq; /* Est. number of rows where the key equals this sample */
10796 tRowcnt nLt; /* Est. number of rows where key is less than this sample */
10797 tRowcnt nDLt; /* Est. number of distinct keys less than this sample */
10801 ** Each token coming out of the lexer is an instance of
10802 ** this structure. Tokens are also used as part of an expression.
10804 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10805 ** may contain random values. Do not make any assumptions about Token.dyn
10806 ** and Token.n when Token.z==0.
10808 struct Token {
10809 const char *z; /* Text of the token. Not NULL-terminated! */
10810 unsigned int n; /* Number of characters in this token */
10814 ** An instance of this structure contains information needed to generate
10815 ** code for a SELECT that contains aggregate functions.
10817 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10818 ** pointer to this structure. The Expr.iColumn field is the index in
10819 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10820 ** code for that node.
10822 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10823 ** original Select structure that describes the SELECT statement. These
10824 ** fields do not need to be freed when deallocating the AggInfo structure.
10826 struct AggInfo {
10827 u8 directMode; /* Direct rendering mode means take data directly
10828 ** from source tables rather than from accumulators */
10829 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
10830 ** than the source table */
10831 int sortingIdx; /* Cursor number of the sorting index */
10832 int sortingIdxPTab; /* Cursor number of pseudo-table */
10833 int nSortingColumn; /* Number of columns in the sorting index */
10834 ExprList *pGroupBy; /* The group by clause */
10835 struct AggInfo_col { /* For each column used in source tables */
10836 Table *pTab; /* Source table */
10837 int iTable; /* Cursor number of the source table */
10838 int iColumn; /* Column number within the source table */
10839 int iSorterColumn; /* Column number in the sorting index */
10840 int iMem; /* Memory location that acts as accumulator */
10841 Expr *pExpr; /* The original expression */
10842 } *aCol;
10843 int nColumn; /* Number of used entries in aCol[] */
10844 int nAccumulator; /* Number of columns that show through to the output.
10845 ** Additional columns are used only as parameters to
10846 ** aggregate functions */
10847 struct AggInfo_func { /* For each aggregate function */
10848 Expr *pExpr; /* Expression encoding the function */
10849 FuncDef *pFunc; /* The aggregate function implementation */
10850 int iMem; /* Memory location that acts as accumulator */
10851 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
10852 } *aFunc;
10853 int nFunc; /* Number of entries in aFunc[] */
10857 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10858 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
10859 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
10860 ** it uses less memory in the Expr object, which is a big memory user
10861 ** in systems with lots of prepared statements. And few applications
10862 ** need more than about 10 or 20 variables. But some extreme users want
10863 ** to have prepared statements with over 32767 variables, and for them
10864 ** the option is available (at compile-time).
10866 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10867 typedef i16 ynVar;
10868 #else
10869 typedef int ynVar;
10870 #endif
10873 ** Each node of an expression in the parse tree is an instance
10874 ** of this structure.
10876 ** Expr.op is the opcode. The integer parser token codes are reused
10877 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10878 ** code representing the ">=" operator. This same integer code is reused
10879 ** to represent the greater-than-or-equal-to operator in the expression
10880 ** tree.
10882 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
10883 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10884 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
10885 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10886 ** then Expr.token contains the name of the function.
10888 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10889 ** binary operator. Either or both may be NULL.
10891 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10892 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10893 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10894 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10895 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
10896 ** valid.
10898 ** An expression of the form ID or ID.ID refers to a column in a table.
10899 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10900 ** the integer cursor number of a VDBE cursor pointing to that table and
10901 ** Expr.iColumn is the column number for the specific column. If the
10902 ** expression is used as a result in an aggregate SELECT, then the
10903 ** value is also stored in the Expr.iAgg column in the aggregate so that
10904 ** it can be accessed after all aggregates are computed.
10906 ** If the expression is an unbound variable marker (a question mark
10907 ** character '?' in the original SQL) then the Expr.iTable holds the index
10908 ** number for that variable.
10910 ** If the expression is a subquery then Expr.iColumn holds an integer
10911 ** register number containing the result of the subquery. If the
10912 ** subquery gives a constant result, then iTable is -1. If the subquery
10913 ** gives a different answer at different times during statement processing
10914 ** then iTable is the address of a subroutine that computes the subquery.
10916 ** If the Expr is of type OP_Column, and the table it is selecting from
10917 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10918 ** corresponding table definition.
10920 ** ALLOCATION NOTES:
10922 ** Expr objects can use a lot of memory space in database schema. To
10923 ** help reduce memory requirements, sometimes an Expr object will be
10924 ** truncated. And to reduce the number of memory allocations, sometimes
10925 ** two or more Expr objects will be stored in a single memory allocation,
10926 ** together with Expr.zToken strings.
10928 ** If the EP_Reduced and EP_TokenOnly flags are set when
10929 ** an Expr object is truncated. When EP_Reduced is set, then all
10930 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10931 ** are contained within the same memory allocation. Note, however, that
10932 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10933 ** allocated, regardless of whether or not EP_Reduced is set.
10935 struct Expr {
10936 u8 op; /* Operation performed by this node */
10937 char affinity; /* The affinity of the column or 0 if not a column */
10938 u16 flags; /* Various flags. EP_* See below */
10939 union {
10940 char *zToken; /* Token value. Zero terminated and dequoted */
10941 int iValue; /* Non-negative integer value if EP_IntValue */
10942 } u;
10944 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10945 ** space is allocated for the fields below this point. An attempt to
10946 ** access them will result in a segfault or malfunction.
10947 *********************************************************************/
10949 Expr *pLeft; /* Left subnode */
10950 Expr *pRight; /* Right subnode */
10951 union {
10952 ExprList *pList; /* Function arguments or in "<expr> IN (<expr-list)" */
10953 Select *pSelect; /* Used for sub-selects and "<expr> IN (<select>)" */
10954 } x;
10956 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10957 ** space is allocated for the fields below this point. An attempt to
10958 ** access them will result in a segfault or malfunction.
10959 *********************************************************************/
10961 #if SQLITE_MAX_EXPR_DEPTH>0
10962 int nHeight; /* Height of the tree headed by this node */
10963 #endif
10964 int iTable; /* TK_COLUMN: cursor number of table holding column
10965 ** TK_REGISTER: register number
10966 ** TK_TRIGGER: 1 -> new, 0 -> old */
10967 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
10968 ** TK_VARIABLE: variable number (always >= 1). */
10969 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10970 i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
10971 u8 flags2; /* Second set of flags. EP2_... */
10972 u8 op2; /* TK_REGISTER: original value of Expr.op
10973 ** TK_COLUMN: the value of p5 for OP_Column
10974 ** TK_AGG_FUNCTION: nesting depth */
10975 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10976 Table *pTab; /* Table for TK_COLUMN expressions. */
10980 ** The following are the meanings of bits in the Expr.flags field.
10982 #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
10983 #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
10984 #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
10985 #define EP_Error 0x0008 /* Expression contains one or more errors */
10986 #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
10987 #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
10988 #define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
10989 #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
10990 #define EP_Collate 0x0100 /* Tree contains a TK_COLLATE opeartor */
10991 #define EP_FixedDest 0x0200 /* Result needed in a specific register */
10992 #define EP_IntValue 0x0400 /* Integer value contained in u.iValue */
10993 #define EP_xIsSelect 0x0800 /* x.pSelect is valid (otherwise x.pList is) */
10994 #define EP_Hint 0x1000 /* Not used */
10995 #define EP_Reduced 0x2000 /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10996 #define EP_TokenOnly 0x4000 /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10997 #define EP_Static 0x8000 /* Held in memory not obtained from malloc() */
11000 ** The following are the meanings of bits in the Expr.flags2 field.
11002 #define EP2_MallocedToken 0x0001 /* Need to sqlite3DbFree() Expr.zToken */
11003 #define EP2_Irreducible 0x0002 /* Cannot EXPRDUP_REDUCE this Expr */
11006 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
11007 ** flag on an expression structure. This flag is used for VV&A only. The
11008 ** routine is implemented as a macro that only works when in debugging mode,
11009 ** so as not to burden production code.
11011 #ifdef SQLITE_DEBUG
11012 # define ExprSetIrreducible(X) (X)->flags2 |= EP2_Irreducible
11013 #else
11014 # define ExprSetIrreducible(X)
11015 #endif
11018 ** These macros can be used to test, set, or clear bits in the
11019 ** Expr.flags field.
11021 #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
11022 #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
11023 #define ExprSetProperty(E,P) (E)->flags|=(P)
11024 #define ExprClearProperty(E,P) (E)->flags&=~(P)
11027 ** Macros to determine the number of bytes required by a normal Expr
11028 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
11029 ** and an Expr struct with the EP_TokenOnly flag set.
11031 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
11032 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
11033 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
11036 ** Flags passed to the sqlite3ExprDup() function. See the header comment
11037 ** above sqlite3ExprDup() for details.
11039 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
11042 ** A list of expressions. Each expression may optionally have a
11043 ** name. An expr/name combination can be used in several ways, such
11044 ** as the list of "expr AS ID" fields following a "SELECT" or in the
11045 ** list of "ID = expr" items in an UPDATE. A list of expressions can
11046 ** also be used as the argument to a function, in which case the a.zName
11047 ** field is not used.
11049 ** By default the Expr.zSpan field holds a human-readable description of
11050 ** the expression that is used in the generation of error messages and
11051 ** column labels. In this case, Expr.zSpan is typically the text of a
11052 ** column expression as it exists in a SELECT statement. However, if
11053 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
11054 ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
11055 ** form is used for name resolution with nested FROM clauses.
11057 struct ExprList {
11058 int nExpr; /* Number of expressions on the list */
11059 int iECursor; /* VDBE Cursor associated with this ExprList */
11060 struct ExprList_item { /* For each expression in the list */
11061 Expr *pExpr; /* The list of expressions */
11062 char *zName; /* Token associated with this expression */
11063 char *zSpan; /* Original text of the expression */
11064 u8 sortOrder; /* 1 for DESC or 0 for ASC */
11065 unsigned done :1; /* A flag to indicate when processing is finished */
11066 unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
11067 u16 iOrderByCol; /* For ORDER BY, column number in result set */
11068 u16 iAlias; /* Index into Parse.aAlias[] for zName */
11069 } *a; /* Alloc a power of two greater or equal to nExpr */
11073 ** An instance of this structure is used by the parser to record both
11074 ** the parse tree for an expression and the span of input text for an
11075 ** expression.
11077 struct ExprSpan {
11078 Expr *pExpr; /* The expression parse tree */
11079 const char *zStart; /* First character of input text */
11080 const char *zEnd; /* One character past the end of input text */
11084 ** An instance of this structure can hold a simple list of identifiers,
11085 ** such as the list "a,b,c" in the following statements:
11087 ** INSERT INTO t(a,b,c) VALUES ...;
11088 ** CREATE INDEX idx ON t(a,b,c);
11089 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
11091 ** The IdList.a.idx field is used when the IdList represents the list of
11092 ** column names after a table name in an INSERT statement. In the statement
11094 ** INSERT INTO t(a,b,c) ...
11096 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
11098 struct IdList {
11099 struct IdList_item {
11100 char *zName; /* Name of the identifier */
11101 int idx; /* Index in some Table.aCol[] of a column named zName */
11102 } *a;
11103 int nId; /* Number of identifiers on the list */
11107 ** The bitmask datatype defined below is used for various optimizations.
11109 ** Changing this from a 64-bit to a 32-bit type limits the number of
11110 ** tables in a join to 32 instead of 64. But it also reduces the size
11111 ** of the library by 738 bytes on ix86.
11113 typedef u64 Bitmask;
11116 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
11118 #define BMS ((int)(sizeof(Bitmask)*8))
11121 ** A bit in a Bitmask
11123 #define MASKBIT(n) (((Bitmask)1)<<(n))
11126 ** The following structure describes the FROM clause of a SELECT statement.
11127 ** Each table or subquery in the FROM clause is a separate element of
11128 ** the SrcList.a[] array.
11130 ** With the addition of multiple database support, the following structure
11131 ** can also be used to describe a particular table such as the table that
11132 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
11133 ** such a table must be a simple name: ID. But in SQLite, the table can
11134 ** now be identified by a database name, a dot, then the table name: ID.ID.
11136 ** The jointype starts out showing the join type between the current table
11137 ** and the next table on the list. The parser builds the list this way.
11138 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
11139 ** jointype expresses the join between the table and the previous table.
11141 ** In the colUsed field, the high-order bit (bit 63) is set if the table
11142 ** contains more than 63 columns and the 64-th or later column is used.
11144 struct SrcList {
11145 u8 nSrc; /* Number of tables or subqueries in the FROM clause */
11146 u8 nAlloc; /* Number of entries allocated in a[] below */
11147 struct SrcList_item {
11148 Schema *pSchema; /* Schema to which this item is fixed */
11149 char *zDatabase; /* Name of database holding this table */
11150 char *zName; /* Name of the table */
11151 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
11152 Table *pTab; /* An SQL table corresponding to zName */
11153 Select *pSelect; /* A SELECT statement used in place of a table name */
11154 int addrFillSub; /* Address of subroutine to manifest a subquery */
11155 int regReturn; /* Register holding return address of addrFillSub */
11156 u8 jointype; /* Type of join between this able and the previous */
11157 unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
11158 unsigned isCorrelated :1; /* True if sub-query is correlated */
11159 unsigned viaCoroutine :1; /* Implemented as a co-routine */
11160 #ifndef SQLITE_OMIT_EXPLAIN
11161 u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
11162 #endif
11163 int iCursor; /* The VDBE cursor number used to access this table */
11164 Expr *pOn; /* The ON clause of a join */
11165 IdList *pUsing; /* The USING clause of a join */
11166 Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
11167 char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
11168 Index *pIndex; /* Index structure corresponding to zIndex, if any */
11169 } a[1]; /* One entry for each identifier on the list */
11173 ** Permitted values of the SrcList.a.jointype field
11175 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
11176 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
11177 #define JT_NATURAL 0x0004 /* True for a "natural" join */
11178 #define JT_LEFT 0x0008 /* Left outer join */
11179 #define JT_RIGHT 0x0010 /* Right outer join */
11180 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
11181 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
11185 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11186 ** and the WhereInfo.wctrlFlags member.
11188 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
11189 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
11190 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
11191 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
11192 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
11193 #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
11194 #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
11195 #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
11196 #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
11197 #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
11198 #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
11199 #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
11201 /* Allowed return values from sqlite3WhereIsDistinct()
11203 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
11204 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
11205 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
11206 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
11209 ** A NameContext defines a context in which to resolve table and column
11210 ** names. The context consists of a list of tables (the pSrcList) field and
11211 ** a list of named expression (pEList). The named expression list may
11212 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
11213 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
11214 ** pEList corresponds to the result set of a SELECT and is NULL for
11215 ** other statements.
11217 ** NameContexts can be nested. When resolving names, the inner-most
11218 ** context is searched first. If no match is found, the next outer
11219 ** context is checked. If there is still no match, the next context
11220 ** is checked. This process continues until either a match is found
11221 ** or all contexts are check. When a match is found, the nRef member of
11222 ** the context containing the match is incremented.
11224 ** Each subquery gets a new NameContext. The pNext field points to the
11225 ** NameContext in the parent query. Thus the process of scanning the
11226 ** NameContext list corresponds to searching through successively outer
11227 ** subqueries looking for a match.
11229 struct NameContext {
11230 Parse *pParse; /* The parser */
11231 SrcList *pSrcList; /* One or more tables used to resolve names */
11232 ExprList *pEList; /* Optional list of result-set columns */
11233 AggInfo *pAggInfo; /* Information about aggregates at this level */
11234 NameContext *pNext; /* Next outer name context. NULL for outermost */
11235 int nRef; /* Number of names resolved by this context */
11236 int nErr; /* Number of errors encountered while resolving names */
11237 u8 ncFlags; /* Zero or more NC_* flags defined below */
11241 ** Allowed values for the NameContext, ncFlags field.
11243 #define NC_AllowAgg 0x01 /* Aggregate functions are allowed here */
11244 #define NC_HasAgg 0x02 /* One or more aggregate functions seen */
11245 #define NC_IsCheck 0x04 /* True if resolving names in a CHECK constraint */
11246 #define NC_InAggFunc 0x08 /* True if analyzing arguments to an agg func */
11247 #define NC_PartIdx 0x10 /* True if resolving a partial index WHERE */
11250 ** An instance of the following structure contains all information
11251 ** needed to generate code for a single SELECT statement.
11253 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
11254 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11255 ** limit and nOffset to the value of the offset (or 0 if there is not
11256 ** offset). But later on, nLimit and nOffset become the memory locations
11257 ** in the VDBE that record the limit and offset counters.
11259 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11260 ** These addresses must be stored so that we can go back and fill in
11261 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
11262 ** the number of columns in P2 can be computed at the same time
11263 ** as the OP_OpenEphm instruction is coded because not
11264 ** enough information about the compound query is known at that point.
11265 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11266 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
11267 ** sequences for the ORDER BY clause.
11269 struct Select {
11270 ExprList *pEList; /* The fields of the result */
11271 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11272 u16 selFlags; /* Various SF_* values */
11273 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
11274 int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
11275 u64 nSelectRow; /* Estimated number of result rows */
11276 SrcList *pSrc; /* The FROM clause */
11277 Expr *pWhere; /* The WHERE clause */
11278 ExprList *pGroupBy; /* The GROUP BY clause */
11279 Expr *pHaving; /* The HAVING clause */
11280 ExprList *pOrderBy; /* The ORDER BY clause */
11281 Select *pPrior; /* Prior select in a compound select statement */
11282 Select *pNext; /* Next select to the left in a compound */
11283 Select *pRightmost; /* Right-most select in a compound select statement */
11284 Expr *pLimit; /* LIMIT expression. NULL means not used. */
11285 Expr *pOffset; /* OFFSET expression. NULL means not used. */
11289 ** Allowed values for Select.selFlags. The "SF" prefix stands for
11290 ** "Select Flag".
11292 #define SF_Distinct 0x0001 /* Output should be DISTINCT */
11293 #define SF_Resolved 0x0002 /* Identifiers have been resolved */
11294 #define SF_Aggregate 0x0004 /* Contains aggregate functions */
11295 #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
11296 #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
11297 #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
11298 #define SF_UseSorter 0x0040 /* Sort using a sorter */
11299 #define SF_Values 0x0080 /* Synthesized from VALUES clause */
11300 #define SF_Materialize 0x0100 /* Force materialization of views */
11301 #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
11302 #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
11306 ** The results of a select can be distributed in several ways. The
11307 ** "SRT" prefix means "SELECT Result Type".
11309 #define SRT_Union 1 /* Store result as keys in an index */
11310 #define SRT_Except 2 /* Remove result from a UNION index */
11311 #define SRT_Exists 3 /* Store 1 if the result is not empty */
11312 #define SRT_Discard 4 /* Do not save the results anywhere */
11314 /* The ORDER BY clause is ignored for all of the above */
11315 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
11317 #define SRT_Output 5 /* Output each row of result */
11318 #define SRT_Mem 6 /* Store result in a memory cell */
11319 #define SRT_Set 7 /* Store results as keys in an index */
11320 #define SRT_Table 8 /* Store result as data with an automatic rowid */
11321 #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
11322 #define SRT_Coroutine 10 /* Generate a single row of result */
11325 ** An instance of this object describes where to put of the results of
11326 ** a SELECT statement.
11328 struct SelectDest {
11329 u8 eDest; /* How to dispose of the results. On of SRT_* above. */
11330 char affSdst; /* Affinity used when eDest==SRT_Set */
11331 int iSDParm; /* A parameter used by the eDest disposal method */
11332 int iSdst; /* Base register where results are written */
11333 int nSdst; /* Number of registers allocated */
11337 ** During code generation of statements that do inserts into AUTOINCREMENT
11338 ** tables, the following information is attached to the Table.u.autoInc.p
11339 ** pointer of each autoincrement table to record some side information that
11340 ** the code generator needs. We have to keep per-table autoincrement
11341 ** information in case inserts are down within triggers. Triggers do not
11342 ** normally coordinate their activities, but we do need to coordinate the
11343 ** loading and saving of autoincrement information.
11345 struct AutoincInfo {
11346 AutoincInfo *pNext; /* Next info block in a list of them all */
11347 Table *pTab; /* Table this info block refers to */
11348 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
11349 int regCtr; /* Memory register holding the rowid counter */
11353 ** Size of the column cache
11355 #ifndef SQLITE_N_COLCACHE
11356 # define SQLITE_N_COLCACHE 10
11357 #endif
11360 ** At least one instance of the following structure is created for each
11361 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11362 ** statement. All such objects are stored in the linked list headed at
11363 ** Parse.pTriggerPrg and deleted once statement compilation has been
11364 ** completed.
11366 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
11367 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11368 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11369 ** The Parse.pTriggerPrg list never contains two entries with the same
11370 ** values for both pTrigger and orconf.
11372 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11373 ** accessed (or set to 0 for triggers fired as a result of INSERT
11374 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11375 ** a mask of new.* columns used by the program.
11377 struct TriggerPrg {
11378 Trigger *pTrigger; /* Trigger this program was coded from */
11379 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
11380 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
11381 int orconf; /* Default ON CONFLICT policy */
11382 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
11386 ** The yDbMask datatype for the bitmask of all attached databases.
11388 #if SQLITE_MAX_ATTACHED>30
11389 typedef sqlite3_uint64 yDbMask;
11390 #else
11391 typedef unsigned int yDbMask;
11392 #endif
11395 ** An SQL parser context. A copy of this structure is passed through
11396 ** the parser and down into all the parser action routine in order to
11397 ** carry around information that is global to the entire parse.
11399 ** The structure is divided into two parts. When the parser and code
11400 ** generate call themselves recursively, the first part of the structure
11401 ** is constant but the second part is reset at the beginning and end of
11402 ** each recursion.
11404 ** The nTableLock and aTableLock variables are only used if the shared-cache
11405 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11406 ** used to store the set of table-locks required by the statement being
11407 ** compiled. Function sqlite3TableLock() is used to add entries to the
11408 ** list.
11410 struct Parse {
11411 sqlite3 *db; /* The main database structure */
11412 char *zErrMsg; /* An error message */
11413 Vdbe *pVdbe; /* An engine for executing database bytecode */
11414 int rc; /* Return code from execution */
11415 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
11416 u8 checkSchema; /* Causes schema cookie check after an error */
11417 u8 nested; /* Number of nested calls to the parser/code generator */
11418 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
11419 u8 nTempInUse; /* Number of aTempReg[] currently checked out */
11420 u8 nColCache; /* Number of entries in aColCache[] */
11421 u8 iColCache; /* Next entry in aColCache[] to replace */
11422 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
11423 u8 mayAbort; /* True if statement may throw an ABORT exception */
11424 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
11425 int aTempReg[8]; /* Holding area for temporary registers */
11426 int nRangeReg; /* Size of the temporary register block */
11427 int iRangeReg; /* First register in temporary register block */
11428 int nErr; /* Number of errors seen */
11429 int nTab; /* Number of previously allocated VDBE cursors */
11430 int nMem; /* Number of memory cells used so far */
11431 int nSet; /* Number of sets used so far */
11432 int nOnce; /* Number of OP_Once instructions so far */
11433 int ckBase; /* Base register of data during check constraints */
11434 int iPartIdxTab; /* Table corresponding to a partial index */
11435 int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11436 int iCacheCnt; /* Counter used to generate aColCache[].lru values */
11437 struct yColCache {
11438 int iTable; /* Table cursor number */
11439 int iColumn; /* Table column number */
11440 u8 tempReg; /* iReg is a temp register that needs to be freed */
11441 int iLevel; /* Nesting level */
11442 int iReg; /* Reg with value of this column. 0 means none. */
11443 int lru; /* Least recently used entry has the smallest value */
11444 } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
11445 yDbMask writeMask; /* Start a write transaction on these databases */
11446 yDbMask cookieMask; /* Bitmask of schema verified databases */
11447 int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
11448 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
11449 int regRowid; /* Register holding rowid of CREATE TABLE entry */
11450 int regRoot; /* Register holding root page number for new objects */
11451 int nMaxArg; /* Max args passed to user function by sub-program */
11452 Token constraintName;/* Name of the constraint currently being parsed */
11453 #ifndef SQLITE_OMIT_SHARED_CACHE
11454 int nTableLock; /* Number of locks in aTableLock */
11455 TableLock *aTableLock; /* Required table locks for shared-cache mode */
11456 #endif
11457 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
11459 /* Information used while coding trigger programs. */
11460 Parse *pToplevel; /* Parse structure for main program (or NULL) */
11461 Table *pTriggerTab; /* Table triggers are being coded for */
11462 u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
11463 u32 oldmask; /* Mask of old.* columns referenced */
11464 u32 newmask; /* Mask of new.* columns referenced */
11465 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
11466 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
11467 u8 disableTriggers; /* True to disable triggers */
11469 /* Above is constant between recursions. Below is reset before and after
11470 ** each recursion */
11472 int nVar; /* Number of '?' variables seen in the SQL so far */
11473 int nzVar; /* Number of available slots in azVar[] */
11474 u8 explain; /* True if the EXPLAIN flag is found on the query */
11475 #ifndef SQLITE_OMIT_VIRTUALTABLE
11476 u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
11477 int nVtabLock; /* Number of virtual tables to lock */
11478 #endif
11479 int nAlias; /* Number of aliased result set columns */
11480 int nHeight; /* Expression tree height of current sub-select */
11481 #ifndef SQLITE_OMIT_EXPLAIN
11482 int iSelectId; /* ID of current select for EXPLAIN output */
11483 int iNextSelectId; /* Next available select ID for EXPLAIN output */
11484 #endif
11485 char **azVar; /* Pointers to names of parameters */
11486 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
11487 int *aAlias; /* Register used to hold aliased result */
11488 const char *zTail; /* All SQL text past the last semicolon parsed */
11489 Table *pNewTable; /* A table being constructed by CREATE TABLE */
11490 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
11491 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11492 Token sNameToken; /* Token with unqualified schema object name */
11493 Token sLastToken; /* The last token parsed */
11494 #ifndef SQLITE_OMIT_VIRTUALTABLE
11495 Token sArg; /* Complete text of a module argument */
11496 Table **apVtabLock; /* Pointer to virtual tables needing locking */
11497 #endif
11498 Table *pZombieTab; /* List of Table objects to delete after code gen */
11499 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
11503 ** Return true if currently inside an sqlite3_declare_vtab() call.
11505 #ifdef SQLITE_OMIT_VIRTUALTABLE
11506 #define IN_DECLARE_VTAB 0
11507 #else
11508 #define IN_DECLARE_VTAB (pParse->declareVtab)
11509 #endif
11512 ** An instance of the following structure can be declared on a stack and used
11513 ** to save the Parse.zAuthContext value so that it can be restored later.
11515 struct AuthContext {
11516 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
11517 Parse *pParse; /* The Parse structure */
11521 ** Bitfield flags for P5 value in various opcodes.
11523 #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
11524 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
11525 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
11526 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
11527 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
11528 #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
11529 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
11530 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
11531 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
11532 #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
11533 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
11536 * Each trigger present in the database schema is stored as an instance of
11537 * struct Trigger.
11539 * Pointers to instances of struct Trigger are stored in two ways.
11540 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
11541 * database). This allows Trigger structures to be retrieved by name.
11542 * 2. All triggers associated with a single table form a linked list, using the
11543 * pNext member of struct Trigger. A pointer to the first element of the
11544 * linked list is stored as the "pTrigger" member of the associated
11545 * struct Table.
11547 * The "step_list" member points to the first element of a linked list
11548 * containing the SQL statements specified as the trigger program.
11550 struct Trigger {
11551 char *zName; /* The name of the trigger */
11552 char *table; /* The table or view to which the trigger applies */
11553 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
11554 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11555 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
11556 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
11557 the <column-list> is stored here */
11558 Schema *pSchema; /* Schema containing the trigger */
11559 Schema *pTabSchema; /* Schema containing the table */
11560 TriggerStep *step_list; /* Link list of trigger program steps */
11561 Trigger *pNext; /* Next trigger associated with the table */
11565 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
11566 ** determine which.
11568 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11569 ** In that cases, the constants below can be ORed together.
11571 #define TRIGGER_BEFORE 1
11572 #define TRIGGER_AFTER 2
11575 * An instance of struct TriggerStep is used to store a single SQL statement
11576 * that is a part of a trigger-program.
11578 * Instances of struct TriggerStep are stored in a singly linked list (linked
11579 * using the "pNext" member) referenced by the "step_list" member of the
11580 * associated struct Trigger instance. The first element of the linked list is
11581 * the first step of the trigger-program.
11583 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11584 * "SELECT" statement. The meanings of the other members is determined by the
11585 * value of "op" as follows:
11587 * (op == TK_INSERT)
11588 * orconf -> stores the ON CONFLICT algorithm
11589 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
11590 * this stores a pointer to the SELECT statement. Otherwise NULL.
11591 * target -> A token holding the quoted name of the table to insert into.
11592 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11593 * this stores values to be inserted. Otherwise NULL.
11594 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
11595 * statement, then this stores the column-names to be
11596 * inserted into.
11598 * (op == TK_DELETE)
11599 * target -> A token holding the quoted name of the table to delete from.
11600 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
11601 * Otherwise NULL.
11603 * (op == TK_UPDATE)
11604 * target -> A token holding the quoted name of the table to update rows of.
11605 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
11606 * Otherwise NULL.
11607 * pExprList -> A list of the columns to update and the expressions to update
11608 * them to. See sqlite3Update() documentation of "pChanges"
11609 * argument.
11612 struct TriggerStep {
11613 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11614 u8 orconf; /* OE_Rollback etc. */
11615 Trigger *pTrig; /* The trigger that this step is a part of */
11616 Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11617 Token target; /* Target table for DELETE, UPDATE, INSERT */
11618 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
11619 ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
11620 IdList *pIdList; /* Column names for INSERT */
11621 TriggerStep *pNext; /* Next in the link-list */
11622 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
11626 ** The following structure contains information used by the sqliteFix...
11627 ** routines as they walk the parse tree to make database references
11628 ** explicit.
11630 typedef struct DbFixer DbFixer;
11631 struct DbFixer {
11632 Parse *pParse; /* The parsing context. Error messages written here */
11633 Schema *pSchema; /* Fix items to this schema */
11634 const char *zDb; /* Make sure all objects are contained in this database */
11635 const char *zType; /* Type of the container - used for error messages */
11636 const Token *pName; /* Name of the container - used for error messages */
11640 ** An objected used to accumulate the text of a string where we
11641 ** do not necessarily know how big the string will be in the end.
11643 struct StrAccum {
11644 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
11645 char *zBase; /* A base allocation. Not from malloc. */
11646 char *zText; /* The string collected so far */
11647 int nChar; /* Length of the string so far */
11648 int nAlloc; /* Amount of space allocated in zText */
11649 int mxAlloc; /* Maximum allowed string length */
11650 u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
11651 u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
11653 #define STRACCUM_NOMEM 1
11654 #define STRACCUM_TOOBIG 2
11657 ** A pointer to this structure is used to communicate information
11658 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11660 typedef struct {
11661 sqlite3 *db; /* The database being initialized */
11662 char **pzErrMsg; /* Error message stored here */
11663 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
11664 int rc; /* Result code stored here */
11665 } InitData;
11668 ** Structure containing global configuration data for the SQLite library.
11670 ** This structure also contains some state information.
11672 struct Sqlite3Config {
11673 int bMemstat; /* True to enable memory status */
11674 int bCoreMutex; /* True to enable core mutexing */
11675 int bFullMutex; /* True to enable full mutexing */
11676 int bOpenUri; /* True to interpret filenames as URIs */
11677 int bUseCis; /* Use covering indices for full-scans */
11678 int mxStrlen; /* Maximum string length */
11679 int szLookaside; /* Default lookaside buffer size */
11680 int nLookaside; /* Default lookaside buffer count */
11681 sqlite3_mem_methods m; /* Low-level memory allocation interface */
11682 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
11683 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
11684 void *pHeap; /* Heap storage space */
11685 int nHeap; /* Size of pHeap[] */
11686 int mnReq, mxReq; /* Min and max heap requests sizes */
11687 sqlite3_int64 szMmap; /* mmap() space per open file */
11688 sqlite3_int64 mxMmap; /* Maximum value for szMmap */
11689 void *pScratch; /* Scratch memory */
11690 int szScratch; /* Size of each scratch buffer */
11691 int nScratch; /* Number of scratch buffers */
11692 void *pPage; /* Page cache memory */
11693 int szPage; /* Size of each page in pPage[] */
11694 int nPage; /* Number of pages in pPage[] */
11695 int mxParserStack; /* maximum depth of the parser stack */
11696 int sharedCacheEnabled; /* true if shared-cache mode enabled */
11697 /* The above might be initialized to non-zero. The following need to always
11698 ** initially be zero, however. */
11699 int isInit; /* True after initialization has finished */
11700 int inProgress; /* True while initialization in progress */
11701 int isMutexInit; /* True after mutexes are initialized */
11702 int isMallocInit; /* True after malloc is initialized */
11703 int isPCacheInit; /* True after malloc is initialized */
11704 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
11705 int nRefInitMutex; /* Number of users of pInitMutex */
11706 void (*xLog)(void*,int,const char*); /* Function for logging */
11707 void *pLogArg; /* First argument to xLog() */
11708 int bLocaltimeFault; /* True to fail localtime() calls */
11709 #ifdef SQLITE_ENABLE_SQLLOG
11710 void(*xSqllog)(void*,sqlite3*,const char*, int);
11711 void *pSqllogArg;
11712 #endif
11716 ** Context pointer passed down through the tree-walk.
11718 struct Walker {
11719 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
11720 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
11721 Parse *pParse; /* Parser context. */
11722 int walkerDepth; /* Number of subqueries */
11723 u8 bSelectDepthFirst; /* Do subqueries first */
11724 union { /* Extra data for callback */
11725 NameContext *pNC; /* Naming context */
11726 int i; /* Integer value */
11727 SrcList *pSrcList; /* FROM clause */
11728 struct SrcCount *pSrcCount; /* Counting column references */
11729 } u;
11732 /* Forward declarations */
11733 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11734 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11735 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11736 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11737 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11740 ** Return code from the parse-tree walking primitives and their
11741 ** callbacks.
11743 #define WRC_Continue 0 /* Continue down into children */
11744 #define WRC_Prune 1 /* Omit children but continue walking siblings */
11745 #define WRC_Abort 2 /* Abandon the tree walk */
11748 ** Assuming zIn points to the first byte of a UTF-8 character,
11749 ** advance zIn to point to the first byte of the next UTF-8 character.
11751 #define SQLITE_SKIP_UTF8(zIn) { \
11752 if( (*(zIn++))>=0xc0 ){ \
11753 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
11758 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11759 ** the same name but without the _BKPT suffix. These macros invoke
11760 ** routines that report the line-number on which the error originated
11761 ** using sqlite3_log(). The routines also provide a convenient place
11762 ** to set a debugger breakpoint.
11764 SQLITE_PRIVATE int sqlite3CorruptError(int);
11765 SQLITE_PRIVATE int sqlite3MisuseError(int);
11766 SQLITE_PRIVATE int sqlite3CantopenError(int);
11767 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11768 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11769 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11773 ** FTS4 is really an extension for FTS3. It is enabled using the
11774 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
11775 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11777 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11778 # define SQLITE_ENABLE_FTS3
11779 #endif
11782 ** The ctype.h header is needed for non-ASCII systems. It is also
11783 ** needed by FTS3 when FTS3 is included in the amalgamation.
11785 #if !defined(SQLITE_ASCII) || \
11786 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11787 # include <ctype.h>
11788 #endif
11791 ** The following macros mimic the standard library functions toupper(),
11792 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11793 ** sqlite versions only work for ASCII characters, regardless of locale.
11795 #ifdef SQLITE_ASCII
11796 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11797 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11798 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11799 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11800 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11801 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11802 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
11803 #else
11804 # define sqlite3Toupper(x) toupper((unsigned char)(x))
11805 # define sqlite3Isspace(x) isspace((unsigned char)(x))
11806 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
11807 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
11808 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
11809 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
11810 # define sqlite3Tolower(x) tolower((unsigned char)(x))
11811 #endif
11814 ** Internal function prototypes
11816 #define sqlite3StrICmp sqlite3_stricmp
11817 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11818 #define sqlite3StrNICmp sqlite3_strnicmp
11820 SQLITE_PRIVATE int sqlite3MallocInit(void);
11821 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11822 SQLITE_PRIVATE void *sqlite3Malloc(int);
11823 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11824 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11825 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11826 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11827 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11828 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11829 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11830 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11831 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11832 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11833 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11834 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11835 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11836 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11837 SQLITE_PRIVATE void sqlite3PageFree(void*);
11838 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11839 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11840 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11843 ** On systems with ample stack space and that support alloca(), make
11844 ** use of alloca() to obtain space for large automatic objects. By default,
11845 ** obtain space from malloc().
11847 ** The alloca() routine never returns NULL. This will cause code paths
11848 ** that deal with sqlite3StackAlloc() failures to be unreachable.
11850 #ifdef SQLITE_USE_ALLOCA
11851 # define sqlite3StackAllocRaw(D,N) alloca(N)
11852 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
11853 # define sqlite3StackFree(D,P)
11854 #else
11855 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
11856 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
11857 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
11858 #endif
11860 #ifdef SQLITE_ENABLE_MEMSYS3
11861 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11862 #endif
11863 #ifdef SQLITE_ENABLE_MEMSYS5
11864 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11865 #endif
11868 #ifndef SQLITE_MUTEX_OMIT
11869 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11870 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11871 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
11872 SQLITE_PRIVATE int sqlite3MutexInit(void);
11873 SQLITE_PRIVATE int sqlite3MutexEnd(void);
11874 #endif
11876 SQLITE_PRIVATE int sqlite3StatusValue(int);
11877 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11878 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11880 #ifndef SQLITE_OMIT_FLOATING_POINT
11881 SQLITE_PRIVATE int sqlite3IsNaN(double);
11882 #else
11883 # define sqlite3IsNaN(X) 0
11884 #endif
11886 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11887 #ifndef SQLITE_OMIT_TRACE
11888 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11889 #endif
11890 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11891 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11892 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11893 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11894 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
11895 #endif
11896 #if defined(SQLITE_TEST)
11897 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
11898 #endif
11900 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
11901 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
11902 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe*);
11903 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
11904 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe*);
11905 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe*);
11906 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe*);
11907 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe*);
11908 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe*, Select*);
11909 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe*, Expr*);
11910 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe*, ExprList*);
11911 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe*);
11912 #else
11913 # define sqlite3ExplainBegin(X)
11914 # define sqlite3ExplainSelect(A,B)
11915 # define sqlite3ExplainExpr(A,B)
11916 # define sqlite3ExplainExprList(A,B)
11917 # define sqlite3ExplainFinish(X)
11918 # define sqlite3VdbeExplanation(X) 0
11919 #endif
11922 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11923 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11924 SQLITE_PRIVATE int sqlite3Dequote(char*);
11925 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11926 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11927 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11928 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11929 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11930 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11931 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11932 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
11933 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11934 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11935 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11936 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11937 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11938 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11939 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11940 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11941 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11942 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11943 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11944 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11945 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11946 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11947 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11948 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
11949 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
11950 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
11951 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11952 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11953 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11954 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11955 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11956 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11957 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11958 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11959 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11960 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11961 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11962 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11963 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11964 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11965 sqlite3_vfs**,char**,char **);
11966 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
11967 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
11969 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11970 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11971 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11972 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11973 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11974 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11975 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11977 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11978 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11979 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11980 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11981 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11983 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11985 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11986 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
11987 #else
11988 # define sqlite3ViewGetColumnNames(A,B) 0
11989 #endif
11991 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11992 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
11993 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11994 #ifndef SQLITE_OMIT_AUTOINCREMENT
11995 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
11996 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
11997 #else
11998 # define sqlite3AutoincrementBegin(X)
11999 # define sqlite3AutoincrementEnd(X)
12000 #endif
12001 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
12002 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
12003 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
12004 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
12005 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
12006 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
12007 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
12008 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
12009 Token*, Select*, Expr*, IdList*);
12010 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
12011 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
12012 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
12013 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
12014 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
12015 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
12016 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
12017 Expr*, int, int);
12018 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
12019 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
12020 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
12021 Expr*,ExprList*,u16,Expr*,Expr*);
12022 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
12023 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
12024 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
12025 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
12026 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
12027 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
12028 #endif
12029 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
12030 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
12031 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
12032 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
12033 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
12034 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
12035 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
12036 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
12037 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
12038 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*);
12039 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
12040 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
12041 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
12042 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
12043 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
12044 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
12045 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
12046 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
12047 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
12048 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
12049 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
12050 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
12051 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
12052 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
12053 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
12054 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
12055 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
12056 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
12057 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
12058 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
12059 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
12060 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
12061 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
12062 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
12063 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
12064 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
12065 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
12066 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
12067 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
12068 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
12069 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
12070 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
12071 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
12072 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
12073 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
12074 SQLITE_PRIVATE void sqlite3PrngResetState(void);
12075 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
12076 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
12077 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
12078 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
12079 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
12080 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
12081 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
12082 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
12083 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
12084 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
12085 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
12086 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
12087 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
12088 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
12089 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
12090 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
12091 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
12092 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
12093 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
12094 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*);
12095 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
12096 int*,int,int,int,int,int*);
12097 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
12098 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
12099 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
12100 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
12101 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
12102 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int);
12103 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12104 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12105 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12106 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12107 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12108 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12109 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12110 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12111 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12112 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12113 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12114 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12115 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12117 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12118 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12119 #endif
12121 #ifndef SQLITE_OMIT_TRIGGER
12122 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12123 Expr*,int, int);
12124 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12125 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
12126 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
12127 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12128 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
12129 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12130 int, int, int);
12131 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12132 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12133 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12134 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12135 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12136 ExprList*,Select*,u8);
12137 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12138 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12139 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12140 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12141 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12142 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12143 #else
12144 # define sqlite3TriggersExist(B,C,D,E,F) 0
12145 # define sqlite3DeleteTrigger(A,B)
12146 # define sqlite3DropTriggerPtr(A,B)
12147 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12148 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12149 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12150 # define sqlite3TriggerList(X, Y) 0
12151 # define sqlite3ParseToplevel(p) p
12152 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12153 #endif
12155 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12156 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12157 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12158 #ifndef SQLITE_OMIT_AUTHORIZATION
12159 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12160 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12161 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12162 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
12163 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12164 #else
12165 # define sqlite3AuthRead(a,b,c,d)
12166 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
12167 # define sqlite3AuthContextPush(a,b,c)
12168 # define sqlite3AuthContextPop(a) ((void)(a))
12169 #endif
12170 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12171 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12172 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12173 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12174 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12175 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12176 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12177 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12178 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12179 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12180 SQLITE_PRIVATE int sqlite3Atoi(const char*);
12181 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12182 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12183 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12186 ** Routines to read and write variable-length integers. These used to
12187 ** be defined locally, but now we use the varint routines in the util.c
12188 ** file. Code should use the MACRO forms below, as the Varint32 versions
12189 ** are coded to assume the single byte case is already handled (which
12190 ** the MACRO form does).
12192 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12193 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
12194 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12195 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12196 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12199 ** The header of a record consists of a sequence variable-length integers.
12200 ** These integers are almost always small and are encoded as a single byte.
12201 ** The following macros take advantage this fact to provide a fast encode
12202 ** and decode of the integers in a record header. It is faster for the common
12203 ** case where the integer is a single byte. It is a little slower when the
12204 ** integer is two or more bytes. But overall it is faster.
12206 ** The following expressions are equivalent:
12208 ** x = sqlite3GetVarint32( A, &B );
12209 ** x = sqlite3PutVarint32( A, B );
12211 ** x = getVarint32( A, B );
12212 ** x = putVarint32( A, B );
12215 #define getVarint32(A,B) \
12216 (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
12217 #define putVarint32(A,B) \
12218 (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
12219 sqlite3PutVarint32((A),(B)))
12220 #define getVarint sqlite3GetVarint
12221 #define putVarint sqlite3PutVarint
12224 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12225 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
12226 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12227 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12228 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12229 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12230 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
12231 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12232 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12233 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12235 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
12236 defined(SQLITE_DEBUG_OS_TRACE)
12237 SQLITE_PRIVATE const char *sqlite3ErrName(int);
12238 #endif
12240 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12241 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12242 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12243 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12244 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12245 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
12246 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
12247 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
12248 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12249 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12250 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12251 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12252 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12253 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12254 SQLITE_PRIVATE int sqlite3AbsInt32(int);
12255 #ifdef SQLITE_ENABLE_8_3_NAMES
12256 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12257 #else
12258 # define sqlite3FileSuffix3(X,Y)
12259 #endif
12260 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
12262 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12263 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12264 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
12265 void(*)(void*));
12266 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
12267 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
12268 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
12269 #ifdef SQLITE_ENABLE_STAT3
12270 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
12271 #endif
12272 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
12273 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
12274 #ifndef SQLITE_AMALGAMATION
12275 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
12276 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12277 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12278 SQLITE_PRIVATE const Token sqlite3IntTokens[];
12279 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12280 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12281 #ifndef SQLITE_OMIT_WSD
12282 SQLITE_PRIVATE int sqlite3PendingByte;
12283 #endif
12284 #endif
12285 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12286 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12287 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12288 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12289 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12290 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12291 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12292 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12293 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12294 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
12295 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12296 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12297 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
12298 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12299 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12300 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12301 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12302 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
12303 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
12304 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12305 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12306 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12307 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12308 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12309 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12310 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12311 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12312 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12313 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12314 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12315 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12316 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12317 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int);
12318 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
12319 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
12320 void (*)(sqlite3_context*,int,sqlite3_value **),
12321 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12322 FuncDestructor *pDestructor
12324 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12325 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12327 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12328 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12329 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12330 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12331 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12332 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12333 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12335 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12336 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12339 ** The interface to the LEMON-generated parser
12341 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12342 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12343 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12344 #ifdef YYTRACKMAXSTACKDEPTH
12345 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
12346 #endif
12348 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12349 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12350 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
12351 #else
12352 # define sqlite3CloseExtensions(X)
12353 #endif
12355 #ifndef SQLITE_OMIT_SHARED_CACHE
12356 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
12357 #else
12358 #define sqlite3TableLock(v,w,x,y,z)
12359 #endif
12361 #ifdef SQLITE_TEST
12362 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
12363 #endif
12365 #ifdef SQLITE_OMIT_VIRTUALTABLE
12366 # define sqlite3VtabClear(Y)
12367 # define sqlite3VtabSync(X,Y) SQLITE_OK
12368 # define sqlite3VtabRollback(X)
12369 # define sqlite3VtabCommit(X)
12370 # define sqlite3VtabInSync(db) 0
12371 # define sqlite3VtabLock(X)
12372 # define sqlite3VtabUnlock(X)
12373 # define sqlite3VtabUnlockList(X)
12374 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12375 # define sqlite3GetVTable(X,Y) ((VTable*)0)
12376 #else
12377 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
12378 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12379 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
12380 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
12381 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
12382 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
12383 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
12384 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
12385 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
12386 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
12387 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
12388 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12389 #endif
12390 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12391 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12392 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12393 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12394 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12395 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12396 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12397 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12398 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12399 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12400 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12401 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12402 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12403 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12404 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12405 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12406 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12407 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12408 #ifndef SQLITE_OMIT_WAL
12409 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12410 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12411 #endif
12413 /* Declarations for functions in fkey.c. All of these are replaced by
12414 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12415 ** key functionality is available. If OMIT_TRIGGER is defined but
12416 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12417 ** this case foreign keys are parsed, but no other functionality is
12418 ** provided (enforcement of FK constraints requires the triggers sub-system).
12420 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12421 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int);
12422 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12423 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int);
12424 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
12425 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
12426 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
12427 #else
12428 #define sqlite3FkActions(a,b,c,d)
12429 #define sqlite3FkCheck(a,b,c,d)
12430 #define sqlite3FkDropTable(a,b,c)
12431 #define sqlite3FkOldmask(a,b) 0
12432 #define sqlite3FkRequired(a,b,c,d) 0
12433 #endif
12434 #ifndef SQLITE_OMIT_FOREIGN_KEY
12435 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
12436 SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
12437 #else
12438 #define sqlite3FkDelete(a,b)
12439 #define sqlite3FkLocateIndex(a,b,c,d,e)
12440 #endif
12444 ** Available fault injectors. Should be numbered beginning with 0.
12446 #define SQLITE_FAULTINJECTOR_MALLOC 0
12447 #define SQLITE_FAULTINJECTOR_COUNT 1
12450 ** The interface to the code in fault.c used for identifying "benign"
12451 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12452 ** is not defined.
12454 #ifndef SQLITE_OMIT_BUILTIN_TEST
12455 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
12456 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
12457 #else
12458 #define sqlite3BeginBenignMalloc()
12459 #define sqlite3EndBenignMalloc()
12460 #endif
12462 #define IN_INDEX_ROWID 1
12463 #define IN_INDEX_EPH 2
12464 #define IN_INDEX_INDEX_ASC 3
12465 #define IN_INDEX_INDEX_DESC 4
12466 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12468 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12469 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12470 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
12471 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
12472 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
12473 #else
12474 #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12475 #define sqlite3JournalExists(p) 1
12476 #endif
12478 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12479 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12480 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12482 #if SQLITE_MAX_EXPR_DEPTH>0
12483 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12484 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
12485 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
12486 #else
12487 #define sqlite3ExprSetHeight(x,y)
12488 #define sqlite3SelectExprHeight(x) 0
12489 #define sqlite3ExprCheckHeight(x,y)
12490 #endif
12492 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12493 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12495 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12496 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12497 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
12498 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
12499 #else
12500 #define sqlite3ConnectionBlocked(x,y)
12501 #define sqlite3ConnectionUnlocked(x)
12502 #define sqlite3ConnectionClosed(x)
12503 #endif
12505 #ifdef SQLITE_DEBUG
12506 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
12507 #endif
12510 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
12511 ** sqlite3IoTrace is a pointer to a printf-like routine used to
12512 ** print I/O tracing messages.
12514 #ifdef SQLITE_ENABLE_IOTRACE
12515 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12516 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
12517 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12518 #else
12519 # define IOTRACE(A)
12520 # define sqlite3VdbeIOTraceSql(X)
12521 #endif
12524 ** These routines are available for the mem2.c debugging memory allocator
12525 ** only. They are used to verify that different "types" of memory
12526 ** allocations are properly tracked by the system.
12528 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12529 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
12530 ** a single bit set.
12532 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
12533 ** argument match the type set by the previous sqlite3MemdebugSetType().
12534 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12536 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
12537 ** argument match the type set by the previous sqlite3MemdebugSetType().
12539 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
12540 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
12541 ** it might have been allocated by lookaside, except the allocation was
12542 ** too large or lookaside was already full. It is important to verify
12543 ** that allocations that might have been satisfied by lookaside are not
12544 ** passed back to non-lookaside free() routines. Asserts such as the
12545 ** example above are placed on the non-lookaside free() routines to verify
12546 ** this constraint.
12548 ** All of this is no-op for a production build. It only comes into
12549 ** play when the SQLITE_MEMDEBUG compile-time option is used.
12551 #ifdef SQLITE_MEMDEBUG
12552 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
12553 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
12554 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
12555 #else
12556 # define sqlite3MemdebugSetType(X,Y) /* no-op */
12557 # define sqlite3MemdebugHasType(X,Y) 1
12558 # define sqlite3MemdebugNoType(X,Y) 1
12559 #endif
12560 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
12561 #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
12562 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
12563 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
12564 #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
12566 #endif /* _SQLITEINT_H_ */
12568 /************** End of sqliteInt.h *******************************************/
12569 /************** Begin file global.c ******************************************/
12571 ** 2008 June 13
12573 ** The author disclaims copyright to this source code. In place of
12574 ** a legal notice, here is a blessing:
12576 ** May you do good and not evil.
12577 ** May you find forgiveness for yourself and forgive others.
12578 ** May you share freely, never taking more than you give.
12580 *************************************************************************
12582 ** This file contains definitions of global variables and contants.
12585 /* An array to map all upper-case characters into their corresponding
12586 ** lower-case character.
12588 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
12589 ** handle case conversions for the UTF character set since the tables
12590 ** involved are nearly as big or bigger than SQLite itself.
12592 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12593 #ifdef SQLITE_ASCII
12594 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
12595 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12596 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12597 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12598 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12599 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12600 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12601 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12602 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12603 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12604 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12605 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12606 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12607 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12608 252,253,254,255
12609 #endif
12610 #ifdef SQLITE_EBCDIC
12611 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
12612 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12613 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12614 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12615 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12616 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12617 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12618 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12619 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12620 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12621 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12622 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12623 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12624 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12625 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12626 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12627 #endif
12631 ** The following 256 byte lookup table is used to support SQLites built-in
12632 ** equivalents to the following standard library functions:
12634 ** isspace() 0x01
12635 ** isalpha() 0x02
12636 ** isdigit() 0x04
12637 ** isalnum() 0x06
12638 ** isxdigit() 0x08
12639 ** toupper() 0x20
12640 ** SQLite identifier character 0x40
12642 ** Bit 0x20 is set if the mapped character requires translation to upper
12643 ** case. i.e. if the character is a lower-case ASCII character.
12644 ** If x is a lower-case ASCII character, then its upper-case equivalent
12645 ** is (x - 0x20). Therefore toupper() can be implemented as:
12647 ** (x & ~(map[x]&0x20))
12649 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12650 ** array. tolower() is used more often than toupper() by SQLite.
12652 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
12653 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
12654 ** non-ASCII UTF character. Hence the test for whether or not a character is
12655 ** part of an identifier is 0x46.
12657 ** SQLite's versions are identical to the standard versions assuming a
12658 ** locale of "C". They are implemented as macros in sqliteInt.h.
12660 #ifdef SQLITE_ASCII
12661 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12662 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
12663 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
12664 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
12665 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
12666 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
12667 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
12668 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
12669 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
12671 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
12672 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
12673 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
12674 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
12675 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
12676 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
12677 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
12678 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
12680 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
12681 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
12682 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
12683 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
12684 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
12685 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
12686 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
12687 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
12689 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
12690 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
12691 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
12692 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
12693 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
12694 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
12695 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
12696 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
12698 #endif
12700 #ifndef SQLITE_USE_URI
12701 # define SQLITE_USE_URI 0
12702 #endif
12704 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
12705 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
12706 #endif
12709 ** The following singleton contains the global configuration for
12710 ** the SQLite library.
12712 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12713 SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
12714 1, /* bCoreMutex */
12715 SQLITE_THREADSAFE==1, /* bFullMutex */
12716 SQLITE_USE_URI, /* bOpenUri */
12717 SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
12718 0x7ffffffe, /* mxStrlen */
12719 128, /* szLookaside */
12720 500, /* nLookaside */
12721 {0,0,0,0,0,0,0,0}, /* m */
12722 {0,0,0,0,0,0,0,0,0}, /* mutex */
12723 {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12724 (void*)0, /* pHeap */
12725 0, /* nHeap */
12726 0, 0, /* mnHeap, mxHeap */
12727 SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
12728 SQLITE_MAX_MMAP_SIZE, /* mxMmap */
12729 (void*)0, /* pScratch */
12730 0, /* szScratch */
12731 0, /* nScratch */
12732 (void*)0, /* pPage */
12733 0, /* szPage */
12734 0, /* nPage */
12735 0, /* mxParserStack */
12736 0, /* sharedCacheEnabled */
12737 /* All the rest should always be initialized to zero */
12738 0, /* isInit */
12739 0, /* inProgress */
12740 0, /* isMutexInit */
12741 0, /* isMallocInit */
12742 0, /* isPCacheInit */
12743 0, /* pInitMutex */
12744 0, /* nRefInitMutex */
12745 0, /* xLog */
12746 0, /* pLogArg */
12747 0, /* bLocaltimeFault */
12748 #ifdef SQLITE_ENABLE_SQLLOG
12749 0, /* xSqllog */
12750 0 /* pSqllogArg */
12751 #endif
12756 ** Hash table for global functions - functions common to all
12757 ** database connections. After initialization, this table is
12758 ** read-only.
12760 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12763 ** Constant tokens for values 0 and 1.
12765 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12766 { "0", 1 },
12767 { "1", 1 }
12772 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12773 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
12774 ** the database page that contains the pending byte. It never attempts
12775 ** to read or write that page. The pending byte page is set assign
12776 ** for use by the VFS layers as space for managing file locks.
12778 ** During testing, it is often desirable to move the pending byte to
12779 ** a different position in the file. This allows code that has to
12780 ** deal with the pending byte to run on files that are much smaller
12781 ** than 1 GiB. The sqlite3_test_control() interface can be used to
12782 ** move the pending byte.
12784 ** IMPORTANT: Changing the pending byte to any value other than
12785 ** 0x40000000 results in an incompatible database file format!
12786 ** Changing the pending byte during operating results in undefined
12787 ** and dileterious behavior.
12789 #ifndef SQLITE_OMIT_WSD
12790 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12791 #endif
12794 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
12795 ** created by mkopcodeh.awk during compilation. Data is obtained
12796 ** from the comments following the "case OP_xxxx:" statements in
12797 ** the vdbe.c file.
12799 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12801 /************** End of global.c **********************************************/
12802 /************** Begin file ctime.c *******************************************/
12804 ** 2010 February 23
12806 ** The author disclaims copyright to this source code. In place of
12807 ** a legal notice, here is a blessing:
12809 ** May you do good and not evil.
12810 ** May you find forgiveness for yourself and forgive others.
12811 ** May you share freely, never taking more than you give.
12813 *************************************************************************
12815 ** This file implements routines used to report what compile-time options
12816 ** SQLite was built with.
12819 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12823 ** An array of names of all compile-time options. This array should
12824 ** be sorted A-Z.
12826 ** This array looks large, but in a typical installation actually uses
12827 ** only a handful of compile-time options, so most times this array is usually
12828 ** rather short and uses little memory space.
12830 static const char * const azCompileOpt[] = {
12832 /* These macros are provided to "stringify" the value of the define
12833 ** for those options in which the value is meaningful. */
12834 #define CTIMEOPT_VAL_(opt) #opt
12835 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12837 #ifdef SQLITE_32BIT_ROWID
12838 "32BIT_ROWID",
12839 #endif
12840 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12841 "4_BYTE_ALIGNED_MALLOC",
12842 #endif
12843 #ifdef SQLITE_CASE_SENSITIVE_LIKE
12844 "CASE_SENSITIVE_LIKE",
12845 #endif
12846 #ifdef SQLITE_CHECK_PAGES
12847 "CHECK_PAGES",
12848 #endif
12849 #ifdef SQLITE_COVERAGE_TEST
12850 "COVERAGE_TEST",
12851 #endif
12852 #ifdef SQLITE_DEBUG
12853 "DEBUG",
12854 #endif
12855 #ifdef SQLITE_DEFAULT_LOCKING_MODE
12856 "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12857 #endif
12858 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
12859 "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
12860 #endif
12861 #ifdef SQLITE_DISABLE_DIRSYNC
12862 "DISABLE_DIRSYNC",
12863 #endif
12864 #ifdef SQLITE_DISABLE_LFS
12865 "DISABLE_LFS",
12866 #endif
12867 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12868 "ENABLE_ATOMIC_WRITE",
12869 #endif
12870 #ifdef SQLITE_ENABLE_CEROD
12871 "ENABLE_CEROD",
12872 #endif
12873 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12874 "ENABLE_COLUMN_METADATA",
12875 #endif
12876 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12877 "ENABLE_EXPENSIVE_ASSERT",
12878 #endif
12879 #ifdef SQLITE_ENABLE_FTS1
12880 "ENABLE_FTS1",
12881 #endif
12882 #ifdef SQLITE_ENABLE_FTS2
12883 "ENABLE_FTS2",
12884 #endif
12885 #ifdef SQLITE_ENABLE_FTS3
12886 "ENABLE_FTS3",
12887 #endif
12888 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12889 "ENABLE_FTS3_PARENTHESIS",
12890 #endif
12891 #ifdef SQLITE_ENABLE_FTS4
12892 "ENABLE_FTS4",
12893 #endif
12894 #ifdef SQLITE_ENABLE_ICU
12895 "ENABLE_ICU",
12896 #endif
12897 #ifdef SQLITE_ENABLE_IOTRACE
12898 "ENABLE_IOTRACE",
12899 #endif
12900 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
12901 "ENABLE_LOAD_EXTENSION",
12902 #endif
12903 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12904 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12905 #endif
12906 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12907 "ENABLE_MEMORY_MANAGEMENT",
12908 #endif
12909 #ifdef SQLITE_ENABLE_MEMSYS3
12910 "ENABLE_MEMSYS3",
12911 #endif
12912 #ifdef SQLITE_ENABLE_MEMSYS5
12913 "ENABLE_MEMSYS5",
12914 #endif
12915 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12916 "ENABLE_OVERSIZE_CELL_CHECK",
12917 #endif
12918 #ifdef SQLITE_ENABLE_RTREE
12919 "ENABLE_RTREE",
12920 #endif
12921 #ifdef SQLITE_ENABLE_STAT3
12922 "ENABLE_STAT3",
12923 #endif
12924 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12925 "ENABLE_UNLOCK_NOTIFY",
12926 #endif
12927 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12928 "ENABLE_UPDATE_DELETE_LIMIT",
12929 #endif
12930 #ifdef SQLITE_HAS_CODEC
12931 "HAS_CODEC",
12932 #endif
12933 #ifdef SQLITE_HAVE_ISNAN
12934 "HAVE_ISNAN",
12935 #endif
12936 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12937 "HOMEGROWN_RECURSIVE_MUTEX",
12938 #endif
12939 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12940 "IGNORE_AFP_LOCK_ERRORS",
12941 #endif
12942 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12943 "IGNORE_FLOCK_LOCK_ERRORS",
12944 #endif
12945 #ifdef SQLITE_INT64_TYPE
12946 "INT64_TYPE",
12947 #endif
12948 #ifdef SQLITE_LOCK_TRACE
12949 "LOCK_TRACE",
12950 #endif
12951 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
12952 "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
12953 #endif
12954 #ifdef SQLITE_MAX_SCHEMA_RETRY
12955 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12956 #endif
12957 #ifdef SQLITE_MEMDEBUG
12958 "MEMDEBUG",
12959 #endif
12960 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12961 "MIXED_ENDIAN_64BIT_FLOAT",
12962 #endif
12963 #ifdef SQLITE_NO_SYNC
12964 "NO_SYNC",
12965 #endif
12966 #ifdef SQLITE_OMIT_ALTERTABLE
12967 "OMIT_ALTERTABLE",
12968 #endif
12969 #ifdef SQLITE_OMIT_ANALYZE
12970 "OMIT_ANALYZE",
12971 #endif
12972 #ifdef SQLITE_OMIT_ATTACH
12973 "OMIT_ATTACH",
12974 #endif
12975 #ifdef SQLITE_OMIT_AUTHORIZATION
12976 "OMIT_AUTHORIZATION",
12977 #endif
12978 #ifdef SQLITE_OMIT_AUTOINCREMENT
12979 "OMIT_AUTOINCREMENT",
12980 #endif
12981 #ifdef SQLITE_OMIT_AUTOINIT
12982 "OMIT_AUTOINIT",
12983 #endif
12984 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12985 "OMIT_AUTOMATIC_INDEX",
12986 #endif
12987 #ifdef SQLITE_OMIT_AUTORESET
12988 "OMIT_AUTORESET",
12989 #endif
12990 #ifdef SQLITE_OMIT_AUTOVACUUM
12991 "OMIT_AUTOVACUUM",
12992 #endif
12993 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12994 "OMIT_BETWEEN_OPTIMIZATION",
12995 #endif
12996 #ifdef SQLITE_OMIT_BLOB_LITERAL
12997 "OMIT_BLOB_LITERAL",
12998 #endif
12999 #ifdef SQLITE_OMIT_BTREECOUNT
13000 "OMIT_BTREECOUNT",
13001 #endif
13002 #ifdef SQLITE_OMIT_BUILTIN_TEST
13003 "OMIT_BUILTIN_TEST",
13004 #endif
13005 #ifdef SQLITE_OMIT_CAST
13006 "OMIT_CAST",
13007 #endif
13008 #ifdef SQLITE_OMIT_CHECK
13009 "OMIT_CHECK",
13010 #endif
13011 #ifdef SQLITE_OMIT_COMPLETE
13012 "OMIT_COMPLETE",
13013 #endif
13014 #ifdef SQLITE_OMIT_COMPOUND_SELECT
13015 "OMIT_COMPOUND_SELECT",
13016 #endif
13017 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13018 "OMIT_DATETIME_FUNCS",
13019 #endif
13020 #ifdef SQLITE_OMIT_DECLTYPE
13021 "OMIT_DECLTYPE",
13022 #endif
13023 #ifdef SQLITE_OMIT_DEPRECATED
13024 "OMIT_DEPRECATED",
13025 #endif
13026 #ifdef SQLITE_OMIT_DISKIO
13027 "OMIT_DISKIO",
13028 #endif
13029 #ifdef SQLITE_OMIT_EXPLAIN
13030 "OMIT_EXPLAIN",
13031 #endif
13032 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
13033 "OMIT_FLAG_PRAGMAS",
13034 #endif
13035 #ifdef SQLITE_OMIT_FLOATING_POINT
13036 "OMIT_FLOATING_POINT",
13037 #endif
13038 #ifdef SQLITE_OMIT_FOREIGN_KEY
13039 "OMIT_FOREIGN_KEY",
13040 #endif
13041 #ifdef SQLITE_OMIT_GET_TABLE
13042 "OMIT_GET_TABLE",
13043 #endif
13044 #ifdef SQLITE_OMIT_INCRBLOB
13045 "OMIT_INCRBLOB",
13046 #endif
13047 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
13048 "OMIT_INTEGRITY_CHECK",
13049 #endif
13050 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
13051 "OMIT_LIKE_OPTIMIZATION",
13052 #endif
13053 #ifdef SQLITE_OMIT_LOAD_EXTENSION
13054 "OMIT_LOAD_EXTENSION",
13055 #endif
13056 #ifdef SQLITE_OMIT_LOCALTIME
13057 "OMIT_LOCALTIME",
13058 #endif
13059 #ifdef SQLITE_OMIT_LOOKASIDE
13060 "OMIT_LOOKASIDE",
13061 #endif
13062 #ifdef SQLITE_OMIT_MEMORYDB
13063 "OMIT_MEMORYDB",
13064 #endif
13065 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
13066 "OMIT_OR_OPTIMIZATION",
13067 #endif
13068 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
13069 "OMIT_PAGER_PRAGMAS",
13070 #endif
13071 #ifdef SQLITE_OMIT_PRAGMA
13072 "OMIT_PRAGMA",
13073 #endif
13074 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
13075 "OMIT_PROGRESS_CALLBACK",
13076 #endif
13077 #ifdef SQLITE_OMIT_QUICKBALANCE
13078 "OMIT_QUICKBALANCE",
13079 #endif
13080 #ifdef SQLITE_OMIT_REINDEX
13081 "OMIT_REINDEX",
13082 #endif
13083 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
13084 "OMIT_SCHEMA_PRAGMAS",
13085 #endif
13086 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
13087 "OMIT_SCHEMA_VERSION_PRAGMAS",
13088 #endif
13089 #ifdef SQLITE_OMIT_SHARED_CACHE
13090 "OMIT_SHARED_CACHE",
13091 #endif
13092 #ifdef SQLITE_OMIT_SUBQUERY
13093 "OMIT_SUBQUERY",
13094 #endif
13095 #ifdef SQLITE_OMIT_TCL_VARIABLE
13096 "OMIT_TCL_VARIABLE",
13097 #endif
13098 #ifdef SQLITE_OMIT_TEMPDB
13099 "OMIT_TEMPDB",
13100 #endif
13101 #ifdef SQLITE_OMIT_TRACE
13102 "OMIT_TRACE",
13103 #endif
13104 #ifdef SQLITE_OMIT_TRIGGER
13105 "OMIT_TRIGGER",
13106 #endif
13107 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
13108 "OMIT_TRUNCATE_OPTIMIZATION",
13109 #endif
13110 #ifdef SQLITE_OMIT_UTF16
13111 "OMIT_UTF16",
13112 #endif
13113 #ifdef SQLITE_OMIT_VACUUM
13114 "OMIT_VACUUM",
13115 #endif
13116 #ifdef SQLITE_OMIT_VIEW
13117 "OMIT_VIEW",
13118 #endif
13119 #ifdef SQLITE_OMIT_VIRTUALTABLE
13120 "OMIT_VIRTUALTABLE",
13121 #endif
13122 #ifdef SQLITE_OMIT_WAL
13123 "OMIT_WAL",
13124 #endif
13125 #ifdef SQLITE_OMIT_WSD
13126 "OMIT_WSD",
13127 #endif
13128 #ifdef SQLITE_OMIT_XFER_OPT
13129 "OMIT_XFER_OPT",
13130 #endif
13131 #ifdef SQLITE_PERFORMANCE_TRACE
13132 "PERFORMANCE_TRACE",
13133 #endif
13134 #ifdef SQLITE_PROXY_DEBUG
13135 "PROXY_DEBUG",
13136 #endif
13137 #ifdef SQLITE_RTREE_INT_ONLY
13138 "RTREE_INT_ONLY",
13139 #endif
13140 #ifdef SQLITE_SECURE_DELETE
13141 "SECURE_DELETE",
13142 #endif
13143 #ifdef SQLITE_SMALL_STACK
13144 "SMALL_STACK",
13145 #endif
13146 #ifdef SQLITE_SOUNDEX
13147 "SOUNDEX",
13148 #endif
13149 #ifdef SQLITE_TCL
13150 "TCL",
13151 #endif
13152 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
13153 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13154 #endif
13155 #ifdef SQLITE_TEST
13156 "TEST",
13157 #endif
13158 #if defined(SQLITE_THREADSAFE)
13159 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13160 #endif
13161 #ifdef SQLITE_USE_ALLOCA
13162 "USE_ALLOCA",
13163 #endif
13164 #ifdef SQLITE_ZERO_MALLOC
13165 "ZERO_MALLOC"
13166 #endif
13170 ** Given the name of a compile-time option, return true if that option
13171 ** was used and false if not.
13173 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13174 ** is not required for a match.
13176 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13177 int i, n;
13178 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
13179 n = sqlite3Strlen30(zOptName);
13181 /* Since ArraySize(azCompileOpt) is normally in single digits, a
13182 ** linear search is adequate. No need for a binary search. */
13183 for(i=0; i<ArraySize(azCompileOpt); i++){
13184 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
13185 && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
13187 return 1;
13190 return 0;
13194 ** Return the N-th compile-time option string. If N is out of range,
13195 ** return a NULL pointer.
13197 SQLITE_API const char *sqlite3_compileoption_get(int N){
13198 if( N>=0 && N<ArraySize(azCompileOpt) ){
13199 return azCompileOpt[N];
13201 return 0;
13204 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
13206 /************** End of ctime.c ***********************************************/
13207 /************** Begin file status.c ******************************************/
13209 ** 2008 June 18
13211 ** The author disclaims copyright to this source code. In place of
13212 ** a legal notice, here is a blessing:
13214 ** May you do good and not evil.
13215 ** May you find forgiveness for yourself and forgive others.
13216 ** May you share freely, never taking more than you give.
13218 *************************************************************************
13220 ** This module implements the sqlite3_status() interface and related
13221 ** functionality.
13223 /************** Include vdbeInt.h in the middle of status.c ******************/
13224 /************** Begin file vdbeInt.h *****************************************/
13226 ** 2003 September 6
13228 ** The author disclaims copyright to this source code. In place of
13229 ** a legal notice, here is a blessing:
13231 ** May you do good and not evil.
13232 ** May you find forgiveness for yourself and forgive others.
13233 ** May you share freely, never taking more than you give.
13235 *************************************************************************
13236 ** This is the header file for information that is private to the
13237 ** VDBE. This information used to all be at the top of the single
13238 ** source code file "vdbe.c". When that file became too big (over
13239 ** 6000 lines long) it was split up into several smaller files and
13240 ** this header information was factored out.
13242 #ifndef _VDBEINT_H_
13243 #define _VDBEINT_H_
13246 ** The maximum number of times that a statement will try to reparse
13247 ** itself before giving up and returning SQLITE_SCHEMA.
13249 #ifndef SQLITE_MAX_SCHEMA_RETRY
13250 # define SQLITE_MAX_SCHEMA_RETRY 50
13251 #endif
13254 ** SQL is translated into a sequence of instructions to be
13255 ** executed by a virtual machine. Each instruction is an instance
13256 ** of the following structure.
13258 typedef struct VdbeOp Op;
13261 ** Boolean values
13263 typedef unsigned char Bool;
13265 /* Opaque type used by code in vdbesort.c */
13266 typedef struct VdbeSorter VdbeSorter;
13268 /* Opaque type used by the explainer */
13269 typedef struct Explain Explain;
13271 /* Elements of the linked list at Vdbe.pAuxData */
13272 typedef struct AuxData AuxData;
13275 ** A cursor is a pointer into a single BTree within a database file.
13276 ** The cursor can seek to a BTree entry with a particular key, or
13277 ** loop over all entries of the Btree. You can also insert new BTree
13278 ** entries or retrieve the key or data from the entry that the cursor
13279 ** is currently pointing to.
13281 ** Every cursor that the virtual machine has open is represented by an
13282 ** instance of the following structure.
13284 struct VdbeCursor {
13285 BtCursor *pCursor; /* The cursor structure of the backend */
13286 Btree *pBt; /* Separate file holding temporary table */
13287 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
13288 int iDb; /* Index of cursor database in db->aDb[] (or -1) */
13289 int pseudoTableReg; /* Register holding pseudotable content. */
13290 int nField; /* Number of fields in the header */
13291 Bool zeroed; /* True if zeroed out and ready for reuse */
13292 Bool rowidIsValid; /* True if lastRowid is valid */
13293 Bool atFirst; /* True if pointing to first entry */
13294 Bool useRandomRowid; /* Generate new record numbers semi-randomly */
13295 Bool nullRow; /* True if pointing to a row with no data */
13296 Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
13297 Bool isTable; /* True if a table requiring integer keys */
13298 Bool isIndex; /* True if an index containing keys only - no data */
13299 Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
13300 Bool isSorter; /* True if a new-style sorter */
13301 Bool multiPseudo; /* Multi-register pseudo-cursor */
13302 sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
13303 const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
13304 i64 seqCount; /* Sequence counter */
13305 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
13306 i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
13307 VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
13309 /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
13310 ** OP_IsUnique opcode on this cursor. */
13311 int seekResult;
13313 /* Cached information about the header for the data record that the
13314 ** cursor is currently pointing to. Only valid if cacheStatus matches
13315 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
13316 ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13317 ** the cache is out of date.
13319 ** aRow might point to (ephemeral) data for the current row, or it might
13320 ** be NULL.
13322 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
13323 int payloadSize; /* Total number of bytes in the record */
13324 u32 *aType; /* Type values for all entries in the record */
13325 u32 *aOffset; /* Cached offsets to the start of each columns data */
13326 u8 *aRow; /* Data for the current row, if all on one page */
13328 typedef struct VdbeCursor VdbeCursor;
13331 ** When a sub-program is executed (OP_Program), a structure of this type
13332 ** is allocated to store the current value of the program counter, as
13333 ** well as the current memory cell array and various other frame specific
13334 ** values stored in the Vdbe struct. When the sub-program is finished,
13335 ** these values are copied back to the Vdbe from the VdbeFrame structure,
13336 ** restoring the state of the VM to as it was before the sub-program
13337 ** began executing.
13339 ** The memory for a VdbeFrame object is allocated and managed by a memory
13340 ** cell in the parent (calling) frame. When the memory cell is deleted or
13341 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13342 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13343 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13344 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
13345 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13346 ** child frame are released.
13348 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13349 ** set to NULL if the currently executing frame is the main program.
13351 typedef struct VdbeFrame VdbeFrame;
13352 struct VdbeFrame {
13353 Vdbe *v; /* VM this frame belongs to */
13354 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
13355 Op *aOp; /* Program instructions for parent frame */
13356 Mem *aMem; /* Array of memory cells for parent frame */
13357 u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
13358 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
13359 void *token; /* Copy of SubProgram.token */
13360 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
13361 int nCursor; /* Number of entries in apCsr */
13362 int pc; /* Program Counter in parent (calling) frame */
13363 int nOp; /* Size of aOp array */
13364 int nMem; /* Number of entries in aMem */
13365 int nOnceFlag; /* Number of entries in aOnceFlag */
13366 int nChildMem; /* Number of memory cells for child frame */
13367 int nChildCsr; /* Number of cursors for child frame */
13368 int nChange; /* Statement changes (Vdbe.nChanges) */
13371 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13374 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13376 #define CACHE_STALE 0
13379 ** Internally, the vdbe manipulates nearly all SQL values as Mem
13380 ** structures. Each Mem struct may cache multiple representations (string,
13381 ** integer etc.) of the same value.
13383 struct Mem {
13384 sqlite3 *db; /* The associated database connection */
13385 char *z; /* String or BLOB value */
13386 double r; /* Real value */
13387 union {
13388 i64 i; /* Integer value used when MEM_Int is set in flags */
13389 int nZero; /* Used when bit MEM_Zero is set in flags */
13390 FuncDef *pDef; /* Used only when flags==MEM_Agg */
13391 RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
13392 VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
13393 } u;
13394 int n; /* Number of characters in string value, excluding '\0' */
13395 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13396 u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
13397 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13398 #ifdef SQLITE_DEBUG
13399 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
13400 void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
13401 #endif
13402 void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
13403 char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
13406 /* One or more of the following flags are set to indicate the validOK
13407 ** representations of the value stored in the Mem struct.
13409 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
13410 ** No other flags may be set in this case.
13412 ** If the MEM_Str flag is set then Mem.z points at a string representation.
13413 ** Usually this is encoded in the same unicode encoding as the main
13414 ** database (see below for exceptions). If the MEM_Term flag is also
13415 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
13416 ** flags may coexist with the MEM_Str flag.
13418 #define MEM_Null 0x0001 /* Value is NULL */
13419 #define MEM_Str 0x0002 /* Value is a string */
13420 #define MEM_Int 0x0004 /* Value is an integer */
13421 #define MEM_Real 0x0008 /* Value is a real number */
13422 #define MEM_Blob 0x0010 /* Value is a BLOB */
13423 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
13424 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
13425 #define MEM_Invalid 0x0080 /* Value is undefined */
13426 #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
13427 #define MEM_TypeMask 0x01ff /* Mask of type bits */
13430 /* Whenever Mem contains a valid string or blob representation, one of
13431 ** the following flags must be set to determine the memory management
13432 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
13433 ** string is \000 or \u0000 terminated
13435 #define MEM_Term 0x0200 /* String rep is nul terminated */
13436 #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
13437 #define MEM_Static 0x0800 /* Mem.z points to a static string */
13438 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
13439 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
13440 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
13441 #ifdef SQLITE_OMIT_INCRBLOB
13442 #undef MEM_Zero
13443 #define MEM_Zero 0x0000
13444 #endif
13447 ** Clear any existing type flags from a Mem and replace them with f
13449 #define MemSetTypeFlag(p, f) \
13450 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13453 ** Return true if a memory cell is not marked as invalid. This macro
13454 ** is for use inside assert() statements only.
13456 #ifdef SQLITE_DEBUG
13457 #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
13458 #endif
13461 ** Each auxilliary data pointer stored by a user defined function
13462 ** implementation calling sqlite3_set_auxdata() is stored in an instance
13463 ** of this structure. All such structures associated with a single VM
13464 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
13465 ** when the VM is halted (if not before).
13467 struct AuxData {
13468 int iOp; /* Instruction number of OP_Function opcode */
13469 int iArg; /* Index of function argument. */
13470 void *pAux; /* Aux data pointer */
13471 void (*xDelete)(void *); /* Destructor for the aux data */
13472 AuxData *pNext; /* Next element in list */
13476 ** The "context" argument for a installable function. A pointer to an
13477 ** instance of this structure is the first argument to the routines used
13478 ** implement the SQL functions.
13480 ** There is a typedef for this structure in sqlite.h. So all routines,
13481 ** even the public interface to SQLite, can use a pointer to this structure.
13482 ** But this file is the only place where the internal details of this
13483 ** structure are known.
13485 ** This structure is defined inside of vdbeInt.h because it uses substructures
13486 ** (Mem) which are only defined there.
13488 struct sqlite3_context {
13489 FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
13490 Mem s; /* The return value is stored here */
13491 Mem *pMem; /* Memory cell used to store aggregate context */
13492 CollSeq *pColl; /* Collating sequence */
13493 Vdbe *pVdbe; /* The VM that owns this context */
13494 int iOp; /* Instruction number of OP_Function */
13495 int isError; /* Error code returned by the function. */
13496 u8 skipFlag; /* Skip skip accumulator loading if true */
13497 u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
13501 ** An Explain object accumulates indented output which is helpful
13502 ** in describing recursive data structures.
13504 struct Explain {
13505 Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
13506 StrAccum str; /* The string being accumulated */
13507 int nIndent; /* Number of elements in aIndent */
13508 u16 aIndent[100]; /* Levels of indentation */
13509 char zBase[100]; /* Initial space */
13512 /* A bitfield type for use inside of structures. Always follow with :N where
13513 ** N is the number of bits.
13515 typedef unsigned bft; /* Bit Field Type */
13518 ** An instance of the virtual machine. This structure contains the complete
13519 ** state of the virtual machine.
13521 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13522 ** is really a pointer to an instance of this structure.
13524 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13525 ** any virtual table method invocations made by the vdbe program. It is
13526 ** set to 2 for xDestroy method calls and 1 for all other methods. This
13527 ** variable is used for two purposes: to allow xDestroy methods to execute
13528 ** "DROP TABLE" statements and to prevent some nasty side effects of
13529 ** malloc failure when SQLite is invoked recursively by a virtual table
13530 ** method function.
13532 struct Vdbe {
13533 sqlite3 *db; /* The database connection that owns this statement */
13534 Op *aOp; /* Space to hold the virtual machine's program */
13535 Mem *aMem; /* The memory locations */
13536 Mem **apArg; /* Arguments to currently executing user function */
13537 Mem *aColName; /* Column names to return */
13538 Mem *pResultSet; /* Pointer to an array of results */
13539 int nMem; /* Number of memory locations currently allocated */
13540 int nOp; /* Number of instructions in the program */
13541 int nOpAlloc; /* Number of slots allocated for aOp[] */
13542 int nLabel; /* Number of labels used */
13543 int *aLabel; /* Space to hold the labels */
13544 u16 nResColumn; /* Number of columns in one row of the result set */
13545 int nCursor; /* Number of slots in apCsr[] */
13546 u32 magic; /* Magic number for sanity checking */
13547 char *zErrMsg; /* Error message written here */
13548 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
13549 VdbeCursor **apCsr; /* One element of this array for each open cursor */
13550 Mem *aVar; /* Values for the OP_Variable opcode. */
13551 char **azVar; /* Name of variables */
13552 ynVar nVar; /* Number of entries in aVar[] */
13553 ynVar nzVar; /* Number of entries in azVar[] */
13554 u32 cacheCtr; /* VdbeCursor row cache generation counter */
13555 int pc; /* The program counter */
13556 int rc; /* Value to return */
13557 u8 errorAction; /* Recovery action to do in case of an error */
13558 u8 minWriteFileFormat; /* Minimum file format for writable database files */
13559 bft explain:2; /* True if EXPLAIN present on SQL command */
13560 bft inVtabMethod:2; /* See comments above */
13561 bft changeCntOn:1; /* True to update the change-counter */
13562 bft expired:1; /* True if the VM needs to be recompiled */
13563 bft runOnlyOnce:1; /* Automatically expire on reset */
13564 bft usesStmtJournal:1; /* True if uses a statement journal */
13565 bft readOnly:1; /* True for statements that do not write */
13566 bft bIsReader:1; /* True for statements that read */
13567 bft isPrepareV2:1; /* True if prepared with prepare_v2() */
13568 bft doingRerun:1; /* True if rerunning after an auto-reprepare */
13569 int nChange; /* Number of db changes made since last reset */
13570 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
13571 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
13572 int iStatement; /* Statement number (or 0 if has not opened stmt) */
13573 u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
13574 #ifndef SQLITE_OMIT_TRACE
13575 i64 startTime; /* Time when query started - used for profiling */
13576 #endif
13577 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
13578 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
13579 i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
13580 char *zSql; /* Text of the SQL statement that generated this */
13581 void *pFree; /* Free this when deleting the vdbe */
13582 #ifdef SQLITE_DEBUG
13583 FILE *trace; /* Write an execution trace here, if not NULL */
13584 #endif
13585 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
13586 Explain *pExplain; /* The explainer */
13587 char *zExplain; /* Explanation of data structures */
13588 #endif
13589 VdbeFrame *pFrame; /* Parent frame */
13590 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
13591 int nFrame; /* Number of frames in pFrame list */
13592 u32 expmask; /* Binding to these vars invalidates VM */
13593 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
13594 int nOnceFlag; /* Size of array aOnceFlag[] */
13595 u8 *aOnceFlag; /* Flags for OP_Once */
13596 AuxData *pAuxData; /* Linked list of auxdata allocations */
13600 ** The following are allowed values for Vdbe.magic
13602 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
13603 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
13604 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
13605 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
13608 ** Function prototypes
13610 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13611 void sqliteVdbePopStack(Vdbe*,int);
13612 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13613 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13614 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13615 #endif
13616 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13617 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13618 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13619 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13620 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
13622 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13623 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13624 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13625 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13626 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13627 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13628 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13629 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13630 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13631 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13632 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13633 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13634 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13635 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13636 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13637 #ifdef SQLITE_OMIT_FLOATING_POINT
13638 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13639 #else
13640 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
13641 #endif
13642 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13643 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13644 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13645 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13646 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13647 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13648 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13649 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13650 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13651 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13652 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13653 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
13654 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13655 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13656 #define VdbeMemRelease(X) \
13657 if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13658 sqlite3VdbeMemReleaseExternal(X);
13659 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13660 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13661 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13662 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13663 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13664 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13665 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13666 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13668 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13669 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13670 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
13671 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
13672 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
13673 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
13674 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
13676 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13677 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
13678 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
13679 #else
13680 # define sqlite3VdbeEnter(X)
13681 # define sqlite3VdbeLeave(X)
13682 #endif
13684 #ifdef SQLITE_DEBUG
13685 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13686 #endif
13688 #ifndef SQLITE_OMIT_FOREIGN_KEY
13689 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13690 #else
13691 # define sqlite3VdbeCheckFk(p,i) 0
13692 #endif
13694 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13695 #ifdef SQLITE_DEBUG
13696 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
13697 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13698 #endif
13699 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13701 #ifndef SQLITE_OMIT_INCRBLOB
13702 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
13703 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13704 #else
13705 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13706 #define ExpandBlob(P) SQLITE_OK
13707 #endif
13709 #endif /* !defined(_VDBEINT_H_) */
13711 /************** End of vdbeInt.h *********************************************/
13712 /************** Continuing where we left off in status.c *********************/
13715 ** Variables in which to record status information.
13717 typedef struct sqlite3StatType sqlite3StatType;
13718 static SQLITE_WSD struct sqlite3StatType {
13719 int nowValue[10]; /* Current value */
13720 int mxValue[10]; /* Maximum value */
13721 } sqlite3Stat = { {0,}, {0,} };
13724 /* The "wsdStat" macro will resolve to the status information
13725 ** state vector. If writable static data is unsupported on the target,
13726 ** we have to locate the state vector at run-time. In the more common
13727 ** case where writable static data is supported, wsdStat can refer directly
13728 ** to the "sqlite3Stat" state vector declared above.
13730 #ifdef SQLITE_OMIT_WSD
13731 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13732 # define wsdStat x[0]
13733 #else
13734 # define wsdStatInit
13735 # define wsdStat sqlite3Stat
13736 #endif
13739 ** Return the current value of a status parameter.
13741 SQLITE_PRIVATE int sqlite3StatusValue(int op){
13742 wsdStatInit;
13743 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13744 return wsdStat.nowValue[op];
13748 ** Add N to the value of a status record. It is assumed that the
13749 ** caller holds appropriate locks.
13751 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13752 wsdStatInit;
13753 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13754 wsdStat.nowValue[op] += N;
13755 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13756 wsdStat.mxValue[op] = wsdStat.nowValue[op];
13761 ** Set the value of a status to X.
13763 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13764 wsdStatInit;
13765 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13766 wsdStat.nowValue[op] = X;
13767 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13768 wsdStat.mxValue[op] = wsdStat.nowValue[op];
13773 ** Query status information.
13775 ** This implementation assumes that reading or writing an aligned
13776 ** 32-bit integer is an atomic operation. If that assumption is not true,
13777 ** then this routine is not threadsafe.
13779 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13780 wsdStatInit;
13781 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13782 return SQLITE_MISUSE_BKPT;
13784 *pCurrent = wsdStat.nowValue[op];
13785 *pHighwater = wsdStat.mxValue[op];
13786 if( resetFlag ){
13787 wsdStat.mxValue[op] = wsdStat.nowValue[op];
13789 return SQLITE_OK;
13793 ** Query status information for a single database connection
13795 SQLITE_API int sqlite3_db_status(
13796 sqlite3 *db, /* The database connection whose status is desired */
13797 int op, /* Status verb */
13798 int *pCurrent, /* Write current value here */
13799 int *pHighwater, /* Write high-water mark here */
13800 int resetFlag /* Reset high-water mark if true */
13802 int rc = SQLITE_OK; /* Return code */
13803 sqlite3_mutex_enter(db->mutex);
13804 switch( op ){
13805 case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13806 *pCurrent = db->lookaside.nOut;
13807 *pHighwater = db->lookaside.mxOut;
13808 if( resetFlag ){
13809 db->lookaside.mxOut = db->lookaside.nOut;
13811 break;
13814 case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13815 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13816 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13817 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13818 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13819 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13820 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13821 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13822 *pCurrent = 0;
13823 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13824 if( resetFlag ){
13825 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13827 break;
13831 ** Return an approximation for the amount of memory currently used
13832 ** by all pagers associated with the given database connection. The
13833 ** highwater mark is meaningless and is returned as zero.
13835 case SQLITE_DBSTATUS_CACHE_USED: {
13836 int totalUsed = 0;
13837 int i;
13838 sqlite3BtreeEnterAll(db);
13839 for(i=0; i<db->nDb; i++){
13840 Btree *pBt = db->aDb[i].pBt;
13841 if( pBt ){
13842 Pager *pPager = sqlite3BtreePager(pBt);
13843 totalUsed += sqlite3PagerMemUsed(pPager);
13846 sqlite3BtreeLeaveAll(db);
13847 *pCurrent = totalUsed;
13848 *pHighwater = 0;
13849 break;
13853 ** *pCurrent gets an accurate estimate of the amount of memory used
13854 ** to store the schema for all databases (main, temp, and any ATTACHed
13855 ** databases. *pHighwater is set to zero.
13857 case SQLITE_DBSTATUS_SCHEMA_USED: {
13858 int i; /* Used to iterate through schemas */
13859 int nByte = 0; /* Used to accumulate return value */
13861 sqlite3BtreeEnterAll(db);
13862 db->pnBytesFreed = &nByte;
13863 for(i=0; i<db->nDb; i++){
13864 Schema *pSchema = db->aDb[i].pSchema;
13865 if( ALWAYS(pSchema!=0) ){
13866 HashElem *p;
13868 nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13869 pSchema->tblHash.count
13870 + pSchema->trigHash.count
13871 + pSchema->idxHash.count
13872 + pSchema->fkeyHash.count
13874 nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13875 nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13876 nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13877 nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13879 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13880 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13882 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13883 sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13887 db->pnBytesFreed = 0;
13888 sqlite3BtreeLeaveAll(db);
13890 *pHighwater = 0;
13891 *pCurrent = nByte;
13892 break;
13896 ** *pCurrent gets an accurate estimate of the amount of memory used
13897 ** to store all prepared statements.
13898 ** *pHighwater is set to zero.
13900 case SQLITE_DBSTATUS_STMT_USED: {
13901 struct Vdbe *pVdbe; /* Used to iterate through VMs */
13902 int nByte = 0; /* Used to accumulate return value */
13904 db->pnBytesFreed = &nByte;
13905 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13906 sqlite3VdbeClearObject(db, pVdbe);
13907 sqlite3DbFree(db, pVdbe);
13909 db->pnBytesFreed = 0;
13911 *pHighwater = 0;
13912 *pCurrent = nByte;
13914 break;
13918 ** Set *pCurrent to the total cache hits or misses encountered by all
13919 ** pagers the database handle is connected to. *pHighwater is always set
13920 ** to zero.
13922 case SQLITE_DBSTATUS_CACHE_HIT:
13923 case SQLITE_DBSTATUS_CACHE_MISS:
13924 case SQLITE_DBSTATUS_CACHE_WRITE:{
13925 int i;
13926 int nRet = 0;
13927 assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13928 assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
13930 for(i=0; i<db->nDb; i++){
13931 if( db->aDb[i].pBt ){
13932 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13933 sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13936 *pHighwater = 0;
13937 *pCurrent = nRet;
13938 break;
13941 /* Set *pCurrent to non-zero if there are unresolved deferred foreign
13942 ** key constraints. Set *pCurrent to zero if all foreign key constraints
13943 ** have been satisfied. The *pHighwater is always set to zero.
13945 case SQLITE_DBSTATUS_DEFERRED_FKS: {
13946 *pHighwater = 0;
13947 *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
13948 break;
13951 default: {
13952 rc = SQLITE_ERROR;
13955 sqlite3_mutex_leave(db->mutex);
13956 return rc;
13959 /************** End of status.c **********************************************/
13960 /************** Begin file date.c ********************************************/
13962 ** 2003 October 31
13964 ** The author disclaims copyright to this source code. In place of
13965 ** a legal notice, here is a blessing:
13967 ** May you do good and not evil.
13968 ** May you find forgiveness for yourself and forgive others.
13969 ** May you share freely, never taking more than you give.
13971 *************************************************************************
13972 ** This file contains the C functions that implement date and time
13973 ** functions for SQLite.
13975 ** There is only one exported symbol in this file - the function
13976 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13977 ** All other code has file scope.
13979 ** SQLite processes all times and dates as Julian Day numbers. The
13980 ** dates and times are stored as the number of days since noon
13981 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13982 ** calendar system.
13984 ** 1970-01-01 00:00:00 is JD 2440587.5
13985 ** 2000-01-01 00:00:00 is JD 2451544.5
13987 ** This implemention requires years to be expressed as a 4-digit number
13988 ** which means that only dates between 0000-01-01 and 9999-12-31 can
13989 ** be represented, even though julian day numbers allow a much wider
13990 ** range of dates.
13992 ** The Gregorian calendar system is used for all dates and times,
13993 ** even those that predate the Gregorian calendar. Historians usually
13994 ** use the Julian calendar for dates prior to 1582-10-15 and for some
13995 ** dates afterwards, depending on locale. Beware of this difference.
13997 ** The conversion algorithms are implemented based on descriptions
13998 ** in the following text:
14000 ** Jean Meeus
14001 ** Astronomical Algorithms, 2nd Edition, 1998
14002 ** ISBM 0-943396-61-1
14003 ** Willmann-Bell, Inc
14004 ** Richmond, Virginia (USA)
14006 /* #include <stdlib.h> */
14007 /* #include <assert.h> */
14008 #include <time.h>
14010 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14014 ** A structure for holding a single date and time.
14016 typedef struct DateTime DateTime;
14017 struct DateTime {
14018 sqlite3_int64 iJD; /* The julian day number times 86400000 */
14019 int Y, M, D; /* Year, month, and day */
14020 int h, m; /* Hour and minutes */
14021 int tz; /* Timezone offset in minutes */
14022 double s; /* Seconds */
14023 char validYMD; /* True (1) if Y,M,D are valid */
14024 char validHMS; /* True (1) if h,m,s are valid */
14025 char validJD; /* True (1) if iJD is valid */
14026 char validTZ; /* True (1) if tz is valid */
14031 ** Convert zDate into one or more integers. Additional arguments
14032 ** come in groups of 5 as follows:
14034 ** N number of digits in the integer
14035 ** min minimum allowed value of the integer
14036 ** max maximum allowed value of the integer
14037 ** nextC first character after the integer
14038 ** pVal where to write the integers value.
14040 ** Conversions continue until one with nextC==0 is encountered.
14041 ** The function returns the number of successful conversions.
14043 static int getDigits(const char *zDate, ...){
14044 va_list ap;
14045 int val;
14046 int N;
14047 int min;
14048 int max;
14049 int nextC;
14050 int *pVal;
14051 int cnt = 0;
14052 va_start(ap, zDate);
14054 N = va_arg(ap, int);
14055 min = va_arg(ap, int);
14056 max = va_arg(ap, int);
14057 nextC = va_arg(ap, int);
14058 pVal = va_arg(ap, int*);
14059 val = 0;
14060 while( N-- ){
14061 if( !sqlite3Isdigit(*zDate) ){
14062 goto end_getDigits;
14064 val = val*10 + *zDate - '0';
14065 zDate++;
14067 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
14068 goto end_getDigits;
14070 *pVal = val;
14071 zDate++;
14072 cnt++;
14073 }while( nextC );
14074 end_getDigits:
14075 va_end(ap);
14076 return cnt;
14080 ** Parse a timezone extension on the end of a date-time.
14081 ** The extension is of the form:
14083 ** (+/-)HH:MM
14085 ** Or the "zulu" notation:
14087 ** Z
14089 ** If the parse is successful, write the number of minutes
14090 ** of change in p->tz and return 0. If a parser error occurs,
14091 ** return non-zero.
14093 ** A missing specifier is not considered an error.
14095 static int parseTimezone(const char *zDate, DateTime *p){
14096 int sgn = 0;
14097 int nHr, nMn;
14098 int c;
14099 while( sqlite3Isspace(*zDate) ){ zDate++; }
14100 p->tz = 0;
14101 c = *zDate;
14102 if( c=='-' ){
14103 sgn = -1;
14104 }else if( c=='+' ){
14105 sgn = +1;
14106 }else if( c=='Z' || c=='z' ){
14107 zDate++;
14108 goto zulu_time;
14109 }else{
14110 return c!=0;
14112 zDate++;
14113 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
14114 return 1;
14116 zDate += 5;
14117 p->tz = sgn*(nMn + nHr*60);
14118 zulu_time:
14119 while( sqlite3Isspace(*zDate) ){ zDate++; }
14120 return *zDate!=0;
14124 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
14125 ** The HH, MM, and SS must each be exactly 2 digits. The
14126 ** fractional seconds FFFF can be one or more digits.
14128 ** Return 1 if there is a parsing error and 0 on success.
14130 static int parseHhMmSs(const char *zDate, DateTime *p){
14131 int h, m, s;
14132 double ms = 0.0;
14133 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
14134 return 1;
14136 zDate += 5;
14137 if( *zDate==':' ){
14138 zDate++;
14139 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
14140 return 1;
14142 zDate += 2;
14143 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
14144 double rScale = 1.0;
14145 zDate++;
14146 while( sqlite3Isdigit(*zDate) ){
14147 ms = ms*10.0 + *zDate - '0';
14148 rScale *= 10.0;
14149 zDate++;
14151 ms /= rScale;
14153 }else{
14154 s = 0;
14156 p->validJD = 0;
14157 p->validHMS = 1;
14158 p->h = h;
14159 p->m = m;
14160 p->s = s + ms;
14161 if( parseTimezone(zDate, p) ) return 1;
14162 p->validTZ = (p->tz!=0)?1:0;
14163 return 0;
14167 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
14168 ** that the YYYY-MM-DD is according to the Gregorian calendar.
14170 ** Reference: Meeus page 61
14172 static void computeJD(DateTime *p){
14173 int Y, M, D, A, B, X1, X2;
14175 if( p->validJD ) return;
14176 if( p->validYMD ){
14177 Y = p->Y;
14178 M = p->M;
14179 D = p->D;
14180 }else{
14181 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
14182 M = 1;
14183 D = 1;
14185 if( M<=2 ){
14186 Y--;
14187 M += 12;
14189 A = Y/100;
14190 B = 2 - A + (A/4);
14191 X1 = 36525*(Y+4716)/100;
14192 X2 = 306001*(M+1)/10000;
14193 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
14194 p->validJD = 1;
14195 if( p->validHMS ){
14196 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
14197 if( p->validTZ ){
14198 p->iJD -= p->tz*60000;
14199 p->validYMD = 0;
14200 p->validHMS = 0;
14201 p->validTZ = 0;
14207 ** Parse dates of the form
14209 ** YYYY-MM-DD HH:MM:SS.FFF
14210 ** YYYY-MM-DD HH:MM:SS
14211 ** YYYY-MM-DD HH:MM
14212 ** YYYY-MM-DD
14214 ** Write the result into the DateTime structure and return 0
14215 ** on success and 1 if the input string is not a well-formed
14216 ** date.
14218 static int parseYyyyMmDd(const char *zDate, DateTime *p){
14219 int Y, M, D, neg;
14221 if( zDate[0]=='-' ){
14222 zDate++;
14223 neg = 1;
14224 }else{
14225 neg = 0;
14227 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
14228 return 1;
14230 zDate += 10;
14231 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
14232 if( parseHhMmSs(zDate, p)==0 ){
14233 /* We got the time */
14234 }else if( *zDate==0 ){
14235 p->validHMS = 0;
14236 }else{
14237 return 1;
14239 p->validJD = 0;
14240 p->validYMD = 1;
14241 p->Y = neg ? -Y : Y;
14242 p->M = M;
14243 p->D = D;
14244 if( p->validTZ ){
14245 computeJD(p);
14247 return 0;
14251 ** Set the time to the current time reported by the VFS.
14253 ** Return the number of errors.
14255 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
14256 sqlite3 *db = sqlite3_context_db_handle(context);
14257 if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
14258 p->validJD = 1;
14259 return 0;
14260 }else{
14261 return 1;
14266 ** Attempt to parse the given string into a Julian Day Number. Return
14267 ** the number of errors.
14269 ** The following are acceptable forms for the input string:
14271 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
14272 ** DDDD.DD
14273 ** now
14275 ** In the first form, the +/-HH:MM is always optional. The fractional
14276 ** seconds extension (the ".FFF") is optional. The seconds portion
14277 ** (":SS.FFF") is option. The year and date can be omitted as long
14278 ** as there is a time string. The time string can be omitted as long
14279 ** as there is a year and date.
14281 static int parseDateOrTime(
14282 sqlite3_context *context,
14283 const char *zDate,
14284 DateTime *p
14286 double r;
14287 if( parseYyyyMmDd(zDate,p)==0 ){
14288 return 0;
14289 }else if( parseHhMmSs(zDate, p)==0 ){
14290 return 0;
14291 }else if( sqlite3StrICmp(zDate,"now")==0){
14292 return setDateTimeToCurrent(context, p);
14293 }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
14294 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
14295 p->validJD = 1;
14296 return 0;
14298 return 1;
14302 ** Compute the Year, Month, and Day from the julian day number.
14304 static void computeYMD(DateTime *p){
14305 int Z, A, B, C, D, E, X1;
14306 if( p->validYMD ) return;
14307 if( !p->validJD ){
14308 p->Y = 2000;
14309 p->M = 1;
14310 p->D = 1;
14311 }else{
14312 Z = (int)((p->iJD + 43200000)/86400000);
14313 A = (int)((Z - 1867216.25)/36524.25);
14314 A = Z + 1 + A - (A/4);
14315 B = A + 1524;
14316 C = (int)((B - 122.1)/365.25);
14317 D = (36525*C)/100;
14318 E = (int)((B-D)/30.6001);
14319 X1 = (int)(30.6001*E);
14320 p->D = B - D - X1;
14321 p->M = E<14 ? E-1 : E-13;
14322 p->Y = p->M>2 ? C - 4716 : C - 4715;
14324 p->validYMD = 1;
14328 ** Compute the Hour, Minute, and Seconds from the julian day number.
14330 static void computeHMS(DateTime *p){
14331 int s;
14332 if( p->validHMS ) return;
14333 computeJD(p);
14334 s = (int)((p->iJD + 43200000) % 86400000);
14335 p->s = s/1000.0;
14336 s = (int)p->s;
14337 p->s -= s;
14338 p->h = s/3600;
14339 s -= p->h*3600;
14340 p->m = s/60;
14341 p->s += s - p->m*60;
14342 p->validHMS = 1;
14346 ** Compute both YMD and HMS
14348 static void computeYMD_HMS(DateTime *p){
14349 computeYMD(p);
14350 computeHMS(p);
14354 ** Clear the YMD and HMS and the TZ
14356 static void clearYMD_HMS_TZ(DateTime *p){
14357 p->validYMD = 0;
14358 p->validHMS = 0;
14359 p->validTZ = 0;
14363 ** On recent Windows platforms, the localtime_s() function is available
14364 ** as part of the "Secure CRT". It is essentially equivalent to
14365 ** localtime_r() available under most POSIX platforms, except that the
14366 ** order of the parameters is reversed.
14368 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14370 ** If the user has not indicated to use localtime_r() or localtime_s()
14371 ** already, check for an MSVC build environment that provides
14372 ** localtime_s().
14374 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14375 defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14376 #define HAVE_LOCALTIME_S 1
14377 #endif
14379 #ifndef SQLITE_OMIT_LOCALTIME
14381 ** The following routine implements the rough equivalent of localtime_r()
14382 ** using whatever operating-system specific localtime facility that
14383 ** is available. This routine returns 0 on success and
14384 ** non-zero on any kind of error.
14386 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14387 ** routine will always fail.
14389 static int osLocaltime(time_t *t, struct tm *pTm){
14390 int rc;
14391 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14392 && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14393 struct tm *pX;
14394 #if SQLITE_THREADSAFE>0
14395 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14396 #endif
14397 sqlite3_mutex_enter(mutex);
14398 pX = localtime(t);
14399 #ifndef SQLITE_OMIT_BUILTIN_TEST
14400 if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14401 #endif
14402 if( pX ) *pTm = *pX;
14403 sqlite3_mutex_leave(mutex);
14404 rc = pX==0;
14405 #else
14406 #ifndef SQLITE_OMIT_BUILTIN_TEST
14407 if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14408 #endif
14409 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14410 rc = localtime_r(t, pTm)==0;
14411 #else
14412 rc = localtime_s(pTm, t);
14413 #endif /* HAVE_LOCALTIME_R */
14414 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
14415 return rc;
14417 #endif /* SQLITE_OMIT_LOCALTIME */
14420 #ifndef SQLITE_OMIT_LOCALTIME
14422 ** Compute the difference (in milliseconds) between localtime and UTC
14423 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14424 ** return this value and set *pRc to SQLITE_OK.
14426 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14427 ** is undefined in this case.
14429 static sqlite3_int64 localtimeOffset(
14430 DateTime *p, /* Date at which to calculate offset */
14431 sqlite3_context *pCtx, /* Write error here if one occurs */
14432 int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
14434 DateTime x, y;
14435 time_t t;
14436 struct tm sLocal;
14438 /* Initialize the contents of sLocal to avoid a compiler warning. */
14439 memset(&sLocal, 0, sizeof(sLocal));
14441 x = *p;
14442 computeYMD_HMS(&x);
14443 if( x.Y<1971 || x.Y>=2038 ){
14444 x.Y = 2000;
14445 x.M = 1;
14446 x.D = 1;
14447 x.h = 0;
14448 x.m = 0;
14449 x.s = 0.0;
14450 } else {
14451 int s = (int)(x.s + 0.5);
14452 x.s = s;
14454 x.tz = 0;
14455 x.validJD = 0;
14456 computeJD(&x);
14457 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14458 if( osLocaltime(&t, &sLocal) ){
14459 sqlite3_result_error(pCtx, "local time unavailable", -1);
14460 *pRc = SQLITE_ERROR;
14461 return 0;
14463 y.Y = sLocal.tm_year + 1900;
14464 y.M = sLocal.tm_mon + 1;
14465 y.D = sLocal.tm_mday;
14466 y.h = sLocal.tm_hour;
14467 y.m = sLocal.tm_min;
14468 y.s = sLocal.tm_sec;
14469 y.validYMD = 1;
14470 y.validHMS = 1;
14471 y.validJD = 0;
14472 y.validTZ = 0;
14473 computeJD(&y);
14474 *pRc = SQLITE_OK;
14475 return y.iJD - x.iJD;
14477 #endif /* SQLITE_OMIT_LOCALTIME */
14480 ** Process a modifier to a date-time stamp. The modifiers are
14481 ** as follows:
14483 ** NNN days
14484 ** NNN hours
14485 ** NNN minutes
14486 ** NNN.NNNN seconds
14487 ** NNN months
14488 ** NNN years
14489 ** start of month
14490 ** start of year
14491 ** start of week
14492 ** start of day
14493 ** weekday N
14494 ** unixepoch
14495 ** localtime
14496 ** utc
14498 ** Return 0 on success and 1 if there is any kind of error. If the error
14499 ** is in a system call (i.e. localtime()), then an error message is written
14500 ** to context pCtx. If the error is an unrecognized modifier, no error is
14501 ** written to pCtx.
14503 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14504 int rc = 1;
14505 int n;
14506 double r;
14507 char *z, zBuf[30];
14508 z = zBuf;
14509 for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14510 z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14512 z[n] = 0;
14513 switch( z[0] ){
14514 #ifndef SQLITE_OMIT_LOCALTIME
14515 case 'l': {
14516 /* localtime
14518 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14519 ** show local time.
14521 if( strcmp(z, "localtime")==0 ){
14522 computeJD(p);
14523 p->iJD += localtimeOffset(p, pCtx, &rc);
14524 clearYMD_HMS_TZ(p);
14526 break;
14528 #endif
14529 case 'u': {
14531 ** unixepoch
14533 ** Treat the current value of p->iJD as the number of
14534 ** seconds since 1970. Convert to a real julian day number.
14536 if( strcmp(z, "unixepoch")==0 && p->validJD ){
14537 p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14538 clearYMD_HMS_TZ(p);
14539 rc = 0;
14541 #ifndef SQLITE_OMIT_LOCALTIME
14542 else if( strcmp(z, "utc")==0 ){
14543 sqlite3_int64 c1;
14544 computeJD(p);
14545 c1 = localtimeOffset(p, pCtx, &rc);
14546 if( rc==SQLITE_OK ){
14547 p->iJD -= c1;
14548 clearYMD_HMS_TZ(p);
14549 p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14552 #endif
14553 break;
14555 case 'w': {
14557 ** weekday N
14559 ** Move the date to the same time on the next occurrence of
14560 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
14561 ** date is already on the appropriate weekday, this is a no-op.
14563 if( strncmp(z, "weekday ", 8)==0
14564 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14565 && (n=(int)r)==r && n>=0 && r<7 ){
14566 sqlite3_int64 Z;
14567 computeYMD_HMS(p);
14568 p->validTZ = 0;
14569 p->validJD = 0;
14570 computeJD(p);
14571 Z = ((p->iJD + 129600000)/86400000) % 7;
14572 if( Z>n ) Z -= 7;
14573 p->iJD += (n - Z)*86400000;
14574 clearYMD_HMS_TZ(p);
14575 rc = 0;
14577 break;
14579 case 's': {
14581 ** start of TTTTT
14583 ** Move the date backwards to the beginning of the current day,
14584 ** or month or year.
14586 if( strncmp(z, "start of ", 9)!=0 ) break;
14587 z += 9;
14588 computeYMD(p);
14589 p->validHMS = 1;
14590 p->h = p->m = 0;
14591 p->s = 0.0;
14592 p->validTZ = 0;
14593 p->validJD = 0;
14594 if( strcmp(z,"month")==0 ){
14595 p->D = 1;
14596 rc = 0;
14597 }else if( strcmp(z,"year")==0 ){
14598 computeYMD(p);
14599 p->M = 1;
14600 p->D = 1;
14601 rc = 0;
14602 }else if( strcmp(z,"day")==0 ){
14603 rc = 0;
14605 break;
14607 case '+':
14608 case '-':
14609 case '0':
14610 case '1':
14611 case '2':
14612 case '3':
14613 case '4':
14614 case '5':
14615 case '6':
14616 case '7':
14617 case '8':
14618 case '9': {
14619 double rRounder;
14620 for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14621 if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14622 rc = 1;
14623 break;
14625 if( z[n]==':' ){
14626 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14627 ** specified number of hours, minutes, seconds, and fractional seconds
14628 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
14629 ** omitted.
14631 const char *z2 = z;
14632 DateTime tx;
14633 sqlite3_int64 day;
14634 if( !sqlite3Isdigit(*z2) ) z2++;
14635 memset(&tx, 0, sizeof(tx));
14636 if( parseHhMmSs(z2, &tx) ) break;
14637 computeJD(&tx);
14638 tx.iJD -= 43200000;
14639 day = tx.iJD/86400000;
14640 tx.iJD -= day*86400000;
14641 if( z[0]=='-' ) tx.iJD = -tx.iJD;
14642 computeJD(p);
14643 clearYMD_HMS_TZ(p);
14644 p->iJD += tx.iJD;
14645 rc = 0;
14646 break;
14648 z += n;
14649 while( sqlite3Isspace(*z) ) z++;
14650 n = sqlite3Strlen30(z);
14651 if( n>10 || n<3 ) break;
14652 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14653 computeJD(p);
14654 rc = 0;
14655 rRounder = r<0 ? -0.5 : +0.5;
14656 if( n==3 && strcmp(z,"day")==0 ){
14657 p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14658 }else if( n==4 && strcmp(z,"hour")==0 ){
14659 p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14660 }else if( n==6 && strcmp(z,"minute")==0 ){
14661 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14662 }else if( n==6 && strcmp(z,"second")==0 ){
14663 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14664 }else if( n==5 && strcmp(z,"month")==0 ){
14665 int x, y;
14666 computeYMD_HMS(p);
14667 p->M += (int)r;
14668 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14669 p->Y += x;
14670 p->M -= x*12;
14671 p->validJD = 0;
14672 computeJD(p);
14673 y = (int)r;
14674 if( y!=r ){
14675 p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14677 }else if( n==4 && strcmp(z,"year")==0 ){
14678 int y = (int)r;
14679 computeYMD_HMS(p);
14680 p->Y += y;
14681 p->validJD = 0;
14682 computeJD(p);
14683 if( y!=r ){
14684 p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14686 }else{
14687 rc = 1;
14689 clearYMD_HMS_TZ(p);
14690 break;
14692 default: {
14693 break;
14696 return rc;
14700 ** Process time function arguments. argv[0] is a date-time stamp.
14701 ** argv[1] and following are modifiers. Parse them all and write
14702 ** the resulting time into the DateTime structure p. Return 0
14703 ** on success and 1 if there are any errors.
14705 ** If there are zero parameters (if even argv[0] is undefined)
14706 ** then assume a default value of "now" for argv[0].
14708 static int isDate(
14709 sqlite3_context *context,
14710 int argc,
14711 sqlite3_value **argv,
14712 DateTime *p
14714 int i;
14715 const unsigned char *z;
14716 int eType;
14717 memset(p, 0, sizeof(*p));
14718 if( argc==0 ){
14719 return setDateTimeToCurrent(context, p);
14721 if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14722 || eType==SQLITE_INTEGER ){
14723 p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14724 p->validJD = 1;
14725 }else{
14726 z = sqlite3_value_text(argv[0]);
14727 if( !z || parseDateOrTime(context, (char*)z, p) ){
14728 return 1;
14731 for(i=1; i<argc; i++){
14732 z = sqlite3_value_text(argv[i]);
14733 if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14735 return 0;
14740 ** The following routines implement the various date and time functions
14741 ** of SQLite.
14745 ** julianday( TIMESTRING, MOD, MOD, ...)
14747 ** Return the julian day number of the date specified in the arguments
14749 static void juliandayFunc(
14750 sqlite3_context *context,
14751 int argc,
14752 sqlite3_value **argv
14754 DateTime x;
14755 if( isDate(context, argc, argv, &x)==0 ){
14756 computeJD(&x);
14757 sqlite3_result_double(context, x.iJD/86400000.0);
14762 ** datetime( TIMESTRING, MOD, MOD, ...)
14764 ** Return YYYY-MM-DD HH:MM:SS
14766 static void datetimeFunc(
14767 sqlite3_context *context,
14768 int argc,
14769 sqlite3_value **argv
14771 DateTime x;
14772 if( isDate(context, argc, argv, &x)==0 ){
14773 char zBuf[100];
14774 computeYMD_HMS(&x);
14775 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14776 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14777 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14782 ** time( TIMESTRING, MOD, MOD, ...)
14784 ** Return HH:MM:SS
14786 static void timeFunc(
14787 sqlite3_context *context,
14788 int argc,
14789 sqlite3_value **argv
14791 DateTime x;
14792 if( isDate(context, argc, argv, &x)==0 ){
14793 char zBuf[100];
14794 computeHMS(&x);
14795 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14796 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14801 ** date( TIMESTRING, MOD, MOD, ...)
14803 ** Return YYYY-MM-DD
14805 static void dateFunc(
14806 sqlite3_context *context,
14807 int argc,
14808 sqlite3_value **argv
14810 DateTime x;
14811 if( isDate(context, argc, argv, &x)==0 ){
14812 char zBuf[100];
14813 computeYMD(&x);
14814 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14815 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14820 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14822 ** Return a string described by FORMAT. Conversions as follows:
14824 ** %d day of month
14825 ** %f ** fractional seconds SS.SSS
14826 ** %H hour 00-24
14827 ** %j day of year 000-366
14828 ** %J ** Julian day number
14829 ** %m month 01-12
14830 ** %M minute 00-59
14831 ** %s seconds since 1970-01-01
14832 ** %S seconds 00-59
14833 ** %w day of week 0-6 sunday==0
14834 ** %W week of year 00-53
14835 ** %Y year 0000-9999
14836 ** %% %
14838 static void strftimeFunc(
14839 sqlite3_context *context,
14840 int argc,
14841 sqlite3_value **argv
14843 DateTime x;
14844 u64 n;
14845 size_t i,j;
14846 char *z;
14847 sqlite3 *db;
14848 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14849 char zBuf[100];
14850 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14851 db = sqlite3_context_db_handle(context);
14852 for(i=0, n=1; zFmt[i]; i++, n++){
14853 if( zFmt[i]=='%' ){
14854 switch( zFmt[i+1] ){
14855 case 'd':
14856 case 'H':
14857 case 'm':
14858 case 'M':
14859 case 'S':
14860 case 'W':
14861 n++;
14862 /* fall thru */
14863 case 'w':
14864 case '%':
14865 break;
14866 case 'f':
14867 n += 8;
14868 break;
14869 case 'j':
14870 n += 3;
14871 break;
14872 case 'Y':
14873 n += 8;
14874 break;
14875 case 's':
14876 case 'J':
14877 n += 50;
14878 break;
14879 default:
14880 return; /* ERROR. return a NULL */
14882 i++;
14885 testcase( n==sizeof(zBuf)-1 );
14886 testcase( n==sizeof(zBuf) );
14887 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14888 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14889 if( n<sizeof(zBuf) ){
14890 z = zBuf;
14891 }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14892 sqlite3_result_error_toobig(context);
14893 return;
14894 }else{
14895 z = sqlite3DbMallocRaw(db, (int)n);
14896 if( z==0 ){
14897 sqlite3_result_error_nomem(context);
14898 return;
14901 computeJD(&x);
14902 computeYMD_HMS(&x);
14903 for(i=j=0; zFmt[i]; i++){
14904 if( zFmt[i]!='%' ){
14905 z[j++] = zFmt[i];
14906 }else{
14907 i++;
14908 switch( zFmt[i] ){
14909 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14910 case 'f': {
14911 double s = x.s;
14912 if( s>59.999 ) s = 59.999;
14913 sqlite3_snprintf(7, &z[j],"%06.3f", s);
14914 j += sqlite3Strlen30(&z[j]);
14915 break;
14917 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14918 case 'W': /* Fall thru */
14919 case 'j': {
14920 int nDay; /* Number of days since 1st day of year */
14921 DateTime y = x;
14922 y.validJD = 0;
14923 y.M = 1;
14924 y.D = 1;
14925 computeJD(&y);
14926 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14927 if( zFmt[i]=='W' ){
14928 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14929 wd = (int)(((x.iJD+43200000)/86400000)%7);
14930 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14931 j += 2;
14932 }else{
14933 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14934 j += 3;
14936 break;
14938 case 'J': {
14939 sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14940 j+=sqlite3Strlen30(&z[j]);
14941 break;
14943 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14944 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14945 case 's': {
14946 sqlite3_snprintf(30,&z[j],"%lld",
14947 (i64)(x.iJD/1000 - 21086676*(i64)10000));
14948 j += sqlite3Strlen30(&z[j]);
14949 break;
14951 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14952 case 'w': {
14953 z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14954 break;
14956 case 'Y': {
14957 sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14958 break;
14960 default: z[j++] = '%'; break;
14964 z[j] = 0;
14965 sqlite3_result_text(context, z, -1,
14966 z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14970 ** current_time()
14972 ** This function returns the same value as time('now').
14974 static void ctimeFunc(
14975 sqlite3_context *context,
14976 int NotUsed,
14977 sqlite3_value **NotUsed2
14979 UNUSED_PARAMETER2(NotUsed, NotUsed2);
14980 timeFunc(context, 0, 0);
14984 ** current_date()
14986 ** This function returns the same value as date('now').
14988 static void cdateFunc(
14989 sqlite3_context *context,
14990 int NotUsed,
14991 sqlite3_value **NotUsed2
14993 UNUSED_PARAMETER2(NotUsed, NotUsed2);
14994 dateFunc(context, 0, 0);
14998 ** current_timestamp()
15000 ** This function returns the same value as datetime('now').
15002 static void ctimestampFunc(
15003 sqlite3_context *context,
15004 int NotUsed,
15005 sqlite3_value **NotUsed2
15007 UNUSED_PARAMETER2(NotUsed, NotUsed2);
15008 datetimeFunc(context, 0, 0);
15010 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
15012 #ifdef SQLITE_OMIT_DATETIME_FUNCS
15014 ** If the library is compiled to omit the full-scale date and time
15015 ** handling (to get a smaller binary), the following minimal version
15016 ** of the functions current_time(), current_date() and current_timestamp()
15017 ** are included instead. This is to support column declarations that
15018 ** include "DEFAULT CURRENT_TIME" etc.
15020 ** This function uses the C-library functions time(), gmtime()
15021 ** and strftime(). The format string to pass to strftime() is supplied
15022 ** as the user-data for the function.
15024 static void currentTimeFunc(
15025 sqlite3_context *context,
15026 int argc,
15027 sqlite3_value **argv
15029 time_t t;
15030 char *zFormat = (char *)sqlite3_user_data(context);
15031 sqlite3 *db;
15032 sqlite3_int64 iT;
15033 struct tm *pTm;
15034 struct tm sNow;
15035 char zBuf[20];
15037 UNUSED_PARAMETER(argc);
15038 UNUSED_PARAMETER(argv);
15040 db = sqlite3_context_db_handle(context);
15041 if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
15042 t = iT/1000 - 10000*(sqlite3_int64)21086676;
15043 #ifdef HAVE_GMTIME_R
15044 pTm = gmtime_r(&t, &sNow);
15045 #else
15046 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15047 pTm = gmtime(&t);
15048 if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
15049 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15050 #endif
15051 if( pTm ){
15052 strftime(zBuf, 20, zFormat, &sNow);
15053 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15056 #endif
15059 ** This function registered all of the above C functions as SQL
15060 ** functions. This should be the only routine in this file with
15061 ** external linkage.
15063 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
15064 static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
15065 #ifndef SQLITE_OMIT_DATETIME_FUNCS
15066 FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
15067 FUNCTION(date, -1, 0, 0, dateFunc ),
15068 FUNCTION(time, -1, 0, 0, timeFunc ),
15069 FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
15070 FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
15071 FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
15072 FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
15073 FUNCTION(current_date, 0, 0, 0, cdateFunc ),
15074 #else
15075 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
15076 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
15077 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
15078 #endif
15080 int i;
15081 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
15082 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
15084 for(i=0; i<ArraySize(aDateTimeFuncs); i++){
15085 sqlite3FuncDefInsert(pHash, &aFunc[i]);
15089 /************** End of date.c ************************************************/
15090 /************** Begin file os.c **********************************************/
15092 ** 2005 November 29
15094 ** The author disclaims copyright to this source code. In place of
15095 ** a legal notice, here is a blessing:
15097 ** May you do good and not evil.
15098 ** May you find forgiveness for yourself and forgive others.
15099 ** May you share freely, never taking more than you give.
15101 ******************************************************************************
15103 ** This file contains OS interface code that is common to all
15104 ** architectures.
15106 #define _SQLITE_OS_C_ 1
15107 #undef _SQLITE_OS_C_
15110 ** The default SQLite sqlite3_vfs implementations do not allocate
15111 ** memory (actually, os_unix.c allocates a small amount of memory
15112 ** from within OsOpen()), but some third-party implementations may.
15113 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
15114 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
15116 ** The following functions are instrumented for malloc() failure
15117 ** testing:
15119 ** sqlite3OsRead()
15120 ** sqlite3OsWrite()
15121 ** sqlite3OsSync()
15122 ** sqlite3OsFileSize()
15123 ** sqlite3OsLock()
15124 ** sqlite3OsCheckReservedLock()
15125 ** sqlite3OsFileControl()
15126 ** sqlite3OsShmMap()
15127 ** sqlite3OsOpen()
15128 ** sqlite3OsDelete()
15129 ** sqlite3OsAccess()
15130 ** sqlite3OsFullPathname()
15133 #if defined(SQLITE_TEST)
15134 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
15135 #define DO_OS_MALLOC_TEST(x) \
15136 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
15137 void *pTstAlloc = sqlite3Malloc(10); \
15138 if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
15139 sqlite3_free(pTstAlloc); \
15141 #else
15142 #define DO_OS_MALLOC_TEST(x)
15143 #endif
15146 ** The following routines are convenience wrappers around methods
15147 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
15148 ** of this would be completely automatic if SQLite were coded using
15149 ** C++ instead of plain old C.
15151 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
15152 int rc = SQLITE_OK;
15153 if( pId->pMethods ){
15154 rc = pId->pMethods->xClose(pId);
15155 pId->pMethods = 0;
15157 return rc;
15159 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
15160 DO_OS_MALLOC_TEST(id);
15161 return id->pMethods->xRead(id, pBuf, amt, offset);
15163 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
15164 DO_OS_MALLOC_TEST(id);
15165 return id->pMethods->xWrite(id, pBuf, amt, offset);
15167 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15168 return id->pMethods->xTruncate(id, size);
15170 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
15171 DO_OS_MALLOC_TEST(id);
15172 return id->pMethods->xSync(id, flags);
15174 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
15175 DO_OS_MALLOC_TEST(id);
15176 return id->pMethods->xFileSize(id, pSize);
15178 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
15179 DO_OS_MALLOC_TEST(id);
15180 return id->pMethods->xLock(id, lockType);
15182 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
15183 return id->pMethods->xUnlock(id, lockType);
15185 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
15186 DO_OS_MALLOC_TEST(id);
15187 return id->pMethods->xCheckReservedLock(id, pResOut);
15191 ** Use sqlite3OsFileControl() when we are doing something that might fail
15192 ** and we need to know about the failures. Use sqlite3OsFileControlHint()
15193 ** when simply tossing information over the wall to the VFS and we do not
15194 ** really care if the VFS receives and understands the information since it
15195 ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
15196 ** routine has no return value since the return value would be meaningless.
15198 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
15199 DO_OS_MALLOC_TEST(id);
15200 return id->pMethods->xFileControl(id, op, pArg);
15202 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
15203 (void)id->pMethods->xFileControl(id, op, pArg);
15206 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
15207 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
15208 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
15210 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
15211 return id->pMethods->xDeviceCharacteristics(id);
15213 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
15214 return id->pMethods->xShmLock(id, offset, n, flags);
15216 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
15217 id->pMethods->xShmBarrier(id);
15219 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
15220 return id->pMethods->xShmUnmap(id, deleteFlag);
15222 SQLITE_PRIVATE int sqlite3OsShmMap(
15223 sqlite3_file *id, /* Database file handle */
15224 int iPage,
15225 int pgsz,
15226 int bExtend, /* True to extend file if necessary */
15227 void volatile **pp /* OUT: Pointer to mapping */
15229 DO_OS_MALLOC_TEST(id);
15230 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
15233 #if SQLITE_MAX_MMAP_SIZE>0
15234 /* The real implementation of xFetch and xUnfetch */
15235 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15236 DO_OS_MALLOC_TEST(id);
15237 return id->pMethods->xFetch(id, iOff, iAmt, pp);
15239 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15240 return id->pMethods->xUnfetch(id, iOff, p);
15242 #else
15243 /* No-op stubs to use when memory-mapped I/O is disabled */
15244 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15245 *pp = 0;
15246 return SQLITE_OK;
15248 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15249 return SQLITE_OK;
15251 #endif
15254 ** The next group of routines are convenience wrappers around the
15255 ** VFS methods.
15257 SQLITE_PRIVATE int sqlite3OsOpen(
15258 sqlite3_vfs *pVfs,
15259 const char *zPath,
15260 sqlite3_file *pFile,
15261 int flags,
15262 int *pFlagsOut
15264 int rc;
15265 DO_OS_MALLOC_TEST(0);
15266 /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
15267 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
15268 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
15269 ** reaching the VFS. */
15270 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
15271 assert( rc==SQLITE_OK || pFile->pMethods==0 );
15272 return rc;
15274 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
15275 DO_OS_MALLOC_TEST(0);
15276 assert( dirSync==0 || dirSync==1 );
15277 return pVfs->xDelete(pVfs, zPath, dirSync);
15279 SQLITE_PRIVATE int sqlite3OsAccess(
15280 sqlite3_vfs *pVfs,
15281 const char *zPath,
15282 int flags,
15283 int *pResOut
15285 DO_OS_MALLOC_TEST(0);
15286 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
15288 SQLITE_PRIVATE int sqlite3OsFullPathname(
15289 sqlite3_vfs *pVfs,
15290 const char *zPath,
15291 int nPathOut,
15292 char *zPathOut
15294 DO_OS_MALLOC_TEST(0);
15295 zPathOut[0] = 0;
15296 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
15298 #ifndef SQLITE_OMIT_LOAD_EXTENSION
15299 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
15300 return pVfs->xDlOpen(pVfs, zPath);
15302 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15303 pVfs->xDlError(pVfs, nByte, zBufOut);
15305 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
15306 return pVfs->xDlSym(pVfs, pHdle, zSym);
15308 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
15309 pVfs->xDlClose(pVfs, pHandle);
15311 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
15312 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15313 return pVfs->xRandomness(pVfs, nByte, zBufOut);
15315 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
15316 return pVfs->xSleep(pVfs, nMicro);
15318 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
15319 int rc;
15320 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
15321 ** method to get the current date and time if that method is available
15322 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
15323 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
15324 ** unavailable.
15326 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
15327 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
15328 }else{
15329 double r;
15330 rc = pVfs->xCurrentTime(pVfs, &r);
15331 *pTimeOut = (sqlite3_int64)(r*86400000.0);
15333 return rc;
15336 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
15337 sqlite3_vfs *pVfs,
15338 const char *zFile,
15339 sqlite3_file **ppFile,
15340 int flags,
15341 int *pOutFlags
15343 int rc = SQLITE_NOMEM;
15344 sqlite3_file *pFile;
15345 pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15346 if( pFile ){
15347 rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15348 if( rc!=SQLITE_OK ){
15349 sqlite3_free(pFile);
15350 }else{
15351 *ppFile = pFile;
15354 return rc;
15356 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15357 int rc = SQLITE_OK;
15358 assert( pFile );
15359 rc = sqlite3OsClose(pFile);
15360 sqlite3_free(pFile);
15361 return rc;
15365 ** This function is a wrapper around the OS specific implementation of
15366 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
15367 ** ability to simulate a malloc failure, so that the handling of an
15368 ** error in sqlite3_os_init() by the upper layers can be tested.
15370 SQLITE_PRIVATE int sqlite3OsInit(void){
15371 void *p = sqlite3_malloc(10);
15372 if( p==0 ) return SQLITE_NOMEM;
15373 sqlite3_free(p);
15374 return sqlite3_os_init();
15378 ** The list of all registered VFS implementations.
15380 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15381 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15384 ** Locate a VFS by name. If no name is given, simply return the
15385 ** first VFS on the list.
15387 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15388 sqlite3_vfs *pVfs = 0;
15389 #if SQLITE_THREADSAFE
15390 sqlite3_mutex *mutex;
15391 #endif
15392 #ifndef SQLITE_OMIT_AUTOINIT
15393 int rc = sqlite3_initialize();
15394 if( rc ) return 0;
15395 #endif
15396 #if SQLITE_THREADSAFE
15397 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15398 #endif
15399 sqlite3_mutex_enter(mutex);
15400 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
15401 if( zVfs==0 ) break;
15402 if( strcmp(zVfs, pVfs->zName)==0 ) break;
15404 sqlite3_mutex_leave(mutex);
15405 return pVfs;
15409 ** Unlink a VFS from the linked list
15411 static void vfsUnlink(sqlite3_vfs *pVfs){
15412 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
15413 if( pVfs==0 ){
15414 /* No-op */
15415 }else if( vfsList==pVfs ){
15416 vfsList = pVfs->pNext;
15417 }else if( vfsList ){
15418 sqlite3_vfs *p = vfsList;
15419 while( p->pNext && p->pNext!=pVfs ){
15420 p = p->pNext;
15422 if( p->pNext==pVfs ){
15423 p->pNext = pVfs->pNext;
15429 ** Register a VFS with the system. It is harmless to register the same
15430 ** VFS multiple times. The new VFS becomes the default if makeDflt is
15431 ** true.
15433 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
15434 MUTEX_LOGIC(sqlite3_mutex *mutex;)
15435 #ifndef SQLITE_OMIT_AUTOINIT
15436 int rc = sqlite3_initialize();
15437 if( rc ) return rc;
15438 #endif
15439 MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
15440 sqlite3_mutex_enter(mutex);
15441 vfsUnlink(pVfs);
15442 if( makeDflt || vfsList==0 ){
15443 pVfs->pNext = vfsList;
15444 vfsList = pVfs;
15445 }else{
15446 pVfs->pNext = vfsList->pNext;
15447 vfsList->pNext = pVfs;
15449 assert(vfsList);
15450 sqlite3_mutex_leave(mutex);
15451 return SQLITE_OK;
15455 ** Unregister a VFS so that it is no longer accessible.
15457 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15458 #if SQLITE_THREADSAFE
15459 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15460 #endif
15461 sqlite3_mutex_enter(mutex);
15462 vfsUnlink(pVfs);
15463 sqlite3_mutex_leave(mutex);
15464 return SQLITE_OK;
15467 /************** End of os.c **************************************************/
15468 /************** Begin file fault.c *******************************************/
15470 ** 2008 Jan 22
15472 ** The author disclaims copyright to this source code. In place of
15473 ** a legal notice, here is a blessing:
15475 ** May you do good and not evil.
15476 ** May you find forgiveness for yourself and forgive others.
15477 ** May you share freely, never taking more than you give.
15479 *************************************************************************
15481 ** This file contains code to support the concept of "benign"
15482 ** malloc failures (when the xMalloc() or xRealloc() method of the
15483 ** sqlite3_mem_methods structure fails to allocate a block of memory
15484 ** and returns 0).
15486 ** Most malloc failures are non-benign. After they occur, SQLite
15487 ** abandons the current operation and returns an error code (usually
15488 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15489 ** fatal. For example, if a malloc fails while resizing a hash table, this
15490 ** is completely recoverable simply by not carrying out the resize. The
15491 ** hash table will continue to function normally. So a malloc failure
15492 ** during a hash table resize is a benign fault.
15496 #ifndef SQLITE_OMIT_BUILTIN_TEST
15499 ** Global variables.
15501 typedef struct BenignMallocHooks BenignMallocHooks;
15502 static SQLITE_WSD struct BenignMallocHooks {
15503 void (*xBenignBegin)(void);
15504 void (*xBenignEnd)(void);
15505 } sqlite3Hooks = { 0, 0 };
15507 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15508 ** structure. If writable static data is unsupported on the target,
15509 ** we have to locate the state vector at run-time. In the more common
15510 ** case where writable static data is supported, wsdHooks can refer directly
15511 ** to the "sqlite3Hooks" state vector declared above.
15513 #ifdef SQLITE_OMIT_WSD
15514 # define wsdHooksInit \
15515 BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15516 # define wsdHooks x[0]
15517 #else
15518 # define wsdHooksInit
15519 # define wsdHooks sqlite3Hooks
15520 #endif
15524 ** Register hooks to call when sqlite3BeginBenignMalloc() and
15525 ** sqlite3EndBenignMalloc() are called, respectively.
15527 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15528 void (*xBenignBegin)(void),
15529 void (*xBenignEnd)(void)
15531 wsdHooksInit;
15532 wsdHooks.xBenignBegin = xBenignBegin;
15533 wsdHooks.xBenignEnd = xBenignEnd;
15537 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15538 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15539 ** indicates that subsequent malloc failures are non-benign.
15541 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15542 wsdHooksInit;
15543 if( wsdHooks.xBenignBegin ){
15544 wsdHooks.xBenignBegin();
15547 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15548 wsdHooksInit;
15549 if( wsdHooks.xBenignEnd ){
15550 wsdHooks.xBenignEnd();
15554 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15556 /************** End of fault.c ***********************************************/
15557 /************** Begin file mem0.c ********************************************/
15559 ** 2008 October 28
15561 ** The author disclaims copyright to this source code. In place of
15562 ** a legal notice, here is a blessing:
15564 ** May you do good and not evil.
15565 ** May you find forgiveness for yourself and forgive others.
15566 ** May you share freely, never taking more than you give.
15568 *************************************************************************
15570 ** This file contains a no-op memory allocation drivers for use when
15571 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
15572 ** here always fail. SQLite will not operate with these drivers. These
15573 ** are merely placeholders. Real drivers must be substituted using
15574 ** sqlite3_config() before SQLite will operate.
15578 ** This version of the memory allocator is the default. It is
15579 ** used when no other memory allocator is specified using compile-time
15580 ** macros.
15582 #ifdef SQLITE_ZERO_MALLOC
15585 ** No-op versions of all memory allocation routines
15587 static void *sqlite3MemMalloc(int nByte){ return 0; }
15588 static void sqlite3MemFree(void *pPrior){ return; }
15589 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15590 static int sqlite3MemSize(void *pPrior){ return 0; }
15591 static int sqlite3MemRoundup(int n){ return n; }
15592 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15593 static void sqlite3MemShutdown(void *NotUsed){ return; }
15596 ** This routine is the only routine in this file with external linkage.
15598 ** Populate the low-level memory allocation function pointers in
15599 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15601 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15602 static const sqlite3_mem_methods defaultMethods = {
15603 sqlite3MemMalloc,
15604 sqlite3MemFree,
15605 sqlite3MemRealloc,
15606 sqlite3MemSize,
15607 sqlite3MemRoundup,
15608 sqlite3MemInit,
15609 sqlite3MemShutdown,
15612 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15615 #endif /* SQLITE_ZERO_MALLOC */
15617 /************** End of mem0.c ************************************************/
15618 /************** Begin file mem1.c ********************************************/
15620 ** 2007 August 14
15622 ** The author disclaims copyright to this source code. In place of
15623 ** a legal notice, here is a blessing:
15625 ** May you do good and not evil.
15626 ** May you find forgiveness for yourself and forgive others.
15627 ** May you share freely, never taking more than you give.
15629 *************************************************************************
15631 ** This file contains low-level memory allocation drivers for when
15632 ** SQLite will use the standard C-library malloc/realloc/free interface
15633 ** to obtain the memory it needs.
15635 ** This file contains implementations of the low-level memory allocation
15636 ** routines specified in the sqlite3_mem_methods object. The content of
15637 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
15638 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15639 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
15640 ** default configuration is to use memory allocation routines in this
15641 ** file.
15643 ** C-preprocessor macro summary:
15645 ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
15646 ** the malloc_usable_size() interface exists
15647 ** on the target platform. Or, this symbol
15648 ** can be set manually, if desired.
15649 ** If an equivalent interface exists by
15650 ** a different name, using a separate -D
15651 ** option to rename it.
15653 ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
15654 ** memory allocator. Set this symbol to enable
15655 ** building on older macs.
15657 ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
15658 ** _msize() on windows systems. This might
15659 ** be necessary when compiling for Delphi,
15660 ** for example.
15664 ** This version of the memory allocator is the default. It is
15665 ** used when no other memory allocator is specified using compile-time
15666 ** macros.
15668 #ifdef SQLITE_SYSTEM_MALLOC
15671 ** The MSVCRT has malloc_usable_size() but it is called _msize().
15672 ** The use of _msize() is automatic, but can be disabled by compiling
15673 ** with -DSQLITE_WITHOUT_MSIZE
15675 #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15676 # define SQLITE_MALLOCSIZE _msize
15677 #endif
15679 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15682 ** Use the zone allocator available on apple products unless the
15683 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15685 #include <sys/sysctl.h>
15686 #include <malloc/malloc.h>
15687 #include <libkern/OSAtomic.h>
15688 static malloc_zone_t* _sqliteZone_;
15689 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15690 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15691 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15692 #define SQLITE_MALLOCSIZE(x) \
15693 (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15695 #else /* if not __APPLE__ */
15698 ** Use standard C library malloc and free on non-Apple systems.
15699 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15701 #define SQLITE_MALLOC(x) malloc(x)
15702 #define SQLITE_FREE(x) free(x)
15703 #define SQLITE_REALLOC(x,y) realloc((x),(y))
15705 #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
15706 || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
15707 # include <malloc.h> /* Needed for malloc_usable_size on linux */
15708 #endif
15709 #ifdef HAVE_MALLOC_USABLE_SIZE
15710 # ifndef SQLITE_MALLOCSIZE
15711 # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
15712 # endif
15713 #else
15714 # undef SQLITE_MALLOCSIZE
15715 #endif
15717 #endif /* __APPLE__ or not __APPLE__ */
15720 ** Like malloc(), but remember the size of the allocation
15721 ** so that we can find it later using sqlite3MemSize().
15723 ** For this low-level routine, we are guaranteed that nByte>0 because
15724 ** cases of nByte<=0 will be intercepted and dealt with by higher level
15725 ** routines.
15727 static void *sqlite3MemMalloc(int nByte){
15728 #ifdef SQLITE_MALLOCSIZE
15729 void *p = SQLITE_MALLOC( nByte );
15730 if( p==0 ){
15731 testcase( sqlite3GlobalConfig.xLog!=0 );
15732 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15734 return p;
15735 #else
15736 sqlite3_int64 *p;
15737 assert( nByte>0 );
15738 nByte = ROUND8(nByte);
15739 p = SQLITE_MALLOC( nByte+8 );
15740 if( p ){
15741 p[0] = nByte;
15742 p++;
15743 }else{
15744 testcase( sqlite3GlobalConfig.xLog!=0 );
15745 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15747 return (void *)p;
15748 #endif
15752 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
15753 ** or sqlite3MemRealloc().
15755 ** For this low-level routine, we already know that pPrior!=0 since
15756 ** cases where pPrior==0 will have been intecepted and dealt with
15757 ** by higher-level routines.
15759 static void sqlite3MemFree(void *pPrior){
15760 #ifdef SQLITE_MALLOCSIZE
15761 SQLITE_FREE(pPrior);
15762 #else
15763 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15764 assert( pPrior!=0 );
15765 p--;
15766 SQLITE_FREE(p);
15767 #endif
15771 ** Report the allocated size of a prior return from xMalloc()
15772 ** or xRealloc().
15774 static int sqlite3MemSize(void *pPrior){
15775 #ifdef SQLITE_MALLOCSIZE
15776 return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15777 #else
15778 sqlite3_int64 *p;
15779 if( pPrior==0 ) return 0;
15780 p = (sqlite3_int64*)pPrior;
15781 p--;
15782 return (int)p[0];
15783 #endif
15787 ** Like realloc(). Resize an allocation previously obtained from
15788 ** sqlite3MemMalloc().
15790 ** For this low-level interface, we know that pPrior!=0. Cases where
15791 ** pPrior==0 while have been intercepted by higher-level routine and
15792 ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
15793 ** cases where nByte<=0 will have been intercepted by higher-level
15794 ** routines and redirected to xFree.
15796 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15797 #ifdef SQLITE_MALLOCSIZE
15798 void *p = SQLITE_REALLOC(pPrior, nByte);
15799 if( p==0 ){
15800 testcase( sqlite3GlobalConfig.xLog!=0 );
15801 sqlite3_log(SQLITE_NOMEM,
15802 "failed memory resize %u to %u bytes",
15803 SQLITE_MALLOCSIZE(pPrior), nByte);
15805 return p;
15806 #else
15807 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15808 assert( pPrior!=0 && nByte>0 );
15809 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
15810 p--;
15811 p = SQLITE_REALLOC(p, nByte+8 );
15812 if( p ){
15813 p[0] = nByte;
15814 p++;
15815 }else{
15816 testcase( sqlite3GlobalConfig.xLog!=0 );
15817 sqlite3_log(SQLITE_NOMEM,
15818 "failed memory resize %u to %u bytes",
15819 sqlite3MemSize(pPrior), nByte);
15821 return (void*)p;
15822 #endif
15826 ** Round up a request size to the next valid allocation size.
15828 static int sqlite3MemRoundup(int n){
15829 return ROUND8(n);
15833 ** Initialize this module.
15835 static int sqlite3MemInit(void *NotUsed){
15836 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15837 int cpuCount;
15838 size_t len;
15839 if( _sqliteZone_ ){
15840 return SQLITE_OK;
15842 len = sizeof(cpuCount);
15843 /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
15844 sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
15845 if( cpuCount>1 ){
15846 /* defer MT decisions to system malloc */
15847 _sqliteZone_ = malloc_default_zone();
15848 }else{
15849 /* only 1 core, use our own zone to contention over global locks,
15850 ** e.g. we have our own dedicated locks */
15851 bool success;
15852 malloc_zone_t* newzone = malloc_create_zone(4096, 0);
15853 malloc_set_zone_name(newzone, "Sqlite_Heap");
15855 success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
15856 (void * volatile *)&_sqliteZone_);
15857 }while(!_sqliteZone_);
15858 if( !success ){
15859 /* somebody registered a zone first */
15860 malloc_destroy_zone(newzone);
15863 #endif
15864 UNUSED_PARAMETER(NotUsed);
15865 return SQLITE_OK;
15869 ** Deinitialize this module.
15871 static void sqlite3MemShutdown(void *NotUsed){
15872 UNUSED_PARAMETER(NotUsed);
15873 return;
15877 ** This routine is the only routine in this file with external linkage.
15879 ** Populate the low-level memory allocation function pointers in
15880 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15882 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15883 static const sqlite3_mem_methods defaultMethods = {
15884 sqlite3MemMalloc,
15885 sqlite3MemFree,
15886 sqlite3MemRealloc,
15887 sqlite3MemSize,
15888 sqlite3MemRoundup,
15889 sqlite3MemInit,
15890 sqlite3MemShutdown,
15893 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15896 #endif /* SQLITE_SYSTEM_MALLOC */
15898 /************** End of mem1.c ************************************************/
15899 /************** Begin file mem2.c ********************************************/
15901 ** 2007 August 15
15903 ** The author disclaims copyright to this source code. In place of
15904 ** a legal notice, here is a blessing:
15906 ** May you do good and not evil.
15907 ** May you find forgiveness for yourself and forgive others.
15908 ** May you share freely, never taking more than you give.
15910 *************************************************************************
15912 ** This file contains low-level memory allocation drivers for when
15913 ** SQLite will use the standard C-library malloc/realloc/free interface
15914 ** to obtain the memory it needs while adding lots of additional debugging
15915 ** information to each allocation in order to help detect and fix memory
15916 ** leaks and memory usage errors.
15918 ** This file contains implementations of the low-level memory allocation
15919 ** routines specified in the sqlite3_mem_methods object.
15923 ** This version of the memory allocator is used only if the
15924 ** SQLITE_MEMDEBUG macro is defined
15926 #ifdef SQLITE_MEMDEBUG
15929 ** The backtrace functionality is only available with GLIBC
15931 #ifdef __GLIBC__
15932 extern int backtrace(void**,int);
15933 extern void backtrace_symbols_fd(void*const*,int,int);
15934 #else
15935 # define backtrace(A,B) 1
15936 # define backtrace_symbols_fd(A,B,C)
15937 #endif
15938 /* #include <stdio.h> */
15941 ** Each memory allocation looks like this:
15943 ** ------------------------------------------------------------------------
15944 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
15945 ** ------------------------------------------------------------------------
15947 ** The application code sees only a pointer to the allocation. We have
15948 ** to back up from the allocation pointer to find the MemBlockHdr. The
15949 ** MemBlockHdr tells us the size of the allocation and the number of
15950 ** backtrace pointers. There is also a guard word at the end of the
15951 ** MemBlockHdr.
15953 struct MemBlockHdr {
15954 i64 iSize; /* Size of this allocation */
15955 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
15956 char nBacktrace; /* Number of backtraces on this alloc */
15957 char nBacktraceSlots; /* Available backtrace slots */
15958 u8 nTitle; /* Bytes of title; includes '\0' */
15959 u8 eType; /* Allocation type code */
15960 int iForeGuard; /* Guard word for sanity */
15964 ** Guard words
15966 #define FOREGUARD 0x80F5E153
15967 #define REARGUARD 0xE4676B53
15970 ** Number of malloc size increments to track.
15972 #define NCSIZE 1000
15975 ** All of the static variables used by this module are collected
15976 ** into a single structure named "mem". This is to keep the
15977 ** static variables organized and to reduce namespace pollution
15978 ** when this module is combined with other in the amalgamation.
15980 static struct {
15983 ** Mutex to control access to the memory allocation subsystem.
15985 sqlite3_mutex *mutex;
15988 ** Head and tail of a linked list of all outstanding allocations
15990 struct MemBlockHdr *pFirst;
15991 struct MemBlockHdr *pLast;
15994 ** The number of levels of backtrace to save in new allocations.
15996 int nBacktrace;
15997 void (*xBacktrace)(int, int, void **);
16000 ** Title text to insert in front of each block
16002 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
16003 char zTitle[100]; /* The title text */
16006 ** sqlite3MallocDisallow() increments the following counter.
16007 ** sqlite3MallocAllow() decrements it.
16009 int disallow; /* Do not allow memory allocation */
16012 ** Gather statistics on the sizes of memory allocations.
16013 ** nAlloc[i] is the number of allocation attempts of i*8
16014 ** bytes. i==NCSIZE is the number of allocation attempts for
16015 ** sizes more than NCSIZE*8 bytes.
16017 int nAlloc[NCSIZE]; /* Total number of allocations */
16018 int nCurrent[NCSIZE]; /* Current number of allocations */
16019 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
16021 } mem;
16025 ** Adjust memory usage statistics
16027 static void adjustStats(int iSize, int increment){
16028 int i = ROUND8(iSize)/8;
16029 if( i>NCSIZE-1 ){
16030 i = NCSIZE - 1;
16032 if( increment>0 ){
16033 mem.nAlloc[i]++;
16034 mem.nCurrent[i]++;
16035 if( mem.nCurrent[i]>mem.mxCurrent[i] ){
16036 mem.mxCurrent[i] = mem.nCurrent[i];
16038 }else{
16039 mem.nCurrent[i]--;
16040 assert( mem.nCurrent[i]>=0 );
16045 ** Given an allocation, find the MemBlockHdr for that allocation.
16047 ** This routine checks the guards at either end of the allocation and
16048 ** if they are incorrect it asserts.
16050 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
16051 struct MemBlockHdr *p;
16052 int *pInt;
16053 u8 *pU8;
16054 int nReserve;
16056 p = (struct MemBlockHdr*)pAllocation;
16057 p--;
16058 assert( p->iForeGuard==(int)FOREGUARD );
16059 nReserve = ROUND8(p->iSize);
16060 pInt = (int*)pAllocation;
16061 pU8 = (u8*)pAllocation;
16062 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
16063 /* This checks any of the "extra" bytes allocated due
16064 ** to rounding up to an 8 byte boundary to ensure
16065 ** they haven't been overwritten.
16067 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
16068 return p;
16072 ** Return the number of bytes currently allocated at address p.
16074 static int sqlite3MemSize(void *p){
16075 struct MemBlockHdr *pHdr;
16076 if( !p ){
16077 return 0;
16079 pHdr = sqlite3MemsysGetHeader(p);
16080 return pHdr->iSize;
16084 ** Initialize the memory allocation subsystem.
16086 static int sqlite3MemInit(void *NotUsed){
16087 UNUSED_PARAMETER(NotUsed);
16088 assert( (sizeof(struct MemBlockHdr)&7) == 0 );
16089 if( !sqlite3GlobalConfig.bMemstat ){
16090 /* If memory status is enabled, then the malloc.c wrapper will already
16091 ** hold the STATIC_MEM mutex when the routines here are invoked. */
16092 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16094 return SQLITE_OK;
16098 ** Deinitialize the memory allocation subsystem.
16100 static void sqlite3MemShutdown(void *NotUsed){
16101 UNUSED_PARAMETER(NotUsed);
16102 mem.mutex = 0;
16106 ** Round up a request size to the next valid allocation size.
16108 static int sqlite3MemRoundup(int n){
16109 return ROUND8(n);
16113 ** Fill a buffer with pseudo-random bytes. This is used to preset
16114 ** the content of a new memory allocation to unpredictable values and
16115 ** to clear the content of a freed allocation to unpredictable values.
16117 static void randomFill(char *pBuf, int nByte){
16118 unsigned int x, y, r;
16119 x = SQLITE_PTR_TO_INT(pBuf);
16120 y = nByte | 1;
16121 while( nByte >= 4 ){
16122 x = (x>>1) ^ (-(x&1) & 0xd0000001);
16123 y = y*1103515245 + 12345;
16124 r = x ^ y;
16125 *(int*)pBuf = r;
16126 pBuf += 4;
16127 nByte -= 4;
16129 while( nByte-- > 0 ){
16130 x = (x>>1) ^ (-(x&1) & 0xd0000001);
16131 y = y*1103515245 + 12345;
16132 r = x ^ y;
16133 *(pBuf++) = r & 0xff;
16138 ** Allocate nByte bytes of memory.
16140 static void *sqlite3MemMalloc(int nByte){
16141 struct MemBlockHdr *pHdr;
16142 void **pBt;
16143 char *z;
16144 int *pInt;
16145 void *p = 0;
16146 int totalSize;
16147 int nReserve;
16148 sqlite3_mutex_enter(mem.mutex);
16149 assert( mem.disallow==0 );
16150 nReserve = ROUND8(nByte);
16151 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
16152 mem.nBacktrace*sizeof(void*) + mem.nTitle;
16153 p = malloc(totalSize);
16154 if( p ){
16155 z = p;
16156 pBt = (void**)&z[mem.nTitle];
16157 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
16158 pHdr->pNext = 0;
16159 pHdr->pPrev = mem.pLast;
16160 if( mem.pLast ){
16161 mem.pLast->pNext = pHdr;
16162 }else{
16163 mem.pFirst = pHdr;
16165 mem.pLast = pHdr;
16166 pHdr->iForeGuard = FOREGUARD;
16167 pHdr->eType = MEMTYPE_HEAP;
16168 pHdr->nBacktraceSlots = mem.nBacktrace;
16169 pHdr->nTitle = mem.nTitle;
16170 if( mem.nBacktrace ){
16171 void *aAddr[40];
16172 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
16173 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
16174 assert(pBt[0]);
16175 if( mem.xBacktrace ){
16176 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
16178 }else{
16179 pHdr->nBacktrace = 0;
16181 if( mem.nTitle ){
16182 memcpy(z, mem.zTitle, mem.nTitle);
16184 pHdr->iSize = nByte;
16185 adjustStats(nByte, +1);
16186 pInt = (int*)&pHdr[1];
16187 pInt[nReserve/sizeof(int)] = REARGUARD;
16188 randomFill((char*)pInt, nByte);
16189 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
16190 p = (void*)pInt;
16192 sqlite3_mutex_leave(mem.mutex);
16193 return p;
16197 ** Free memory.
16199 static void sqlite3MemFree(void *pPrior){
16200 struct MemBlockHdr *pHdr;
16201 void **pBt;
16202 char *z;
16203 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
16204 || mem.mutex!=0 );
16205 pHdr = sqlite3MemsysGetHeader(pPrior);
16206 pBt = (void**)pHdr;
16207 pBt -= pHdr->nBacktraceSlots;
16208 sqlite3_mutex_enter(mem.mutex);
16209 if( pHdr->pPrev ){
16210 assert( pHdr->pPrev->pNext==pHdr );
16211 pHdr->pPrev->pNext = pHdr->pNext;
16212 }else{
16213 assert( mem.pFirst==pHdr );
16214 mem.pFirst = pHdr->pNext;
16216 if( pHdr->pNext ){
16217 assert( pHdr->pNext->pPrev==pHdr );
16218 pHdr->pNext->pPrev = pHdr->pPrev;
16219 }else{
16220 assert( mem.pLast==pHdr );
16221 mem.pLast = pHdr->pPrev;
16223 z = (char*)pBt;
16224 z -= pHdr->nTitle;
16225 adjustStats(pHdr->iSize, -1);
16226 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
16227 pHdr->iSize + sizeof(int) + pHdr->nTitle);
16228 free(z);
16229 sqlite3_mutex_leave(mem.mutex);
16233 ** Change the size of an existing memory allocation.
16235 ** For this debugging implementation, we *always* make a copy of the
16236 ** allocation into a new place in memory. In this way, if the
16237 ** higher level code is using pointer to the old allocation, it is
16238 ** much more likely to break and we are much more liking to find
16239 ** the error.
16241 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16242 struct MemBlockHdr *pOldHdr;
16243 void *pNew;
16244 assert( mem.disallow==0 );
16245 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
16246 pOldHdr = sqlite3MemsysGetHeader(pPrior);
16247 pNew = sqlite3MemMalloc(nByte);
16248 if( pNew ){
16249 memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
16250 if( nByte>pOldHdr->iSize ){
16251 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
16253 sqlite3MemFree(pPrior);
16255 return pNew;
16259 ** Populate the low-level memory allocation function pointers in
16260 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16262 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16263 static const sqlite3_mem_methods defaultMethods = {
16264 sqlite3MemMalloc,
16265 sqlite3MemFree,
16266 sqlite3MemRealloc,
16267 sqlite3MemSize,
16268 sqlite3MemRoundup,
16269 sqlite3MemInit,
16270 sqlite3MemShutdown,
16273 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16277 ** Set the "type" of an allocation.
16279 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
16280 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16281 struct MemBlockHdr *pHdr;
16282 pHdr = sqlite3MemsysGetHeader(p);
16283 assert( pHdr->iForeGuard==FOREGUARD );
16284 pHdr->eType = eType;
16289 ** Return TRUE if the mask of type in eType matches the type of the
16290 ** allocation p. Also return true if p==NULL.
16292 ** This routine is designed for use within an assert() statement, to
16293 ** verify the type of an allocation. For example:
16295 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
16297 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
16298 int rc = 1;
16299 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16300 struct MemBlockHdr *pHdr;
16301 pHdr = sqlite3MemsysGetHeader(p);
16302 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
16303 if( (pHdr->eType&eType)==0 ){
16304 rc = 0;
16307 return rc;
16311 ** Return TRUE if the mask of type in eType matches no bits of the type of the
16312 ** allocation p. Also return true if p==NULL.
16314 ** This routine is designed for use within an assert() statement, to
16315 ** verify the type of an allocation. For example:
16317 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
16319 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
16320 int rc = 1;
16321 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16322 struct MemBlockHdr *pHdr;
16323 pHdr = sqlite3MemsysGetHeader(p);
16324 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
16325 if( (pHdr->eType&eType)!=0 ){
16326 rc = 0;
16329 return rc;
16333 ** Set the number of backtrace levels kept for each allocation.
16334 ** A value of zero turns off backtracing. The number is always rounded
16335 ** up to a multiple of 2.
16337 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
16338 if( depth<0 ){ depth = 0; }
16339 if( depth>20 ){ depth = 20; }
16340 depth = (depth+1)&0xfe;
16341 mem.nBacktrace = depth;
16344 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16345 mem.xBacktrace = xBacktrace;
16349 ** Set the title string for subsequent allocations.
16351 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16352 unsigned int n = sqlite3Strlen30(zTitle) + 1;
16353 sqlite3_mutex_enter(mem.mutex);
16354 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16355 memcpy(mem.zTitle, zTitle, n);
16356 mem.zTitle[n] = 0;
16357 mem.nTitle = ROUND8(n);
16358 sqlite3_mutex_leave(mem.mutex);
16361 SQLITE_PRIVATE void sqlite3MemdebugSync(){
16362 struct MemBlockHdr *pHdr;
16363 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16364 void **pBt = (void**)pHdr;
16365 pBt -= pHdr->nBacktraceSlots;
16366 mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16371 ** Open the file indicated and write a log of all unfreed memory
16372 ** allocations into that log.
16374 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16375 FILE *out;
16376 struct MemBlockHdr *pHdr;
16377 void **pBt;
16378 int i;
16379 out = fopen(zFilename, "w");
16380 if( out==0 ){
16381 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16382 zFilename);
16383 return;
16385 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16386 char *z = (char*)pHdr;
16387 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
16388 fprintf(out, "**** %lld bytes at %p from %s ****\n",
16389 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
16390 if( pHdr->nBacktrace ){
16391 fflush(out);
16392 pBt = (void**)pHdr;
16393 pBt -= pHdr->nBacktraceSlots;
16394 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
16395 fprintf(out, "\n");
16398 fprintf(out, "COUNTS:\n");
16399 for(i=0; i<NCSIZE-1; i++){
16400 if( mem.nAlloc[i] ){
16401 fprintf(out, " %5d: %10d %10d %10d\n",
16402 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
16405 if( mem.nAlloc[NCSIZE-1] ){
16406 fprintf(out, " %5d: %10d %10d %10d\n",
16407 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
16408 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
16410 fclose(out);
16414 ** Return the number of times sqlite3MemMalloc() has been called.
16416 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
16417 int i;
16418 int nTotal = 0;
16419 for(i=0; i<NCSIZE; i++){
16420 nTotal += mem.nAlloc[i];
16422 return nTotal;
16426 #endif /* SQLITE_MEMDEBUG */
16428 /************** End of mem2.c ************************************************/
16429 /************** Begin file mem3.c ********************************************/
16431 ** 2007 October 14
16433 ** The author disclaims copyright to this source code. In place of
16434 ** a legal notice, here is a blessing:
16436 ** May you do good and not evil.
16437 ** May you find forgiveness for yourself and forgive others.
16438 ** May you share freely, never taking more than you give.
16440 *************************************************************************
16441 ** This file contains the C functions that implement a memory
16442 ** allocation subsystem for use by SQLite.
16444 ** This version of the memory allocation subsystem omits all
16445 ** use of malloc(). The SQLite user supplies a block of memory
16446 ** before calling sqlite3_initialize() from which allocations
16447 ** are made and returned by the xMalloc() and xRealloc()
16448 ** implementations. Once sqlite3_initialize() has been called,
16449 ** the amount of memory available to SQLite is fixed and cannot
16450 ** be changed.
16452 ** This version of the memory allocation subsystem is included
16453 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16457 ** This version of the memory allocator is only built into the library
16458 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16459 ** mean that the library will use a memory-pool by default, just that
16460 ** it is available. The mempool allocator is activated by calling
16461 ** sqlite3_config().
16463 #ifdef SQLITE_ENABLE_MEMSYS3
16466 ** Maximum size (in Mem3Blocks) of a "small" chunk.
16468 #define MX_SMALL 10
16472 ** Number of freelist hash slots
16474 #define N_HASH 61
16477 ** A memory allocation (also called a "chunk") consists of two or
16478 ** more blocks where each block is 8 bytes. The first 8 bytes are
16479 ** a header that is not returned to the user.
16481 ** A chunk is two or more blocks that is either checked out or
16482 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
16483 ** size of the allocation in blocks if the allocation is free.
16484 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16485 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
16486 ** is true if the previous chunk is checked out and false if the
16487 ** previous chunk is free. The u.hdr.prevSize field is the size of
16488 ** the previous chunk in blocks if the previous chunk is on the
16489 ** freelist. If the previous chunk is checked out, then
16490 ** u.hdr.prevSize can be part of the data for that chunk and should
16491 ** not be read or written.
16493 ** We often identify a chunk by its index in mem3.aPool[]. When
16494 ** this is done, the chunk index refers to the second block of
16495 ** the chunk. In this way, the first chunk has an index of 1.
16496 ** A chunk index of 0 means "no such chunk" and is the equivalent
16497 ** of a NULL pointer.
16499 ** The second block of free chunks is of the form u.list. The
16500 ** two fields form a double-linked list of chunks of related sizes.
16501 ** Pointers to the head of the list are stored in mem3.aiSmall[]
16502 ** for smaller chunks and mem3.aiHash[] for larger chunks.
16504 ** The second block of a chunk is user data if the chunk is checked
16505 ** out. If a chunk is checked out, the user data may extend into
16506 ** the u.hdr.prevSize value of the following chunk.
16508 typedef struct Mem3Block Mem3Block;
16509 struct Mem3Block {
16510 union {
16511 struct {
16512 u32 prevSize; /* Size of previous chunk in Mem3Block elements */
16513 u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
16514 } hdr;
16515 struct {
16516 u32 next; /* Index in mem3.aPool[] of next free chunk */
16517 u32 prev; /* Index in mem3.aPool[] of previous free chunk */
16518 } list;
16519 } u;
16523 ** All of the static variables used by this module are collected
16524 ** into a single structure named "mem3". This is to keep the
16525 ** static variables organized and to reduce namespace pollution
16526 ** when this module is combined with other in the amalgamation.
16528 static SQLITE_WSD struct Mem3Global {
16530 ** Memory available for allocation. nPool is the size of the array
16531 ** (in Mem3Blocks) pointed to by aPool less 2.
16533 u32 nPool;
16534 Mem3Block *aPool;
16537 ** True if we are evaluating an out-of-memory callback.
16539 int alarmBusy;
16542 ** Mutex to control access to the memory allocation subsystem.
16544 sqlite3_mutex *mutex;
16547 ** The minimum amount of free space that we have seen.
16549 u32 mnMaster;
16552 ** iMaster is the index of the master chunk. Most new allocations
16553 ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
16554 ** of the current master. iMaster is 0 if there is not master chunk.
16555 ** The master chunk is not in either the aiHash[] or aiSmall[].
16557 u32 iMaster;
16558 u32 szMaster;
16561 ** Array of lists of free blocks according to the block size
16562 ** for smaller chunks, or a hash on the block size for larger
16563 ** chunks.
16565 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
16566 u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
16567 } mem3 = { 97535575 };
16569 #define mem3 GLOBAL(struct Mem3Global, mem3)
16572 ** Unlink the chunk at mem3.aPool[i] from list it is currently
16573 ** on. *pRoot is the list that i is a member of.
16575 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16576 u32 next = mem3.aPool[i].u.list.next;
16577 u32 prev = mem3.aPool[i].u.list.prev;
16578 assert( sqlite3_mutex_held(mem3.mutex) );
16579 if( prev==0 ){
16580 *pRoot = next;
16581 }else{
16582 mem3.aPool[prev].u.list.next = next;
16584 if( next ){
16585 mem3.aPool[next].u.list.prev = prev;
16587 mem3.aPool[i].u.list.next = 0;
16588 mem3.aPool[i].u.list.prev = 0;
16592 ** Unlink the chunk at index i from
16593 ** whatever list is currently a member of.
16595 static void memsys3Unlink(u32 i){
16596 u32 size, hash;
16597 assert( sqlite3_mutex_held(mem3.mutex) );
16598 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16599 assert( i>=1 );
16600 size = mem3.aPool[i-1].u.hdr.size4x/4;
16601 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16602 assert( size>=2 );
16603 if( size <= MX_SMALL ){
16604 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16605 }else{
16606 hash = size % N_HASH;
16607 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16612 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
16613 ** at *pRoot.
16615 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16616 assert( sqlite3_mutex_held(mem3.mutex) );
16617 mem3.aPool[i].u.list.next = *pRoot;
16618 mem3.aPool[i].u.list.prev = 0;
16619 if( *pRoot ){
16620 mem3.aPool[*pRoot].u.list.prev = i;
16622 *pRoot = i;
16626 ** Link the chunk at index i into either the appropriate
16627 ** small chunk list, or into the large chunk hash table.
16629 static void memsys3Link(u32 i){
16630 u32 size, hash;
16631 assert( sqlite3_mutex_held(mem3.mutex) );
16632 assert( i>=1 );
16633 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16634 size = mem3.aPool[i-1].u.hdr.size4x/4;
16635 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16636 assert( size>=2 );
16637 if( size <= MX_SMALL ){
16638 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16639 }else{
16640 hash = size % N_HASH;
16641 memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16646 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16647 ** will already be held (obtained by code in malloc.c) if
16648 ** sqlite3GlobalConfig.bMemStat is true.
16650 static void memsys3Enter(void){
16651 if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16652 mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16654 sqlite3_mutex_enter(mem3.mutex);
16656 static void memsys3Leave(void){
16657 sqlite3_mutex_leave(mem3.mutex);
16661 ** Called when we are unable to satisfy an allocation of nBytes.
16663 static void memsys3OutOfMemory(int nByte){
16664 if( !mem3.alarmBusy ){
16665 mem3.alarmBusy = 1;
16666 assert( sqlite3_mutex_held(mem3.mutex) );
16667 sqlite3_mutex_leave(mem3.mutex);
16668 sqlite3_release_memory(nByte);
16669 sqlite3_mutex_enter(mem3.mutex);
16670 mem3.alarmBusy = 0;
16676 ** Chunk i is a free chunk that has been unlinked. Adjust its
16677 ** size parameters for check-out and return a pointer to the
16678 ** user portion of the chunk.
16680 static void *memsys3Checkout(u32 i, u32 nBlock){
16681 u32 x;
16682 assert( sqlite3_mutex_held(mem3.mutex) );
16683 assert( i>=1 );
16684 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16685 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16686 x = mem3.aPool[i-1].u.hdr.size4x;
16687 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16688 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16689 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16690 return &mem3.aPool[i];
16694 ** Carve a piece off of the end of the mem3.iMaster free chunk.
16695 ** Return a pointer to the new allocation. Or, if the master chunk
16696 ** is not large enough, return 0.
16698 static void *memsys3FromMaster(u32 nBlock){
16699 assert( sqlite3_mutex_held(mem3.mutex) );
16700 assert( mem3.szMaster>=nBlock );
16701 if( nBlock>=mem3.szMaster-1 ){
16702 /* Use the entire master */
16703 void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16704 mem3.iMaster = 0;
16705 mem3.szMaster = 0;
16706 mem3.mnMaster = 0;
16707 return p;
16708 }else{
16709 /* Split the master block. Return the tail. */
16710 u32 newi, x;
16711 newi = mem3.iMaster + mem3.szMaster - nBlock;
16712 assert( newi > mem3.iMaster+1 );
16713 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16714 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16715 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16716 mem3.szMaster -= nBlock;
16717 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16718 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16719 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16720 if( mem3.szMaster < mem3.mnMaster ){
16721 mem3.mnMaster = mem3.szMaster;
16723 return (void*)&mem3.aPool[newi];
16728 ** *pRoot is the head of a list of free chunks of the same size
16729 ** or same size hash. In other words, *pRoot is an entry in either
16730 ** mem3.aiSmall[] or mem3.aiHash[].
16732 ** This routine examines all entries on the given list and tries
16733 ** to coalesce each entries with adjacent free chunks.
16735 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
16736 ** the current mem3.iMaster with the new larger chunk. In order for
16737 ** this mem3.iMaster replacement to work, the master chunk must be
16738 ** linked into the hash tables. That is not the normal state of
16739 ** affairs, of course. The calling routine must link the master
16740 ** chunk before invoking this routine, then must unlink the (possibly
16741 ** changed) master chunk once this routine has finished.
16743 static void memsys3Merge(u32 *pRoot){
16744 u32 iNext, prev, size, i, x;
16746 assert( sqlite3_mutex_held(mem3.mutex) );
16747 for(i=*pRoot; i>0; i=iNext){
16748 iNext = mem3.aPool[i].u.list.next;
16749 size = mem3.aPool[i-1].u.hdr.size4x;
16750 assert( (size&1)==0 );
16751 if( (size&2)==0 ){
16752 memsys3UnlinkFromList(i, pRoot);
16753 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16754 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16755 if( prev==iNext ){
16756 iNext = mem3.aPool[prev].u.list.next;
16758 memsys3Unlink(prev);
16759 size = i + size/4 - prev;
16760 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16761 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16762 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16763 memsys3Link(prev);
16764 i = prev;
16765 }else{
16766 size /= 4;
16768 if( size>mem3.szMaster ){
16769 mem3.iMaster = i;
16770 mem3.szMaster = size;
16776 ** Return a block of memory of at least nBytes in size.
16777 ** Return NULL if unable.
16779 ** This function assumes that the necessary mutexes, if any, are
16780 ** already held by the caller. Hence "Unsafe".
16782 static void *memsys3MallocUnsafe(int nByte){
16783 u32 i;
16784 u32 nBlock;
16785 u32 toFree;
16787 assert( sqlite3_mutex_held(mem3.mutex) );
16788 assert( sizeof(Mem3Block)==8 );
16789 if( nByte<=12 ){
16790 nBlock = 2;
16791 }else{
16792 nBlock = (nByte + 11)/8;
16794 assert( nBlock>=2 );
16796 /* STEP 1:
16797 ** Look for an entry of the correct size in either the small
16798 ** chunk table or in the large chunk hash table. This is
16799 ** successful most of the time (about 9 times out of 10).
16801 if( nBlock <= MX_SMALL ){
16802 i = mem3.aiSmall[nBlock-2];
16803 if( i>0 ){
16804 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
16805 return memsys3Checkout(i, nBlock);
16807 }else{
16808 int hash = nBlock % N_HASH;
16809 for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
16810 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
16811 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16812 return memsys3Checkout(i, nBlock);
16817 /* STEP 2:
16818 ** Try to satisfy the allocation by carving a piece off of the end
16819 ** of the master chunk. This step usually works if step 1 fails.
16821 if( mem3.szMaster>=nBlock ){
16822 return memsys3FromMaster(nBlock);
16826 /* STEP 3:
16827 ** Loop through the entire memory pool. Coalesce adjacent free
16828 ** chunks. Recompute the master chunk as the largest free chunk.
16829 ** Then try again to satisfy the allocation by carving a piece off
16830 ** of the end of the master chunk. This step happens very
16831 ** rarely (we hope!)
16833 for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
16834 memsys3OutOfMemory(toFree);
16835 if( mem3.iMaster ){
16836 memsys3Link(mem3.iMaster);
16837 mem3.iMaster = 0;
16838 mem3.szMaster = 0;
16840 for(i=0; i<N_HASH; i++){
16841 memsys3Merge(&mem3.aiHash[i]);
16843 for(i=0; i<MX_SMALL-1; i++){
16844 memsys3Merge(&mem3.aiSmall[i]);
16846 if( mem3.szMaster ){
16847 memsys3Unlink(mem3.iMaster);
16848 if( mem3.szMaster>=nBlock ){
16849 return memsys3FromMaster(nBlock);
16854 /* If none of the above worked, then we fail. */
16855 return 0;
16859 ** Free an outstanding memory allocation.
16861 ** This function assumes that the necessary mutexes, if any, are
16862 ** already held by the caller. Hence "Unsafe".
16864 static void memsys3FreeUnsafe(void *pOld){
16865 Mem3Block *p = (Mem3Block*)pOld;
16866 int i;
16867 u32 size, x;
16868 assert( sqlite3_mutex_held(mem3.mutex) );
16869 assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16870 i = p - mem3.aPool;
16871 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16872 size = mem3.aPool[i-1].u.hdr.size4x/4;
16873 assert( i+size<=mem3.nPool+1 );
16874 mem3.aPool[i-1].u.hdr.size4x &= ~1;
16875 mem3.aPool[i+size-1].u.hdr.prevSize = size;
16876 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16877 memsys3Link(i);
16879 /* Try to expand the master using the newly freed chunk */
16880 if( mem3.iMaster ){
16881 while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16882 size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16883 mem3.iMaster -= size;
16884 mem3.szMaster += size;
16885 memsys3Unlink(mem3.iMaster);
16886 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16887 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16888 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16890 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16891 while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16892 memsys3Unlink(mem3.iMaster+mem3.szMaster);
16893 mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16894 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16895 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16901 ** Return the size of an outstanding allocation, in bytes. The
16902 ** size returned omits the 8-byte header overhead. This only
16903 ** works for chunks that are currently checked out.
16905 static int memsys3Size(void *p){
16906 Mem3Block *pBlock;
16907 if( p==0 ) return 0;
16908 pBlock = (Mem3Block*)p;
16909 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16910 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16914 ** Round up a request size to the next valid allocation size.
16916 static int memsys3Roundup(int n){
16917 if( n<=12 ){
16918 return 12;
16919 }else{
16920 return ((n+11)&~7) - 4;
16925 ** Allocate nBytes of memory.
16927 static void *memsys3Malloc(int nBytes){
16928 sqlite3_int64 *p;
16929 assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
16930 memsys3Enter();
16931 p = memsys3MallocUnsafe(nBytes);
16932 memsys3Leave();
16933 return (void*)p;
16937 ** Free memory.
16939 static void memsys3Free(void *pPrior){
16940 assert( pPrior );
16941 memsys3Enter();
16942 memsys3FreeUnsafe(pPrior);
16943 memsys3Leave();
16947 ** Change the size of an existing memory allocation
16949 static void *memsys3Realloc(void *pPrior, int nBytes){
16950 int nOld;
16951 void *p;
16952 if( pPrior==0 ){
16953 return sqlite3_malloc(nBytes);
16955 if( nBytes<=0 ){
16956 sqlite3_free(pPrior);
16957 return 0;
16959 nOld = memsys3Size(pPrior);
16960 if( nBytes<=nOld && nBytes>=nOld-128 ){
16961 return pPrior;
16963 memsys3Enter();
16964 p = memsys3MallocUnsafe(nBytes);
16965 if( p ){
16966 if( nOld<nBytes ){
16967 memcpy(p, pPrior, nOld);
16968 }else{
16969 memcpy(p, pPrior, nBytes);
16971 memsys3FreeUnsafe(pPrior);
16973 memsys3Leave();
16974 return p;
16978 ** Initialize this module.
16980 static int memsys3Init(void *NotUsed){
16981 UNUSED_PARAMETER(NotUsed);
16982 if( !sqlite3GlobalConfig.pHeap ){
16983 return SQLITE_ERROR;
16986 /* Store a pointer to the memory block in global structure mem3. */
16987 assert( sizeof(Mem3Block)==8 );
16988 mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16989 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16991 /* Initialize the master block. */
16992 mem3.szMaster = mem3.nPool;
16993 mem3.mnMaster = mem3.szMaster;
16994 mem3.iMaster = 1;
16995 mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
16996 mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
16997 mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
16999 return SQLITE_OK;
17003 ** Deinitialize this module.
17005 static void memsys3Shutdown(void *NotUsed){
17006 UNUSED_PARAMETER(NotUsed);
17007 mem3.mutex = 0;
17008 return;
17014 ** Open the file indicated and write a log of all unfreed memory
17015 ** allocations into that log.
17017 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
17018 #ifdef SQLITE_DEBUG
17019 FILE *out;
17020 u32 i, j;
17021 u32 size;
17022 if( zFilename==0 || zFilename[0]==0 ){
17023 out = stdout;
17024 }else{
17025 out = fopen(zFilename, "w");
17026 if( out==0 ){
17027 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17028 zFilename);
17029 return;
17032 memsys3Enter();
17033 fprintf(out, "CHUNKS:\n");
17034 for(i=1; i<=mem3.nPool; i+=size/4){
17035 size = mem3.aPool[i-1].u.hdr.size4x;
17036 if( size/4<=1 ){
17037 fprintf(out, "%p size error\n", &mem3.aPool[i]);
17038 assert( 0 );
17039 break;
17041 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
17042 fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
17043 assert( 0 );
17044 break;
17046 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
17047 fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
17048 assert( 0 );
17049 break;
17051 if( size&1 ){
17052 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
17053 }else{
17054 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
17055 i==mem3.iMaster ? " **master**" : "");
17058 for(i=0; i<MX_SMALL-1; i++){
17059 if( mem3.aiSmall[i]==0 ) continue;
17060 fprintf(out, "small(%2d):", i);
17061 for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
17062 fprintf(out, " %p(%d)", &mem3.aPool[j],
17063 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17065 fprintf(out, "\n");
17067 for(i=0; i<N_HASH; i++){
17068 if( mem3.aiHash[i]==0 ) continue;
17069 fprintf(out, "hash(%2d):", i);
17070 for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
17071 fprintf(out, " %p(%d)", &mem3.aPool[j],
17072 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17074 fprintf(out, "\n");
17076 fprintf(out, "master=%d\n", mem3.iMaster);
17077 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
17078 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
17079 sqlite3_mutex_leave(mem3.mutex);
17080 if( out==stdout ){
17081 fflush(stdout);
17082 }else{
17083 fclose(out);
17085 #else
17086 UNUSED_PARAMETER(zFilename);
17087 #endif
17091 ** This routine is the only routine in this file with external
17092 ** linkage.
17094 ** Populate the low-level memory allocation function pointers in
17095 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
17096 ** arguments specify the block of memory to manage.
17098 ** This routine is only called by sqlite3_config(), and therefore
17099 ** is not required to be threadsafe (it is not).
17101 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
17102 static const sqlite3_mem_methods mempoolMethods = {
17103 memsys3Malloc,
17104 memsys3Free,
17105 memsys3Realloc,
17106 memsys3Size,
17107 memsys3Roundup,
17108 memsys3Init,
17109 memsys3Shutdown,
17112 return &mempoolMethods;
17115 #endif /* SQLITE_ENABLE_MEMSYS3 */
17117 /************** End of mem3.c ************************************************/
17118 /************** Begin file mem5.c ********************************************/
17120 ** 2007 October 14
17122 ** The author disclaims copyright to this source code. In place of
17123 ** a legal notice, here is a blessing:
17125 ** May you do good and not evil.
17126 ** May you find forgiveness for yourself and forgive others.
17127 ** May you share freely, never taking more than you give.
17129 *************************************************************************
17130 ** This file contains the C functions that implement a memory
17131 ** allocation subsystem for use by SQLite.
17133 ** This version of the memory allocation subsystem omits all
17134 ** use of malloc(). The application gives SQLite a block of memory
17135 ** before calling sqlite3_initialize() from which allocations
17136 ** are made and returned by the xMalloc() and xRealloc()
17137 ** implementations. Once sqlite3_initialize() has been called,
17138 ** the amount of memory available to SQLite is fixed and cannot
17139 ** be changed.
17141 ** This version of the memory allocation subsystem is included
17142 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
17144 ** This memory allocator uses the following algorithm:
17146 ** 1. All memory allocations sizes are rounded up to a power of 2.
17148 ** 2. If two adjacent free blocks are the halves of a larger block,
17149 ** then the two blocks are coalesed into the single larger block.
17151 ** 3. New memory is allocated from the first available free block.
17153 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
17154 ** Concerning Dynamic Storage Allocation". Journal of the Association for
17155 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
17157 ** Let n be the size of the largest allocation divided by the minimum
17158 ** allocation size (after rounding all sizes up to a power of 2.) Let M
17159 ** be the maximum amount of memory ever outstanding at one time. Let
17160 ** N be the total amount of memory available for allocation. Robson
17161 ** proved that this memory allocator will never breakdown due to
17162 ** fragmentation as long as the following constraint holds:
17164 ** N >= M*(1 + log2(n)/2) - n + 1
17166 ** The sqlite3_status() logic tracks the maximum values of n and M so
17167 ** that an application can, at any time, verify this constraint.
17171 ** This version of the memory allocator is used only when
17172 ** SQLITE_ENABLE_MEMSYS5 is defined.
17174 #ifdef SQLITE_ENABLE_MEMSYS5
17177 ** A minimum allocation is an instance of the following structure.
17178 ** Larger allocations are an array of these structures where the
17179 ** size of the array is a power of 2.
17181 ** The size of this object must be a power of two. That fact is
17182 ** verified in memsys5Init().
17184 typedef struct Mem5Link Mem5Link;
17185 struct Mem5Link {
17186 int next; /* Index of next free chunk */
17187 int prev; /* Index of previous free chunk */
17191 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
17192 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
17193 ** it is not actually possible to reach this limit.
17195 #define LOGMAX 30
17198 ** Masks used for mem5.aCtrl[] elements.
17200 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
17201 #define CTRL_FREE 0x20 /* True if not checked out */
17204 ** All of the static variables used by this module are collected
17205 ** into a single structure named "mem5". This is to keep the
17206 ** static variables organized and to reduce namespace pollution
17207 ** when this module is combined with other in the amalgamation.
17209 static SQLITE_WSD struct Mem5Global {
17211 ** Memory available for allocation
17213 int szAtom; /* Smallest possible allocation in bytes */
17214 int nBlock; /* Number of szAtom sized blocks in zPool */
17215 u8 *zPool; /* Memory available to be allocated */
17218 ** Mutex to control access to the memory allocation subsystem.
17220 sqlite3_mutex *mutex;
17223 ** Performance statistics
17225 u64 nAlloc; /* Total number of calls to malloc */
17226 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
17227 u64 totalExcess; /* Total internal fragmentation */
17228 u32 currentOut; /* Current checkout, including internal fragmentation */
17229 u32 currentCount; /* Current number of distinct checkouts */
17230 u32 maxOut; /* Maximum instantaneous currentOut */
17231 u32 maxCount; /* Maximum instantaneous currentCount */
17232 u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
17235 ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
17236 ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
17237 ** and so forth.
17239 int aiFreelist[LOGMAX+1];
17242 ** Space for tracking which blocks are checked out and the size
17243 ** of each block. One byte per block.
17245 u8 *aCtrl;
17247 } mem5;
17250 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
17252 #define mem5 GLOBAL(struct Mem5Global, mem5)
17255 ** Assuming mem5.zPool is divided up into an array of Mem5Link
17256 ** structures, return a pointer to the idx-th such link.
17258 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
17261 ** Unlink the chunk at mem5.aPool[i] from list it is currently
17262 ** on. It should be found on mem5.aiFreelist[iLogsize].
17264 static void memsys5Unlink(int i, int iLogsize){
17265 int next, prev;
17266 assert( i>=0 && i<mem5.nBlock );
17267 assert( iLogsize>=0 && iLogsize<=LOGMAX );
17268 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17270 next = MEM5LINK(i)->next;
17271 prev = MEM5LINK(i)->prev;
17272 if( prev<0 ){
17273 mem5.aiFreelist[iLogsize] = next;
17274 }else{
17275 MEM5LINK(prev)->next = next;
17277 if( next>=0 ){
17278 MEM5LINK(next)->prev = prev;
17283 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
17284 ** free list.
17286 static void memsys5Link(int i, int iLogsize){
17287 int x;
17288 assert( sqlite3_mutex_held(mem5.mutex) );
17289 assert( i>=0 && i<mem5.nBlock );
17290 assert( iLogsize>=0 && iLogsize<=LOGMAX );
17291 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17293 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
17294 MEM5LINK(i)->prev = -1;
17295 if( x>=0 ){
17296 assert( x<mem5.nBlock );
17297 MEM5LINK(x)->prev = i;
17299 mem5.aiFreelist[iLogsize] = i;
17303 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17304 ** will already be held (obtained by code in malloc.c) if
17305 ** sqlite3GlobalConfig.bMemStat is true.
17307 static void memsys5Enter(void){
17308 sqlite3_mutex_enter(mem5.mutex);
17310 static void memsys5Leave(void){
17311 sqlite3_mutex_leave(mem5.mutex);
17315 ** Return the size of an outstanding allocation, in bytes. The
17316 ** size returned omits the 8-byte header overhead. This only
17317 ** works for chunks that are currently checked out.
17319 static int memsys5Size(void *p){
17320 int iSize = 0;
17321 if( p ){
17322 int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
17323 assert( i>=0 && i<mem5.nBlock );
17324 iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
17326 return iSize;
17330 ** Find the first entry on the freelist iLogsize. Unlink that
17331 ** entry and return its index.
17333 static int memsys5UnlinkFirst(int iLogsize){
17334 int i;
17335 int iFirst;
17337 assert( iLogsize>=0 && iLogsize<=LOGMAX );
17338 i = iFirst = mem5.aiFreelist[iLogsize];
17339 assert( iFirst>=0 );
17340 while( i>0 ){
17341 if( i<iFirst ) iFirst = i;
17342 i = MEM5LINK(i)->next;
17344 memsys5Unlink(iFirst, iLogsize);
17345 return iFirst;
17349 ** Return a block of memory of at least nBytes in size.
17350 ** Return NULL if unable. Return NULL if nBytes==0.
17352 ** The caller guarantees that nByte is positive.
17354 ** The caller has obtained a mutex prior to invoking this
17355 ** routine so there is never any chance that two or more
17356 ** threads can be in this routine at the same time.
17358 static void *memsys5MallocUnsafe(int nByte){
17359 int i; /* Index of a mem5.aPool[] slot */
17360 int iBin; /* Index into mem5.aiFreelist[] */
17361 int iFullSz; /* Size of allocation rounded up to power of 2 */
17362 int iLogsize; /* Log2 of iFullSz/POW2_MIN */
17364 /* nByte must be a positive */
17365 assert( nByte>0 );
17367 /* Keep track of the maximum allocation request. Even unfulfilled
17368 ** requests are counted */
17369 if( (u32)nByte>mem5.maxRequest ){
17370 mem5.maxRequest = nByte;
17373 /* Abort if the requested allocation size is larger than the largest
17374 ** power of two that we can represent using 32-bit signed integers.
17376 if( nByte > 0x40000000 ){
17377 return 0;
17380 /* Round nByte up to the next valid power of two */
17381 for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17383 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17384 ** block. If not, then split a block of the next larger power of
17385 ** two in order to create a new free block of size iLogsize.
17387 for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
17388 if( iBin>LOGMAX ){
17389 testcase( sqlite3GlobalConfig.xLog!=0 );
17390 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17391 return 0;
17393 i = memsys5UnlinkFirst(iBin);
17394 while( iBin>iLogsize ){
17395 int newSize;
17397 iBin--;
17398 newSize = 1 << iBin;
17399 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
17400 memsys5Link(i+newSize, iBin);
17402 mem5.aCtrl[i] = iLogsize;
17404 /* Update allocator performance statistics. */
17405 mem5.nAlloc++;
17406 mem5.totalAlloc += iFullSz;
17407 mem5.totalExcess += iFullSz - nByte;
17408 mem5.currentCount++;
17409 mem5.currentOut += iFullSz;
17410 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
17411 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
17413 /* Return a pointer to the allocated memory. */
17414 return (void*)&mem5.zPool[i*mem5.szAtom];
17418 ** Free an outstanding memory allocation.
17420 static void memsys5FreeUnsafe(void *pOld){
17421 u32 size, iLogsize;
17422 int iBlock;
17424 /* Set iBlock to the index of the block pointed to by pOld in
17425 ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
17427 iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
17429 /* Check that the pointer pOld points to a valid, non-free block. */
17430 assert( iBlock>=0 && iBlock<mem5.nBlock );
17431 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
17432 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
17434 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
17435 size = 1<<iLogsize;
17436 assert( iBlock+size-1<(u32)mem5.nBlock );
17438 mem5.aCtrl[iBlock] |= CTRL_FREE;
17439 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
17440 assert( mem5.currentCount>0 );
17441 assert( mem5.currentOut>=(size*mem5.szAtom) );
17442 mem5.currentCount--;
17443 mem5.currentOut -= size*mem5.szAtom;
17444 assert( mem5.currentOut>0 || mem5.currentCount==0 );
17445 assert( mem5.currentCount>0 || mem5.currentOut==0 );
17447 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17448 while( ALWAYS(iLogsize<LOGMAX) ){
17449 int iBuddy;
17450 if( (iBlock>>iLogsize) & 1 ){
17451 iBuddy = iBlock - size;
17452 }else{
17453 iBuddy = iBlock + size;
17455 assert( iBuddy>=0 );
17456 if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17457 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17458 memsys5Unlink(iBuddy, iLogsize);
17459 iLogsize++;
17460 if( iBuddy<iBlock ){
17461 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17462 mem5.aCtrl[iBlock] = 0;
17463 iBlock = iBuddy;
17464 }else{
17465 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17466 mem5.aCtrl[iBuddy] = 0;
17468 size *= 2;
17470 memsys5Link(iBlock, iLogsize);
17474 ** Allocate nBytes of memory.
17476 static void *memsys5Malloc(int nBytes){
17477 sqlite3_int64 *p = 0;
17478 if( nBytes>0 ){
17479 memsys5Enter();
17480 p = memsys5MallocUnsafe(nBytes);
17481 memsys5Leave();
17483 return (void*)p;
17487 ** Free memory.
17489 ** The outer layer memory allocator prevents this routine from
17490 ** being called with pPrior==0.
17492 static void memsys5Free(void *pPrior){
17493 assert( pPrior!=0 );
17494 memsys5Enter();
17495 memsys5FreeUnsafe(pPrior);
17496 memsys5Leave();
17500 ** Change the size of an existing memory allocation.
17502 ** The outer layer memory allocator prevents this routine from
17503 ** being called with pPrior==0.
17505 ** nBytes is always a value obtained from a prior call to
17506 ** memsys5Round(). Hence nBytes is always a non-negative power
17507 ** of two. If nBytes==0 that means that an oversize allocation
17508 ** (an allocation larger than 0x40000000) was requested and this
17509 ** routine should return 0 without freeing pPrior.
17511 static void *memsys5Realloc(void *pPrior, int nBytes){
17512 int nOld;
17513 void *p;
17514 assert( pPrior!=0 );
17515 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
17516 assert( nBytes>=0 );
17517 if( nBytes==0 ){
17518 return 0;
17520 nOld = memsys5Size(pPrior);
17521 if( nBytes<=nOld ){
17522 return pPrior;
17524 memsys5Enter();
17525 p = memsys5MallocUnsafe(nBytes);
17526 if( p ){
17527 memcpy(p, pPrior, nOld);
17528 memsys5FreeUnsafe(pPrior);
17530 memsys5Leave();
17531 return p;
17535 ** Round up a request size to the next valid allocation size. If
17536 ** the allocation is too large to be handled by this allocation system,
17537 ** return 0.
17539 ** All allocations must be a power of two and must be expressed by a
17540 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
17541 ** or 1073741824 bytes.
17543 static int memsys5Roundup(int n){
17544 int iFullSz;
17545 if( n > 0x40000000 ) return 0;
17546 for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17547 return iFullSz;
17551 ** Return the ceiling of the logarithm base 2 of iValue.
17553 ** Examples: memsys5Log(1) -> 0
17554 ** memsys5Log(2) -> 1
17555 ** memsys5Log(4) -> 2
17556 ** memsys5Log(5) -> 3
17557 ** memsys5Log(8) -> 3
17558 ** memsys5Log(9) -> 4
17560 static int memsys5Log(int iValue){
17561 int iLog;
17562 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17563 return iLog;
17567 ** Initialize the memory allocator.
17569 ** This routine is not threadsafe. The caller must be holding a mutex
17570 ** to prevent multiple threads from entering at the same time.
17572 static int memsys5Init(void *NotUsed){
17573 int ii; /* Loop counter */
17574 int nByte; /* Number of bytes of memory available to this allocator */
17575 u8 *zByte; /* Memory usable by this allocator */
17576 int nMinLog; /* Log base 2 of minimum allocation size in bytes */
17577 int iOffset; /* An offset into mem5.aCtrl[] */
17579 UNUSED_PARAMETER(NotUsed);
17581 /* For the purposes of this routine, disable the mutex */
17582 mem5.mutex = 0;
17584 /* The size of a Mem5Link object must be a power of two. Verify that
17585 ** this is case.
17587 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17589 nByte = sqlite3GlobalConfig.nHeap;
17590 zByte = (u8*)sqlite3GlobalConfig.pHeap;
17591 assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
17593 /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17594 nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17595 mem5.szAtom = (1<<nMinLog);
17596 while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17597 mem5.szAtom = mem5.szAtom << 1;
17600 mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17601 mem5.zPool = zByte;
17602 mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17604 for(ii=0; ii<=LOGMAX; ii++){
17605 mem5.aiFreelist[ii] = -1;
17608 iOffset = 0;
17609 for(ii=LOGMAX; ii>=0; ii--){
17610 int nAlloc = (1<<ii);
17611 if( (iOffset+nAlloc)<=mem5.nBlock ){
17612 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17613 memsys5Link(iOffset, ii);
17614 iOffset += nAlloc;
17616 assert((iOffset+nAlloc)>mem5.nBlock);
17619 /* If a mutex is required for normal operation, allocate one */
17620 if( sqlite3GlobalConfig.bMemstat==0 ){
17621 mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17624 return SQLITE_OK;
17628 ** Deinitialize this module.
17630 static void memsys5Shutdown(void *NotUsed){
17631 UNUSED_PARAMETER(NotUsed);
17632 mem5.mutex = 0;
17633 return;
17636 #ifdef SQLITE_TEST
17638 ** Open the file indicated and write a log of all unfreed memory
17639 ** allocations into that log.
17641 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17642 FILE *out;
17643 int i, j, n;
17644 int nMinLog;
17646 if( zFilename==0 || zFilename[0]==0 ){
17647 out = stdout;
17648 }else{
17649 out = fopen(zFilename, "w");
17650 if( out==0 ){
17651 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17652 zFilename);
17653 return;
17656 memsys5Enter();
17657 nMinLog = memsys5Log(mem5.szAtom);
17658 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17659 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17660 fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17662 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
17663 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
17664 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
17665 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
17666 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17667 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
17668 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
17669 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
17670 memsys5Leave();
17671 if( out==stdout ){
17672 fflush(stdout);
17673 }else{
17674 fclose(out);
17677 #endif
17680 ** This routine is the only routine in this file with external
17681 ** linkage. It returns a pointer to a static sqlite3_mem_methods
17682 ** struct populated with the memsys5 methods.
17684 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17685 static const sqlite3_mem_methods memsys5Methods = {
17686 memsys5Malloc,
17687 memsys5Free,
17688 memsys5Realloc,
17689 memsys5Size,
17690 memsys5Roundup,
17691 memsys5Init,
17692 memsys5Shutdown,
17695 return &memsys5Methods;
17698 #endif /* SQLITE_ENABLE_MEMSYS5 */
17700 /************** End of mem5.c ************************************************/
17701 /************** Begin file mutex.c *******************************************/
17703 ** 2007 August 14
17705 ** The author disclaims copyright to this source code. In place of
17706 ** a legal notice, here is a blessing:
17708 ** May you do good and not evil.
17709 ** May you find forgiveness for yourself and forgive others.
17710 ** May you share freely, never taking more than you give.
17712 *************************************************************************
17713 ** This file contains the C functions that implement mutexes.
17715 ** This file contains code that is common across all mutex implementations.
17718 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17720 ** For debugging purposes, record when the mutex subsystem is initialized
17721 ** and uninitialized so that we can assert() if there is an attempt to
17722 ** allocate a mutex while the system is uninitialized.
17724 static SQLITE_WSD int mutexIsInit = 0;
17725 #endif /* SQLITE_DEBUG */
17728 #ifndef SQLITE_MUTEX_OMIT
17730 ** Initialize the mutex system.
17732 SQLITE_PRIVATE int sqlite3MutexInit(void){
17733 int rc = SQLITE_OK;
17734 if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17735 /* If the xMutexAlloc method has not been set, then the user did not
17736 ** install a mutex implementation via sqlite3_config() prior to
17737 ** sqlite3_initialize() being called. This block copies pointers to
17738 ** the default implementation into the sqlite3GlobalConfig structure.
17740 sqlite3_mutex_methods const *pFrom;
17741 sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17743 if( sqlite3GlobalConfig.bCoreMutex ){
17744 pFrom = sqlite3DefaultMutex();
17745 }else{
17746 pFrom = sqlite3NoopMutex();
17748 memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17749 memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17750 sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17751 pTo->xMutexAlloc = pFrom->xMutexAlloc;
17753 rc = sqlite3GlobalConfig.mutex.xMutexInit();
17755 #ifdef SQLITE_DEBUG
17756 GLOBAL(int, mutexIsInit) = 1;
17757 #endif
17759 return rc;
17763 ** Shutdown the mutex system. This call frees resources allocated by
17764 ** sqlite3MutexInit().
17766 SQLITE_PRIVATE int sqlite3MutexEnd(void){
17767 int rc = SQLITE_OK;
17768 if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17769 rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17772 #ifdef SQLITE_DEBUG
17773 GLOBAL(int, mutexIsInit) = 0;
17774 #endif
17776 return rc;
17780 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17782 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17783 #ifndef SQLITE_OMIT_AUTOINIT
17784 if( sqlite3_initialize() ) return 0;
17785 #endif
17786 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17789 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17790 if( !sqlite3GlobalConfig.bCoreMutex ){
17791 return 0;
17793 assert( GLOBAL(int, mutexIsInit) );
17794 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17798 ** Free a dynamic mutex.
17800 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17801 if( p ){
17802 sqlite3GlobalConfig.mutex.xMutexFree(p);
17807 ** Obtain the mutex p. If some other thread already has the mutex, block
17808 ** until it can be obtained.
17810 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
17811 if( p ){
17812 sqlite3GlobalConfig.mutex.xMutexEnter(p);
17817 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
17818 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
17820 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
17821 int rc = SQLITE_OK;
17822 if( p ){
17823 return sqlite3GlobalConfig.mutex.xMutexTry(p);
17825 return rc;
17829 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
17830 ** entered by the same thread. The behavior is undefined if the mutex
17831 ** is not currently entered. If a NULL pointer is passed as an argument
17832 ** this function is a no-op.
17834 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
17835 if( p ){
17836 sqlite3GlobalConfig.mutex.xMutexLeave(p);
17840 #ifndef NDEBUG
17842 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17843 ** intended for use inside assert() statements.
17845 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
17846 return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
17848 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
17849 return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
17851 #endif
17853 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17855 /************** End of mutex.c ***********************************************/
17856 /************** Begin file mutex_noop.c **************************************/
17858 ** 2008 October 07
17860 ** The author disclaims copyright to this source code. In place of
17861 ** a legal notice, here is a blessing:
17863 ** May you do good and not evil.
17864 ** May you find forgiveness for yourself and forgive others.
17865 ** May you share freely, never taking more than you give.
17867 *************************************************************************
17868 ** This file contains the C functions that implement mutexes.
17870 ** This implementation in this file does not provide any mutual
17871 ** exclusion and is thus suitable for use only in applications
17872 ** that use SQLite in a single thread. The routines defined
17873 ** here are place-holders. Applications can substitute working
17874 ** mutex routines at start-time using the
17876 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17878 ** interface.
17880 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
17881 ** that does error checking on mutexes to make sure they are being
17882 ** called correctly.
17885 #ifndef SQLITE_MUTEX_OMIT
17887 #ifndef SQLITE_DEBUG
17889 ** Stub routines for all mutex methods.
17891 ** This routines provide no mutual exclusion or error checking.
17893 static int noopMutexInit(void){ return SQLITE_OK; }
17894 static int noopMutexEnd(void){ return SQLITE_OK; }
17895 static sqlite3_mutex *noopMutexAlloc(int id){
17896 UNUSED_PARAMETER(id);
17897 return (sqlite3_mutex*)8;
17899 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17900 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17901 static int noopMutexTry(sqlite3_mutex *p){
17902 UNUSED_PARAMETER(p);
17903 return SQLITE_OK;
17905 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17907 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17908 static const sqlite3_mutex_methods sMutex = {
17909 noopMutexInit,
17910 noopMutexEnd,
17911 noopMutexAlloc,
17912 noopMutexFree,
17913 noopMutexEnter,
17914 noopMutexTry,
17915 noopMutexLeave,
17921 return &sMutex;
17923 #endif /* !SQLITE_DEBUG */
17925 #ifdef SQLITE_DEBUG
17927 ** In this implementation, error checking is provided for testing
17928 ** and debugging purposes. The mutexes still do not provide any
17929 ** mutual exclusion.
17933 ** The mutex object
17935 typedef struct sqlite3_debug_mutex {
17936 int id; /* The mutex type */
17937 int cnt; /* Number of entries without a matching leave */
17938 } sqlite3_debug_mutex;
17941 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17942 ** intended for use inside assert() statements.
17944 static int debugMutexHeld(sqlite3_mutex *pX){
17945 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17946 return p==0 || p->cnt>0;
17948 static int debugMutexNotheld(sqlite3_mutex *pX){
17949 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17950 return p==0 || p->cnt==0;
17954 ** Initialize and deinitialize the mutex subsystem.
17956 static int debugMutexInit(void){ return SQLITE_OK; }
17957 static int debugMutexEnd(void){ return SQLITE_OK; }
17960 ** The sqlite3_mutex_alloc() routine allocates a new
17961 ** mutex and returns a pointer to it. If it returns NULL
17962 ** that means that a mutex could not be allocated.
17964 static sqlite3_mutex *debugMutexAlloc(int id){
17965 static sqlite3_debug_mutex aStatic[6];
17966 sqlite3_debug_mutex *pNew = 0;
17967 switch( id ){
17968 case SQLITE_MUTEX_FAST:
17969 case SQLITE_MUTEX_RECURSIVE: {
17970 pNew = sqlite3Malloc(sizeof(*pNew));
17971 if( pNew ){
17972 pNew->id = id;
17973 pNew->cnt = 0;
17975 break;
17977 default: {
17978 assert( id-2 >= 0 );
17979 assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17980 pNew = &aStatic[id-2];
17981 pNew->id = id;
17982 break;
17985 return (sqlite3_mutex*)pNew;
17989 ** This routine deallocates a previously allocated mutex.
17991 static void debugMutexFree(sqlite3_mutex *pX){
17992 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17993 assert( p->cnt==0 );
17994 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17995 sqlite3_free(p);
17999 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18000 ** to enter a mutex. If another thread is already within the mutex,
18001 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18002 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
18003 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
18004 ** be entered multiple times by the same thread. In such cases the,
18005 ** mutex must be exited an equal number of times before another thread
18006 ** can enter. If the same thread tries to enter any other kind of mutex
18007 ** more than once, the behavior is undefined.
18009 static void debugMutexEnter(sqlite3_mutex *pX){
18010 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18011 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18012 p->cnt++;
18014 static int debugMutexTry(sqlite3_mutex *pX){
18015 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18016 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18017 p->cnt++;
18018 return SQLITE_OK;
18022 ** The sqlite3_mutex_leave() routine exits a mutex that was
18023 ** previously entered by the same thread. The behavior
18024 ** is undefined if the mutex is not currently entered or
18025 ** is not currently allocated. SQLite will never do either.
18027 static void debugMutexLeave(sqlite3_mutex *pX){
18028 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18029 assert( debugMutexHeld(pX) );
18030 p->cnt--;
18031 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18034 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18035 static const sqlite3_mutex_methods sMutex = {
18036 debugMutexInit,
18037 debugMutexEnd,
18038 debugMutexAlloc,
18039 debugMutexFree,
18040 debugMutexEnter,
18041 debugMutexTry,
18042 debugMutexLeave,
18044 debugMutexHeld,
18045 debugMutexNotheld
18048 return &sMutex;
18050 #endif /* SQLITE_DEBUG */
18053 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
18054 ** is used regardless of the run-time threadsafety setting.
18056 #ifdef SQLITE_MUTEX_NOOP
18057 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18058 return sqlite3NoopMutex();
18060 #endif /* defined(SQLITE_MUTEX_NOOP) */
18061 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18063 /************** End of mutex_noop.c ******************************************/
18064 /************** Begin file mutex_unix.c **************************************/
18066 ** 2007 August 28
18068 ** The author disclaims copyright to this source code. In place of
18069 ** a legal notice, here is a blessing:
18071 ** May you do good and not evil.
18072 ** May you find forgiveness for yourself and forgive others.
18073 ** May you share freely, never taking more than you give.
18075 *************************************************************************
18076 ** This file contains the C functions that implement mutexes for pthreads
18080 ** The code in this file is only used if we are compiling threadsafe
18081 ** under unix with pthreads.
18083 ** Note that this implementation requires a version of pthreads that
18084 ** supports recursive mutexes.
18086 #ifdef SQLITE_MUTEX_PTHREADS
18088 #include <pthread.h>
18091 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
18092 ** are necessary under two condidtions: (1) Debug builds and (2) using
18093 ** home-grown mutexes. Encapsulate these conditions into a single #define.
18095 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
18096 # define SQLITE_MUTEX_NREF 1
18097 #else
18098 # define SQLITE_MUTEX_NREF 0
18099 #endif
18102 ** Each recursive mutex is an instance of the following structure.
18104 struct sqlite3_mutex {
18105 pthread_mutex_t mutex; /* Mutex controlling the lock */
18106 #if SQLITE_MUTEX_NREF
18107 int id; /* Mutex type */
18108 volatile int nRef; /* Number of entrances */
18109 volatile pthread_t owner; /* Thread that is within this mutex */
18110 int trace; /* True to trace changes */
18111 #endif
18113 #if SQLITE_MUTEX_NREF
18114 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
18115 #else
18116 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
18117 #endif
18120 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18121 ** intended for use only inside assert() statements. On some platforms,
18122 ** there might be race conditions that can cause these routines to
18123 ** deliver incorrect results. In particular, if pthread_equal() is
18124 ** not an atomic operation, then these routines might delivery
18125 ** incorrect results. On most platforms, pthread_equal() is a
18126 ** comparison of two integers and is therefore atomic. But we are
18127 ** told that HPUX is not such a platform. If so, then these routines
18128 ** will not always work correctly on HPUX.
18130 ** On those platforms where pthread_equal() is not atomic, SQLite
18131 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
18132 ** make sure no assert() statements are evaluated and hence these
18133 ** routines are never called.
18135 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
18136 static int pthreadMutexHeld(sqlite3_mutex *p){
18137 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
18139 static int pthreadMutexNotheld(sqlite3_mutex *p){
18140 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
18142 #endif
18145 ** Initialize and deinitialize the mutex subsystem.
18147 static int pthreadMutexInit(void){ return SQLITE_OK; }
18148 static int pthreadMutexEnd(void){ return SQLITE_OK; }
18151 ** The sqlite3_mutex_alloc() routine allocates a new
18152 ** mutex and returns a pointer to it. If it returns NULL
18153 ** that means that a mutex could not be allocated. SQLite
18154 ** will unwind its stack and return an error. The argument
18155 ** to sqlite3_mutex_alloc() is one of these integer constants:
18157 ** <ul>
18158 ** <li> SQLITE_MUTEX_FAST
18159 ** <li> SQLITE_MUTEX_RECURSIVE
18160 ** <li> SQLITE_MUTEX_STATIC_MASTER
18161 ** <li> SQLITE_MUTEX_STATIC_MEM
18162 ** <li> SQLITE_MUTEX_STATIC_MEM2
18163 ** <li> SQLITE_MUTEX_STATIC_PRNG
18164 ** <li> SQLITE_MUTEX_STATIC_LRU
18165 ** <li> SQLITE_MUTEX_STATIC_PMEM
18166 ** </ul>
18168 ** The first two constants cause sqlite3_mutex_alloc() to create
18169 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18170 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18171 ** The mutex implementation does not need to make a distinction
18172 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18173 ** not want to. But SQLite will only request a recursive mutex in
18174 ** cases where it really needs one. If a faster non-recursive mutex
18175 ** implementation is available on the host platform, the mutex subsystem
18176 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18178 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18179 ** a pointer to a static preexisting mutex. Six static mutexes are
18180 ** used by the current version of SQLite. Future versions of SQLite
18181 ** may add additional static mutexes. Static mutexes are for internal
18182 ** use by SQLite only. Applications that use SQLite mutexes should
18183 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18184 ** SQLITE_MUTEX_RECURSIVE.
18186 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18187 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18188 ** returns a different mutex on every call. But for the static
18189 ** mutex types, the same mutex is returned on every call that has
18190 ** the same type number.
18192 static sqlite3_mutex *pthreadMutexAlloc(int iType){
18193 static sqlite3_mutex staticMutexes[] = {
18194 SQLITE3_MUTEX_INITIALIZER,
18195 SQLITE3_MUTEX_INITIALIZER,
18196 SQLITE3_MUTEX_INITIALIZER,
18197 SQLITE3_MUTEX_INITIALIZER,
18198 SQLITE3_MUTEX_INITIALIZER,
18199 SQLITE3_MUTEX_INITIALIZER
18201 sqlite3_mutex *p;
18202 switch( iType ){
18203 case SQLITE_MUTEX_RECURSIVE: {
18204 p = sqlite3MallocZero( sizeof(*p) );
18205 if( p ){
18206 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18207 /* If recursive mutexes are not available, we will have to
18208 ** build our own. See below. */
18209 pthread_mutex_init(&p->mutex, 0);
18210 #else
18211 /* Use a recursive mutex if it is available */
18212 pthread_mutexattr_t recursiveAttr;
18213 pthread_mutexattr_init(&recursiveAttr);
18214 pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18215 pthread_mutex_init(&p->mutex, &recursiveAttr);
18216 pthread_mutexattr_destroy(&recursiveAttr);
18217 #endif
18218 #if SQLITE_MUTEX_NREF
18219 p->id = iType;
18220 #endif
18222 break;
18224 case SQLITE_MUTEX_FAST: {
18225 p = sqlite3MallocZero( sizeof(*p) );
18226 if( p ){
18227 #if SQLITE_MUTEX_NREF
18228 p->id = iType;
18229 #endif
18230 pthread_mutex_init(&p->mutex, 0);
18232 break;
18234 default: {
18235 assert( iType-2 >= 0 );
18236 assert( iType-2 < ArraySize(staticMutexes) );
18237 p = &staticMutexes[iType-2];
18238 #if SQLITE_MUTEX_NREF
18239 p->id = iType;
18240 #endif
18241 break;
18244 return p;
18249 ** This routine deallocates a previously
18250 ** allocated mutex. SQLite is careful to deallocate every
18251 ** mutex that it allocates.
18253 static void pthreadMutexFree(sqlite3_mutex *p){
18254 assert( p->nRef==0 );
18255 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18256 pthread_mutex_destroy(&p->mutex);
18257 sqlite3_free(p);
18261 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18262 ** to enter a mutex. If another thread is already within the mutex,
18263 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18264 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
18265 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
18266 ** be entered multiple times by the same thread. In such cases the,
18267 ** mutex must be exited an equal number of times before another thread
18268 ** can enter. If the same thread tries to enter any other kind of mutex
18269 ** more than once, the behavior is undefined.
18271 static void pthreadMutexEnter(sqlite3_mutex *p){
18272 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18274 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18275 /* If recursive mutexes are not available, then we have to grow
18276 ** our own. This implementation assumes that pthread_equal()
18277 ** is atomic - that it cannot be deceived into thinking self
18278 ** and p->owner are equal if p->owner changes between two values
18279 ** that are not equal to self while the comparison is taking place.
18280 ** This implementation also assumes a coherent cache - that
18281 ** separate processes cannot read different values from the same
18282 ** address at the same time. If either of these two conditions
18283 ** are not met, then the mutexes will fail and problems will result.
18286 pthread_t self = pthread_self();
18287 if( p->nRef>0 && pthread_equal(p->owner, self) ){
18288 p->nRef++;
18289 }else{
18290 pthread_mutex_lock(&p->mutex);
18291 assert( p->nRef==0 );
18292 p->owner = self;
18293 p->nRef = 1;
18296 #else
18297 /* Use the built-in recursive mutexes if they are available.
18299 pthread_mutex_lock(&p->mutex);
18300 #if SQLITE_MUTEX_NREF
18301 assert( p->nRef>0 || p->owner==0 );
18302 p->owner = pthread_self();
18303 p->nRef++;
18304 #endif
18305 #endif
18307 #ifdef SQLITE_DEBUG
18308 if( p->trace ){
18309 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18311 #endif
18313 static int pthreadMutexTry(sqlite3_mutex *p){
18314 int rc;
18315 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18317 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18318 /* If recursive mutexes are not available, then we have to grow
18319 ** our own. This implementation assumes that pthread_equal()
18320 ** is atomic - that it cannot be deceived into thinking self
18321 ** and p->owner are equal if p->owner changes between two values
18322 ** that are not equal to self while the comparison is taking place.
18323 ** This implementation also assumes a coherent cache - that
18324 ** separate processes cannot read different values from the same
18325 ** address at the same time. If either of these two conditions
18326 ** are not met, then the mutexes will fail and problems will result.
18329 pthread_t self = pthread_self();
18330 if( p->nRef>0 && pthread_equal(p->owner, self) ){
18331 p->nRef++;
18332 rc = SQLITE_OK;
18333 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18334 assert( p->nRef==0 );
18335 p->owner = self;
18336 p->nRef = 1;
18337 rc = SQLITE_OK;
18338 }else{
18339 rc = SQLITE_BUSY;
18342 #else
18343 /* Use the built-in recursive mutexes if they are available.
18345 if( pthread_mutex_trylock(&p->mutex)==0 ){
18346 #if SQLITE_MUTEX_NREF
18347 p->owner = pthread_self();
18348 p->nRef++;
18349 #endif
18350 rc = SQLITE_OK;
18351 }else{
18352 rc = SQLITE_BUSY;
18354 #endif
18356 #ifdef SQLITE_DEBUG
18357 if( rc==SQLITE_OK && p->trace ){
18358 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18360 #endif
18361 return rc;
18365 ** The sqlite3_mutex_leave() routine exits a mutex that was
18366 ** previously entered by the same thread. The behavior
18367 ** is undefined if the mutex is not currently entered or
18368 ** is not currently allocated. SQLite will never do either.
18370 static void pthreadMutexLeave(sqlite3_mutex *p){
18371 assert( pthreadMutexHeld(p) );
18372 #if SQLITE_MUTEX_NREF
18373 p->nRef--;
18374 if( p->nRef==0 ) p->owner = 0;
18375 #endif
18376 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18378 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18379 if( p->nRef==0 ){
18380 pthread_mutex_unlock(&p->mutex);
18382 #else
18383 pthread_mutex_unlock(&p->mutex);
18384 #endif
18386 #ifdef SQLITE_DEBUG
18387 if( p->trace ){
18388 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18390 #endif
18393 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18394 static const sqlite3_mutex_methods sMutex = {
18395 pthreadMutexInit,
18396 pthreadMutexEnd,
18397 pthreadMutexAlloc,
18398 pthreadMutexFree,
18399 pthreadMutexEnter,
18400 pthreadMutexTry,
18401 pthreadMutexLeave,
18402 #ifdef SQLITE_DEBUG
18403 pthreadMutexHeld,
18404 pthreadMutexNotheld
18405 #else
18408 #endif
18411 return &sMutex;
18414 #endif /* SQLITE_MUTEX_PTHREADS */
18416 /************** End of mutex_unix.c ******************************************/
18417 /************** Begin file mutex_w32.c ***************************************/
18419 ** 2007 August 14
18421 ** The author disclaims copyright to this source code. In place of
18422 ** a legal notice, here is a blessing:
18424 ** May you do good and not evil.
18425 ** May you find forgiveness for yourself and forgive others.
18426 ** May you share freely, never taking more than you give.
18428 *************************************************************************
18429 ** This file contains the C functions that implement mutexes for win32
18433 ** The code in this file is only used if we are compiling multithreaded
18434 ** on a win32 system.
18436 #ifdef SQLITE_MUTEX_W32
18439 ** Each recursive mutex is an instance of the following structure.
18441 struct sqlite3_mutex {
18442 CRITICAL_SECTION mutex; /* Mutex controlling the lock */
18443 int id; /* Mutex type */
18444 #ifdef SQLITE_DEBUG
18445 volatile int nRef; /* Number of enterances */
18446 volatile DWORD owner; /* Thread holding this mutex */
18447 int trace; /* True to trace changes */
18448 #endif
18450 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18451 #ifdef SQLITE_DEBUG
18452 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18453 #else
18454 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18455 #endif
18458 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18459 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
18461 ** Here is an interesting observation: Win95, Win98, and WinME lack
18462 ** the LockFileEx() API. But we can still statically link against that
18463 ** API as long as we don't call it win running Win95/98/ME. A call to
18464 ** this routine is used to determine if the host is Win95/98/ME or
18465 ** WinNT/2K/XP so that we will know whether or not we can safely call
18466 ** the LockFileEx() API.
18468 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18469 ** which is only available if your application was compiled with
18470 ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
18471 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
18472 ** this out as well.
18474 #if 0
18475 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
18476 # define mutexIsNT() (1)
18477 #else
18478 static int mutexIsNT(void){
18479 static int osType = 0;
18480 if( osType==0 ){
18481 OSVERSIONINFO sInfo;
18482 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18483 GetVersionEx(&sInfo);
18484 osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18486 return osType==2;
18488 #endif /* SQLITE_OS_WINCE */
18489 #endif
18491 #ifdef SQLITE_DEBUG
18493 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18494 ** intended for use only inside assert() statements.
18496 static int winMutexHeld(sqlite3_mutex *p){
18497 return p->nRef!=0 && p->owner==GetCurrentThreadId();
18499 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18500 return p->nRef==0 || p->owner!=tid;
18502 static int winMutexNotheld(sqlite3_mutex *p){
18503 DWORD tid = GetCurrentThreadId();
18504 return winMutexNotheld2(p, tid);
18506 #endif
18510 ** Initialize and deinitialize the mutex subsystem.
18512 static sqlite3_mutex winMutex_staticMutexes[6] = {
18513 SQLITE3_MUTEX_INITIALIZER,
18514 SQLITE3_MUTEX_INITIALIZER,
18515 SQLITE3_MUTEX_INITIALIZER,
18516 SQLITE3_MUTEX_INITIALIZER,
18517 SQLITE3_MUTEX_INITIALIZER,
18518 SQLITE3_MUTEX_INITIALIZER
18520 static int winMutex_isInit = 0;
18521 /* As winMutexInit() and winMutexEnd() are called as part
18522 ** of the sqlite3_initialize and sqlite3_shutdown()
18523 ** processing, the "interlocked" magic is probably not
18524 ** strictly necessary.
18526 static long winMutex_lock = 0;
18528 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
18530 static int winMutexInit(void){
18531 /* The first to increment to 1 does actual initialization */
18532 if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18533 int i;
18534 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18535 #if SQLITE_OS_WINRT
18536 InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
18537 #else
18538 InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18539 #endif
18541 winMutex_isInit = 1;
18542 }else{
18543 /* Someone else is in the process of initing the static mutexes */
18544 while( !winMutex_isInit ){
18545 sqlite3_win32_sleep(1);
18548 return SQLITE_OK;
18551 static int winMutexEnd(void){
18552 /* The first to decrement to 0 does actual shutdown
18553 ** (which should be the last to shutdown.) */
18554 if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18555 if( winMutex_isInit==1 ){
18556 int i;
18557 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18558 DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18560 winMutex_isInit = 0;
18563 return SQLITE_OK;
18567 ** The sqlite3_mutex_alloc() routine allocates a new
18568 ** mutex and returns a pointer to it. If it returns NULL
18569 ** that means that a mutex could not be allocated. SQLite
18570 ** will unwind its stack and return an error. The argument
18571 ** to sqlite3_mutex_alloc() is one of these integer constants:
18573 ** <ul>
18574 ** <li> SQLITE_MUTEX_FAST
18575 ** <li> SQLITE_MUTEX_RECURSIVE
18576 ** <li> SQLITE_MUTEX_STATIC_MASTER
18577 ** <li> SQLITE_MUTEX_STATIC_MEM
18578 ** <li> SQLITE_MUTEX_STATIC_MEM2
18579 ** <li> SQLITE_MUTEX_STATIC_PRNG
18580 ** <li> SQLITE_MUTEX_STATIC_LRU
18581 ** <li> SQLITE_MUTEX_STATIC_PMEM
18582 ** </ul>
18584 ** The first two constants cause sqlite3_mutex_alloc() to create
18585 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18586 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18587 ** The mutex implementation does not need to make a distinction
18588 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18589 ** not want to. But SQLite will only request a recursive mutex in
18590 ** cases where it really needs one. If a faster non-recursive mutex
18591 ** implementation is available on the host platform, the mutex subsystem
18592 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18594 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18595 ** a pointer to a static preexisting mutex. Six static mutexes are
18596 ** used by the current version of SQLite. Future versions of SQLite
18597 ** may add additional static mutexes. Static mutexes are for internal
18598 ** use by SQLite only. Applications that use SQLite mutexes should
18599 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18600 ** SQLITE_MUTEX_RECURSIVE.
18602 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18603 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18604 ** returns a different mutex on every call. But for the static
18605 ** mutex types, the same mutex is returned on every call that has
18606 ** the same type number.
18608 static sqlite3_mutex *winMutexAlloc(int iType){
18609 sqlite3_mutex *p;
18611 switch( iType ){
18612 case SQLITE_MUTEX_FAST:
18613 case SQLITE_MUTEX_RECURSIVE: {
18614 p = sqlite3MallocZero( sizeof(*p) );
18615 if( p ){
18616 #ifdef SQLITE_DEBUG
18617 p->id = iType;
18618 #endif
18619 #if SQLITE_OS_WINRT
18620 InitializeCriticalSectionEx(&p->mutex, 0, 0);
18621 #else
18622 InitializeCriticalSection(&p->mutex);
18623 #endif
18625 break;
18627 default: {
18628 assert( winMutex_isInit==1 );
18629 assert( iType-2 >= 0 );
18630 assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18631 p = &winMutex_staticMutexes[iType-2];
18632 #ifdef SQLITE_DEBUG
18633 p->id = iType;
18634 #endif
18635 break;
18638 return p;
18643 ** This routine deallocates a previously
18644 ** allocated mutex. SQLite is careful to deallocate every
18645 ** mutex that it allocates.
18647 static void winMutexFree(sqlite3_mutex *p){
18648 assert( p );
18649 assert( p->nRef==0 && p->owner==0 );
18650 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18651 DeleteCriticalSection(&p->mutex);
18652 sqlite3_free(p);
18656 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18657 ** to enter a mutex. If another thread is already within the mutex,
18658 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18659 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
18660 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
18661 ** be entered multiple times by the same thread. In such cases the,
18662 ** mutex must be exited an equal number of times before another thread
18663 ** can enter. If the same thread tries to enter any other kind of mutex
18664 ** more than once, the behavior is undefined.
18666 static void winMutexEnter(sqlite3_mutex *p){
18667 #ifdef SQLITE_DEBUG
18668 DWORD tid = GetCurrentThreadId();
18669 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18670 #endif
18671 EnterCriticalSection(&p->mutex);
18672 #ifdef SQLITE_DEBUG
18673 assert( p->nRef>0 || p->owner==0 );
18674 p->owner = tid;
18675 p->nRef++;
18676 if( p->trace ){
18677 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18679 #endif
18681 static int winMutexTry(sqlite3_mutex *p){
18682 #ifndef NDEBUG
18683 DWORD tid = GetCurrentThreadId();
18684 #endif
18685 int rc = SQLITE_BUSY;
18686 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18688 ** The sqlite3_mutex_try() routine is very rarely used, and when it
18689 ** is used it is merely an optimization. So it is OK for it to always
18690 ** fail.
18692 ** The TryEnterCriticalSection() interface is only available on WinNT.
18693 ** And some windows compilers complain if you try to use it without
18694 ** first doing some #defines that prevent SQLite from building on Win98.
18695 ** For that reason, we will omit this optimization for now. See
18696 ** ticket #2685.
18698 #if 0
18699 if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18700 p->owner = tid;
18701 p->nRef++;
18702 rc = SQLITE_OK;
18704 #else
18705 UNUSED_PARAMETER(p);
18706 #endif
18707 #ifdef SQLITE_DEBUG
18708 if( rc==SQLITE_OK && p->trace ){
18709 printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18711 #endif
18712 return rc;
18716 ** The sqlite3_mutex_leave() routine exits a mutex that was
18717 ** previously entered by the same thread. The behavior
18718 ** is undefined if the mutex is not currently entered or
18719 ** is not currently allocated. SQLite will never do either.
18721 static void winMutexLeave(sqlite3_mutex *p){
18722 #ifndef NDEBUG
18723 DWORD tid = GetCurrentThreadId();
18724 assert( p->nRef>0 );
18725 assert( p->owner==tid );
18726 p->nRef--;
18727 if( p->nRef==0 ) p->owner = 0;
18728 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18729 #endif
18730 LeaveCriticalSection(&p->mutex);
18731 #ifdef SQLITE_DEBUG
18732 if( p->trace ){
18733 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18735 #endif
18738 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18739 static const sqlite3_mutex_methods sMutex = {
18740 winMutexInit,
18741 winMutexEnd,
18742 winMutexAlloc,
18743 winMutexFree,
18744 winMutexEnter,
18745 winMutexTry,
18746 winMutexLeave,
18747 #ifdef SQLITE_DEBUG
18748 winMutexHeld,
18749 winMutexNotheld
18750 #else
18753 #endif
18756 return &sMutex;
18758 #endif /* SQLITE_MUTEX_W32 */
18760 /************** End of mutex_w32.c *******************************************/
18761 /************** Begin file malloc.c ******************************************/
18763 ** 2001 September 15
18765 ** The author disclaims copyright to this source code. In place of
18766 ** a legal notice, here is a blessing:
18768 ** May you do good and not evil.
18769 ** May you find forgiveness for yourself and forgive others.
18770 ** May you share freely, never taking more than you give.
18772 *************************************************************************
18774 ** Memory allocation functions used throughout sqlite.
18776 /* #include <stdarg.h> */
18779 ** Attempt to release up to n bytes of non-essential memory currently
18780 ** held by SQLite. An example of non-essential memory is memory used to
18781 ** cache database pages that are not currently in use.
18783 SQLITE_API int sqlite3_release_memory(int n){
18784 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18785 return sqlite3PcacheReleaseMemory(n);
18786 #else
18787 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18788 ** is a no-op returning zero if SQLite is not compiled with
18789 ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18790 UNUSED_PARAMETER(n);
18791 return 0;
18792 #endif
18796 ** An instance of the following object records the location of
18797 ** each unused scratch buffer.
18799 typedef struct ScratchFreeslot {
18800 struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
18801 } ScratchFreeslot;
18804 ** State information local to the memory allocation subsystem.
18806 static SQLITE_WSD struct Mem0Global {
18807 sqlite3_mutex *mutex; /* Mutex to serialize access */
18810 ** The alarm callback and its arguments. The mem0.mutex lock will
18811 ** be held while the callback is running. Recursive calls into
18812 ** the memory subsystem are allowed, but no new callbacks will be
18813 ** issued.
18815 sqlite3_int64 alarmThreshold;
18816 void (*alarmCallback)(void*, sqlite3_int64,int);
18817 void *alarmArg;
18820 ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18821 ** (so that a range test can be used to determine if an allocation
18822 ** being freed came from pScratch) and a pointer to the list of
18823 ** unused scratch allocations.
18825 void *pScratchEnd;
18826 ScratchFreeslot *pScratchFree;
18827 u32 nScratchFree;
18830 ** True if heap is nearly "full" where "full" is defined by the
18831 ** sqlite3_soft_heap_limit() setting.
18833 int nearlyFull;
18834 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18836 #define mem0 GLOBAL(struct Mem0Global, mem0)
18839 ** This routine runs when the memory allocator sees that the
18840 ** total memory allocation is about to exceed the soft heap
18841 ** limit.
18843 static void softHeapLimitEnforcer(
18844 void *NotUsed,
18845 sqlite3_int64 NotUsed2,
18846 int allocSize
18848 UNUSED_PARAMETER2(NotUsed, NotUsed2);
18849 sqlite3_release_memory(allocSize);
18853 ** Change the alarm callback
18855 static int sqlite3MemoryAlarm(
18856 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18857 void *pArg,
18858 sqlite3_int64 iThreshold
18860 int nUsed;
18861 sqlite3_mutex_enter(mem0.mutex);
18862 mem0.alarmCallback = xCallback;
18863 mem0.alarmArg = pArg;
18864 mem0.alarmThreshold = iThreshold;
18865 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18866 mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18867 sqlite3_mutex_leave(mem0.mutex);
18868 return SQLITE_OK;
18871 #ifndef SQLITE_OMIT_DEPRECATED
18873 ** Deprecated external interface. Internal/core SQLite code
18874 ** should call sqlite3MemoryAlarm.
18876 SQLITE_API int sqlite3_memory_alarm(
18877 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18878 void *pArg,
18879 sqlite3_int64 iThreshold
18881 return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18883 #endif
18886 ** Set the soft heap-size limit for the library. Passing a zero or
18887 ** negative value indicates no limit.
18889 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18890 sqlite3_int64 priorLimit;
18891 sqlite3_int64 excess;
18892 #ifndef SQLITE_OMIT_AUTOINIT
18893 int rc = sqlite3_initialize();
18894 if( rc ) return -1;
18895 #endif
18896 sqlite3_mutex_enter(mem0.mutex);
18897 priorLimit = mem0.alarmThreshold;
18898 sqlite3_mutex_leave(mem0.mutex);
18899 if( n<0 ) return priorLimit;
18900 if( n>0 ){
18901 sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18902 }else{
18903 sqlite3MemoryAlarm(0, 0, 0);
18905 excess = sqlite3_memory_used() - n;
18906 if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18907 return priorLimit;
18909 SQLITE_API void sqlite3_soft_heap_limit(int n){
18910 if( n<0 ) n = 0;
18911 sqlite3_soft_heap_limit64(n);
18915 ** Initialize the memory allocation subsystem.
18917 SQLITE_PRIVATE int sqlite3MallocInit(void){
18918 if( sqlite3GlobalConfig.m.xMalloc==0 ){
18919 sqlite3MemSetDefault();
18921 memset(&mem0, 0, sizeof(mem0));
18922 if( sqlite3GlobalConfig.bCoreMutex ){
18923 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18925 if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18926 && sqlite3GlobalConfig.nScratch>0 ){
18927 int i, n, sz;
18928 ScratchFreeslot *pSlot;
18929 sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18930 sqlite3GlobalConfig.szScratch = sz;
18931 pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18932 n = sqlite3GlobalConfig.nScratch;
18933 mem0.pScratchFree = pSlot;
18934 mem0.nScratchFree = n;
18935 for(i=0; i<n-1; i++){
18936 pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18937 pSlot = pSlot->pNext;
18939 pSlot->pNext = 0;
18940 mem0.pScratchEnd = (void*)&pSlot[1];
18941 }else{
18942 mem0.pScratchEnd = 0;
18943 sqlite3GlobalConfig.pScratch = 0;
18944 sqlite3GlobalConfig.szScratch = 0;
18945 sqlite3GlobalConfig.nScratch = 0;
18947 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18948 || sqlite3GlobalConfig.nPage<1 ){
18949 sqlite3GlobalConfig.pPage = 0;
18950 sqlite3GlobalConfig.szPage = 0;
18951 sqlite3GlobalConfig.nPage = 0;
18953 return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18957 ** Return true if the heap is currently under memory pressure - in other
18958 ** words if the amount of heap used is close to the limit set by
18959 ** sqlite3_soft_heap_limit().
18961 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18962 return mem0.nearlyFull;
18966 ** Deinitialize the memory allocation subsystem.
18968 SQLITE_PRIVATE void sqlite3MallocEnd(void){
18969 if( sqlite3GlobalConfig.m.xShutdown ){
18970 sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18972 memset(&mem0, 0, sizeof(mem0));
18976 ** Return the amount of memory currently checked out.
18978 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18979 int n, mx;
18980 sqlite3_int64 res;
18981 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18982 res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
18983 return res;
18987 ** Return the maximum amount of memory that has ever been
18988 ** checked out since either the beginning of this process
18989 ** or since the most recent reset.
18991 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18992 int n, mx;
18993 sqlite3_int64 res;
18994 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18995 res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
18996 return res;
19000 ** Trigger the alarm
19002 static void sqlite3MallocAlarm(int nByte){
19003 void (*xCallback)(void*,sqlite3_int64,int);
19004 sqlite3_int64 nowUsed;
19005 void *pArg;
19006 if( mem0.alarmCallback==0 ) return;
19007 xCallback = mem0.alarmCallback;
19008 nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19009 pArg = mem0.alarmArg;
19010 mem0.alarmCallback = 0;
19011 sqlite3_mutex_leave(mem0.mutex);
19012 xCallback(pArg, nowUsed, nByte);
19013 sqlite3_mutex_enter(mem0.mutex);
19014 mem0.alarmCallback = xCallback;
19015 mem0.alarmArg = pArg;
19019 ** Do a memory allocation with statistics and alarms. Assume the
19020 ** lock is already held.
19022 static int mallocWithAlarm(int n, void **pp){
19023 int nFull;
19024 void *p;
19025 assert( sqlite3_mutex_held(mem0.mutex) );
19026 nFull = sqlite3GlobalConfig.m.xRoundup(n);
19027 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
19028 if( mem0.alarmCallback!=0 ){
19029 int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19030 if( nUsed >= mem0.alarmThreshold - nFull ){
19031 mem0.nearlyFull = 1;
19032 sqlite3MallocAlarm(nFull);
19033 }else{
19034 mem0.nearlyFull = 0;
19037 p = sqlite3GlobalConfig.m.xMalloc(nFull);
19038 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19039 if( p==0 && mem0.alarmCallback ){
19040 sqlite3MallocAlarm(nFull);
19041 p = sqlite3GlobalConfig.m.xMalloc(nFull);
19043 #endif
19044 if( p ){
19045 nFull = sqlite3MallocSize(p);
19046 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
19047 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
19049 *pp = p;
19050 return nFull;
19054 ** Allocate memory. This routine is like sqlite3_malloc() except that it
19055 ** assumes the memory subsystem has already been initialized.
19057 SQLITE_PRIVATE void *sqlite3Malloc(int n){
19058 void *p;
19059 if( n<=0 /* IMP: R-65312-04917 */
19060 || n>=0x7fffff00
19062 /* A memory allocation of a number of bytes which is near the maximum
19063 ** signed integer value might cause an integer overflow inside of the
19064 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
19065 ** 255 bytes of overhead. SQLite itself will never use anything near
19066 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
19067 p = 0;
19068 }else if( sqlite3GlobalConfig.bMemstat ){
19069 sqlite3_mutex_enter(mem0.mutex);
19070 mallocWithAlarm(n, &p);
19071 sqlite3_mutex_leave(mem0.mutex);
19072 }else{
19073 p = sqlite3GlobalConfig.m.xMalloc(n);
19075 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
19076 return p;
19080 ** This version of the memory allocation is for use by the application.
19081 ** First make sure the memory subsystem is initialized, then do the
19082 ** allocation.
19084 SQLITE_API void *sqlite3_malloc(int n){
19085 #ifndef SQLITE_OMIT_AUTOINIT
19086 if( sqlite3_initialize() ) return 0;
19087 #endif
19088 return sqlite3Malloc(n);
19092 ** Each thread may only have a single outstanding allocation from
19093 ** xScratchMalloc(). We verify this constraint in the single-threaded
19094 ** case by setting scratchAllocOut to 1 when an allocation
19095 ** is outstanding clearing it when the allocation is freed.
19097 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19098 static int scratchAllocOut = 0;
19099 #endif
19103 ** Allocate memory that is to be used and released right away.
19104 ** This routine is similar to alloca() in that it is not intended
19105 ** for situations where the memory might be held long-term. This
19106 ** routine is intended to get memory to old large transient data
19107 ** structures that would not normally fit on the stack of an
19108 ** embedded processor.
19110 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
19111 void *p;
19112 assert( n>0 );
19114 sqlite3_mutex_enter(mem0.mutex);
19115 if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
19116 p = mem0.pScratchFree;
19117 mem0.pScratchFree = mem0.pScratchFree->pNext;
19118 mem0.nScratchFree--;
19119 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
19120 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19121 sqlite3_mutex_leave(mem0.mutex);
19122 }else{
19123 if( sqlite3GlobalConfig.bMemstat ){
19124 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19125 n = mallocWithAlarm(n, &p);
19126 if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
19127 sqlite3_mutex_leave(mem0.mutex);
19128 }else{
19129 sqlite3_mutex_leave(mem0.mutex);
19130 p = sqlite3GlobalConfig.m.xMalloc(n);
19132 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
19134 assert( sqlite3_mutex_notheld(mem0.mutex) );
19137 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19138 /* Verify that no more than two scratch allocations per thread
19139 ** are outstanding at one time. (This is only checked in the
19140 ** single-threaded case since checking in the multi-threaded case
19141 ** would be much more complicated.) */
19142 assert( scratchAllocOut<=1 );
19143 if( p ) scratchAllocOut++;
19144 #endif
19146 return p;
19148 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
19149 if( p ){
19151 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19152 /* Verify that no more than two scratch allocation per thread
19153 ** is outstanding at one time. (This is only checked in the
19154 ** single-threaded case since checking in the multi-threaded case
19155 ** would be much more complicated.) */
19156 assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
19157 scratchAllocOut--;
19158 #endif
19160 if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
19161 /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
19162 ScratchFreeslot *pSlot;
19163 pSlot = (ScratchFreeslot*)p;
19164 sqlite3_mutex_enter(mem0.mutex);
19165 pSlot->pNext = mem0.pScratchFree;
19166 mem0.pScratchFree = pSlot;
19167 mem0.nScratchFree++;
19168 assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
19169 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
19170 sqlite3_mutex_leave(mem0.mutex);
19171 }else{
19172 /* Release memory back to the heap */
19173 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
19174 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19175 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19176 if( sqlite3GlobalConfig.bMemstat ){
19177 int iSize = sqlite3MallocSize(p);
19178 sqlite3_mutex_enter(mem0.mutex);
19179 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19180 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19181 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19182 sqlite3GlobalConfig.m.xFree(p);
19183 sqlite3_mutex_leave(mem0.mutex);
19184 }else{
19185 sqlite3GlobalConfig.m.xFree(p);
19192 ** TRUE if p is a lookaside memory allocation from db
19194 #ifndef SQLITE_OMIT_LOOKASIDE
19195 static int isLookaside(sqlite3 *db, void *p){
19196 return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19198 #else
19199 #define isLookaside(A,B) 0
19200 #endif
19203 ** Return the size of a memory allocation previously obtained from
19204 ** sqlite3Malloc() or sqlite3_malloc().
19206 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19207 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19208 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19209 return sqlite3GlobalConfig.m.xSize(p);
19211 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19212 assert( db==0 || sqlite3_mutex_held(db->mutex) );
19213 if( db && isLookaside(db, p) ){
19214 return db->lookaside.sz;
19215 }else{
19216 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19217 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19218 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19219 return sqlite3GlobalConfig.m.xSize(p);
19224 ** Free memory previously obtained from sqlite3Malloc().
19226 SQLITE_API void sqlite3_free(void *p){
19227 if( p==0 ) return; /* IMP: R-49053-54554 */
19228 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19229 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19230 if( sqlite3GlobalConfig.bMemstat ){
19231 sqlite3_mutex_enter(mem0.mutex);
19232 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19233 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19234 sqlite3GlobalConfig.m.xFree(p);
19235 sqlite3_mutex_leave(mem0.mutex);
19236 }else{
19237 sqlite3GlobalConfig.m.xFree(p);
19242 ** Free memory that might be associated with a particular database
19243 ** connection.
19245 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19246 assert( db==0 || sqlite3_mutex_held(db->mutex) );
19247 if( db ){
19248 if( db->pnBytesFreed ){
19249 *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19250 return;
19252 if( isLookaside(db, p) ){
19253 LookasideSlot *pBuf = (LookasideSlot*)p;
19254 #if SQLITE_DEBUG
19255 /* Trash all content in the buffer being freed */
19256 memset(p, 0xaa, db->lookaside.sz);
19257 #endif
19258 pBuf->pNext = db->lookaside.pFree;
19259 db->lookaside.pFree = pBuf;
19260 db->lookaside.nOut--;
19261 return;
19264 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19265 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19266 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19267 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19268 sqlite3_free(p);
19272 ** Change the size of an existing memory allocation
19274 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19275 int nOld, nNew, nDiff;
19276 void *pNew;
19277 if( pOld==0 ){
19278 return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19280 if( nBytes<=0 ){
19281 sqlite3_free(pOld); /* IMP: R-31593-10574 */
19282 return 0;
19284 if( nBytes>=0x7fffff00 ){
19285 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19286 return 0;
19288 nOld = sqlite3MallocSize(pOld);
19289 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19290 ** argument to xRealloc is always a value returned by a prior call to
19291 ** xRoundup. */
19292 nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19293 if( nOld==nNew ){
19294 pNew = pOld;
19295 }else if( sqlite3GlobalConfig.bMemstat ){
19296 sqlite3_mutex_enter(mem0.mutex);
19297 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19298 nDiff = nNew - nOld;
19299 if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
19300 mem0.alarmThreshold-nDiff ){
19301 sqlite3MallocAlarm(nDiff);
19303 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19304 assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19305 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19306 if( pNew==0 && mem0.alarmCallback ){
19307 sqlite3MallocAlarm(nBytes);
19308 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19310 if( pNew ){
19311 nNew = sqlite3MallocSize(pNew);
19312 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19314 sqlite3_mutex_leave(mem0.mutex);
19315 }else{
19316 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19318 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19319 return pNew;
19323 ** The public interface to sqlite3Realloc. Make sure that the memory
19324 ** subsystem is initialized prior to invoking sqliteRealloc.
19326 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19327 #ifndef SQLITE_OMIT_AUTOINIT
19328 if( sqlite3_initialize() ) return 0;
19329 #endif
19330 return sqlite3Realloc(pOld, n);
19335 ** Allocate and zero memory.
19337 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19338 void *p = sqlite3Malloc(n);
19339 if( p ){
19340 memset(p, 0, n);
19342 return p;
19346 ** Allocate and zero memory. If the allocation fails, make
19347 ** the mallocFailed flag in the connection pointer.
19349 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19350 void *p = sqlite3DbMallocRaw(db, n);
19351 if( p ){
19352 memset(p, 0, n);
19354 return p;
19358 ** Allocate and zero memory. If the allocation fails, make
19359 ** the mallocFailed flag in the connection pointer.
19361 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19362 ** failure on the same database connection) then always return 0.
19363 ** Hence for a particular database connection, once malloc starts
19364 ** failing, it fails consistently until mallocFailed is reset.
19365 ** This is an important assumption. There are many places in the
19366 ** code that do things like this:
19368 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
19369 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
19370 ** if( b ) a[10] = 9;
19372 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19373 ** that all prior mallocs (ex: "a") worked too.
19375 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19376 void *p;
19377 assert( db==0 || sqlite3_mutex_held(db->mutex) );
19378 assert( db==0 || db->pnBytesFreed==0 );
19379 #ifndef SQLITE_OMIT_LOOKASIDE
19380 if( db ){
19381 LookasideSlot *pBuf;
19382 if( db->mallocFailed ){
19383 return 0;
19385 if( db->lookaside.bEnabled ){
19386 if( n>db->lookaside.sz ){
19387 db->lookaside.anStat[1]++;
19388 }else if( (pBuf = db->lookaside.pFree)==0 ){
19389 db->lookaside.anStat[2]++;
19390 }else{
19391 db->lookaside.pFree = pBuf->pNext;
19392 db->lookaside.nOut++;
19393 db->lookaside.anStat[0]++;
19394 if( db->lookaside.nOut>db->lookaside.mxOut ){
19395 db->lookaside.mxOut = db->lookaside.nOut;
19397 return (void*)pBuf;
19401 #else
19402 if( db && db->mallocFailed ){
19403 return 0;
19405 #endif
19406 p = sqlite3Malloc(n);
19407 if( !p && db ){
19408 db->mallocFailed = 1;
19410 sqlite3MemdebugSetType(p, MEMTYPE_DB |
19411 ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19412 return p;
19416 ** Resize the block of memory pointed to by p to n bytes. If the
19417 ** resize fails, set the mallocFailed flag in the connection object.
19419 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19420 void *pNew = 0;
19421 assert( db!=0 );
19422 assert( sqlite3_mutex_held(db->mutex) );
19423 if( db->mallocFailed==0 ){
19424 if( p==0 ){
19425 return sqlite3DbMallocRaw(db, n);
19427 if( isLookaside(db, p) ){
19428 if( n<=db->lookaside.sz ){
19429 return p;
19431 pNew = sqlite3DbMallocRaw(db, n);
19432 if( pNew ){
19433 memcpy(pNew, p, db->lookaside.sz);
19434 sqlite3DbFree(db, p);
19436 }else{
19437 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19438 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19439 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19440 pNew = sqlite3_realloc(p, n);
19441 if( !pNew ){
19442 sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19443 db->mallocFailed = 1;
19445 sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
19446 (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19449 return pNew;
19453 ** Attempt to reallocate p. If the reallocation fails, then free p
19454 ** and set the mallocFailed flag in the database connection.
19456 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19457 void *pNew;
19458 pNew = sqlite3DbRealloc(db, p, n);
19459 if( !pNew ){
19460 sqlite3DbFree(db, p);
19462 return pNew;
19466 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
19467 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19468 ** is because when memory debugging is turned on, these two functions are
19469 ** called via macros that record the current file and line number in the
19470 ** ThreadData structure.
19472 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19473 char *zNew;
19474 size_t n;
19475 if( z==0 ){
19476 return 0;
19478 n = sqlite3Strlen30(z) + 1;
19479 assert( (n&0x7fffffff)==n );
19480 zNew = sqlite3DbMallocRaw(db, (int)n);
19481 if( zNew ){
19482 memcpy(zNew, z, n);
19484 return zNew;
19486 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19487 char *zNew;
19488 if( z==0 ){
19489 return 0;
19491 assert( (n&0x7fffffff)==n );
19492 zNew = sqlite3DbMallocRaw(db, n+1);
19493 if( zNew ){
19494 memcpy(zNew, z, n);
19495 zNew[n] = 0;
19497 return zNew;
19501 ** Create a string from the zFromat argument and the va_list that follows.
19502 ** Store the string in memory obtained from sqliteMalloc() and make *pz
19503 ** point to that string.
19505 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19506 va_list ap;
19507 char *z;
19509 va_start(ap, zFormat);
19510 z = sqlite3VMPrintf(db, zFormat, ap);
19511 va_end(ap);
19512 sqlite3DbFree(db, *pz);
19513 *pz = z;
19518 ** This function must be called before exiting any API function (i.e.
19519 ** returning control to the user) that has called sqlite3_malloc or
19520 ** sqlite3_realloc.
19522 ** The returned value is normally a copy of the second argument to this
19523 ** function. However, if a malloc() failure has occurred since the previous
19524 ** invocation SQLITE_NOMEM is returned instead.
19526 ** If the first argument, db, is not NULL and a malloc() error has occurred,
19527 ** then the connection error-code (the value returned by sqlite3_errcode())
19528 ** is set to SQLITE_NOMEM.
19530 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19531 /* If the db handle is not NULL, then we must hold the connection handle
19532 ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
19533 ** is unsafe, as is the call to sqlite3Error().
19535 assert( !db || sqlite3_mutex_held(db->mutex) );
19536 if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19537 sqlite3Error(db, SQLITE_NOMEM, 0);
19538 db->mallocFailed = 0;
19539 rc = SQLITE_NOMEM;
19541 return rc & (db ? db->errMask : 0xff);
19544 /************** End of malloc.c **********************************************/
19545 /************** Begin file printf.c ******************************************/
19547 ** The "printf" code that follows dates from the 1980's. It is in
19548 ** the public domain. The original comments are included here for
19549 ** completeness. They are very out-of-date but might be useful as
19550 ** an historical reference. Most of the "enhancements" have been backed
19551 ** out so that the functionality is now the same as standard printf().
19553 **************************************************************************
19555 ** This file contains code for a set of "printf"-like routines. These
19556 ** routines format strings much like the printf() from the standard C
19557 ** library, though the implementation here has enhancements to support
19558 ** SQLlite.
19562 ** Conversion types fall into various categories as defined by the
19563 ** following enumeration.
19565 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
19566 #define etFLOAT 2 /* Floating point. %f */
19567 #define etEXP 3 /* Exponentional notation. %e and %E */
19568 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
19569 #define etSIZE 5 /* Return number of characters processed so far. %n */
19570 #define etSTRING 6 /* Strings. %s */
19571 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
19572 #define etPERCENT 8 /* Percent symbol. %% */
19573 #define etCHARX 9 /* Characters. %c */
19574 /* The rest are extensions, not normally found in printf() */
19575 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
19576 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19577 NULL pointers replaced by SQL NULL. %Q */
19578 #define etTOKEN 12 /* a pointer to a Token structure */
19579 #define etSRCLIST 13 /* a pointer to a SrcList */
19580 #define etPOINTER 14 /* The %p conversion */
19581 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19582 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
19584 #define etINVALID 0 /* Any unrecognized conversion type */
19588 ** An "etByte" is an 8-bit unsigned value.
19590 typedef unsigned char etByte;
19593 ** Each builtin conversion character (ex: the 'd' in "%d") is described
19594 ** by an instance of the following structure
19596 typedef struct et_info { /* Information about each format field */
19597 char fmttype; /* The format field code letter */
19598 etByte base; /* The base for radix conversion */
19599 etByte flags; /* One or more of FLAG_ constants below */
19600 etByte type; /* Conversion paradigm */
19601 etByte charset; /* Offset into aDigits[] of the digits string */
19602 etByte prefix; /* Offset into aPrefix[] of the prefix string */
19603 } et_info;
19606 ** Allowed values for et_info.flags
19608 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
19609 #define FLAG_INTERN 2 /* True if for internal use only */
19610 #define FLAG_STRING 4 /* Allow infinity precision */
19614 ** The following table is searched linearly, so it is good to put the
19615 ** most frequently used conversion types first.
19617 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19618 static const char aPrefix[] = "-x0\000X0";
19619 static const et_info fmtinfo[] = {
19620 { 'd', 10, 1, etRADIX, 0, 0 },
19621 { 's', 0, 4, etSTRING, 0, 0 },
19622 { 'g', 0, 1, etGENERIC, 30, 0 },
19623 { 'z', 0, 4, etDYNSTRING, 0, 0 },
19624 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
19625 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
19626 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
19627 { 'c', 0, 0, etCHARX, 0, 0 },
19628 { 'o', 8, 0, etRADIX, 0, 2 },
19629 { 'u', 10, 0, etRADIX, 0, 0 },
19630 { 'x', 16, 0, etRADIX, 16, 1 },
19631 { 'X', 16, 0, etRADIX, 0, 4 },
19632 #ifndef SQLITE_OMIT_FLOATING_POINT
19633 { 'f', 0, 1, etFLOAT, 0, 0 },
19634 { 'e', 0, 1, etEXP, 30, 0 },
19635 { 'E', 0, 1, etEXP, 14, 0 },
19636 { 'G', 0, 1, etGENERIC, 14, 0 },
19637 #endif
19638 { 'i', 10, 1, etRADIX, 0, 0 },
19639 { 'n', 0, 0, etSIZE, 0, 0 },
19640 { '%', 0, 0, etPERCENT, 0, 0 },
19641 { 'p', 16, 0, etPOINTER, 0, 1 },
19643 /* All the rest have the FLAG_INTERN bit set and are thus for internal
19644 ** use only */
19645 { 'T', 0, 2, etTOKEN, 0, 0 },
19646 { 'S', 0, 2, etSRCLIST, 0, 0 },
19647 { 'r', 10, 3, etORDINAL, 0, 0 },
19651 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19652 ** conversions will work.
19654 #ifndef SQLITE_OMIT_FLOATING_POINT
19656 ** "*val" is a double such that 0.1 <= *val < 10.0
19657 ** Return the ascii code for the leading digit of *val, then
19658 ** multiply "*val" by 10.0 to renormalize.
19660 ** Example:
19661 ** input: *val = 3.14159
19662 ** output: *val = 1.4159 function return = '3'
19664 ** The counter *cnt is incremented each time. After counter exceeds
19665 ** 16 (the number of significant digits in a 64-bit float) '0' is
19666 ** always returned.
19668 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19669 int digit;
19670 LONGDOUBLE_TYPE d;
19671 if( (*cnt)<=0 ) return '0';
19672 (*cnt)--;
19673 digit = (int)*val;
19674 d = digit;
19675 digit += '0';
19676 *val = (*val - d)*10.0;
19677 return (char)digit;
19679 #endif /* SQLITE_OMIT_FLOATING_POINT */
19682 ** Append N space characters to the given string buffer.
19684 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19685 static const char zSpaces[] = " ";
19686 while( N>=(int)sizeof(zSpaces)-1 ){
19687 sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19688 N -= sizeof(zSpaces)-1;
19690 if( N>0 ){
19691 sqlite3StrAccumAppend(pAccum, zSpaces, N);
19696 ** On machines with a small stack size, you can redefine the
19697 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19699 #ifndef SQLITE_PRINT_BUF_SIZE
19700 # define SQLITE_PRINT_BUF_SIZE 70
19701 #endif
19702 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
19705 ** Render a string given by "fmt" into the StrAccum object.
19707 SQLITE_PRIVATE void sqlite3VXPrintf(
19708 StrAccum *pAccum, /* Accumulate results here */
19709 int useExtended, /* Allow extended %-conversions */
19710 const char *fmt, /* Format string */
19711 va_list ap /* arguments */
19713 int c; /* Next character in the format string */
19714 char *bufpt; /* Pointer to the conversion buffer */
19715 int precision; /* Precision of the current field */
19716 int length; /* Length of the field */
19717 int idx; /* A general purpose loop counter */
19718 int width; /* Width of the current field */
19719 etByte flag_leftjustify; /* True if "-" flag is present */
19720 etByte flag_plussign; /* True if "+" flag is present */
19721 etByte flag_blanksign; /* True if " " flag is present */
19722 etByte flag_alternateform; /* True if "#" flag is present */
19723 etByte flag_altform2; /* True if "!" flag is present */
19724 etByte flag_zeropad; /* True if field width constant starts with zero */
19725 etByte flag_long; /* True if "l" flag is present */
19726 etByte flag_longlong; /* True if the "ll" flag is present */
19727 etByte done; /* Loop termination flag */
19728 etByte xtype = 0; /* Conversion paradigm */
19729 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
19730 sqlite_uint64 longvalue; /* Value for integer types */
19731 LONGDOUBLE_TYPE realvalue; /* Value for real types */
19732 const et_info *infop; /* Pointer to the appropriate info structure */
19733 char *zOut; /* Rendering buffer */
19734 int nOut; /* Size of the rendering buffer */
19735 char *zExtra; /* Malloced memory used by some conversion */
19736 #ifndef SQLITE_OMIT_FLOATING_POINT
19737 int exp, e2; /* exponent of real numbers */
19738 int nsd; /* Number of significant digits returned */
19739 double rounder; /* Used for rounding floating point values */
19740 etByte flag_dp; /* True if decimal point should be shown */
19741 etByte flag_rtz; /* True if trailing zeros should be removed */
19742 #endif
19743 char buf[etBUFSIZE]; /* Conversion buffer */
19745 bufpt = 0;
19746 for(; (c=(*fmt))!=0; ++fmt){
19747 if( c!='%' ){
19748 int amt;
19749 bufpt = (char *)fmt;
19750 amt = 1;
19751 while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19752 sqlite3StrAccumAppend(pAccum, bufpt, amt);
19753 if( c==0 ) break;
19755 if( (c=(*++fmt))==0 ){
19756 sqlite3StrAccumAppend(pAccum, "%", 1);
19757 break;
19759 /* Find out what flags are present */
19760 flag_leftjustify = flag_plussign = flag_blanksign =
19761 flag_alternateform = flag_altform2 = flag_zeropad = 0;
19762 done = 0;
19764 switch( c ){
19765 case '-': flag_leftjustify = 1; break;
19766 case '+': flag_plussign = 1; break;
19767 case ' ': flag_blanksign = 1; break;
19768 case '#': flag_alternateform = 1; break;
19769 case '!': flag_altform2 = 1; break;
19770 case '0': flag_zeropad = 1; break;
19771 default: done = 1; break;
19773 }while( !done && (c=(*++fmt))!=0 );
19774 /* Get the field width */
19775 width = 0;
19776 if( c=='*' ){
19777 width = va_arg(ap,int);
19778 if( width<0 ){
19779 flag_leftjustify = 1;
19780 width = -width;
19782 c = *++fmt;
19783 }else{
19784 while( c>='0' && c<='9' ){
19785 width = width*10 + c - '0';
19786 c = *++fmt;
19789 /* Get the precision */
19790 if( c=='.' ){
19791 precision = 0;
19792 c = *++fmt;
19793 if( c=='*' ){
19794 precision = va_arg(ap,int);
19795 if( precision<0 ) precision = -precision;
19796 c = *++fmt;
19797 }else{
19798 while( c>='0' && c<='9' ){
19799 precision = precision*10 + c - '0';
19800 c = *++fmt;
19803 }else{
19804 precision = -1;
19806 /* Get the conversion type modifier */
19807 if( c=='l' ){
19808 flag_long = 1;
19809 c = *++fmt;
19810 if( c=='l' ){
19811 flag_longlong = 1;
19812 c = *++fmt;
19813 }else{
19814 flag_longlong = 0;
19816 }else{
19817 flag_long = flag_longlong = 0;
19819 /* Fetch the info entry for the field */
19820 infop = &fmtinfo[0];
19821 xtype = etINVALID;
19822 for(idx=0; idx<ArraySize(fmtinfo); idx++){
19823 if( c==fmtinfo[idx].fmttype ){
19824 infop = &fmtinfo[idx];
19825 if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19826 xtype = infop->type;
19827 }else{
19828 return;
19830 break;
19833 zExtra = 0;
19836 ** At this point, variables are initialized as follows:
19838 ** flag_alternateform TRUE if a '#' is present.
19839 ** flag_altform2 TRUE if a '!' is present.
19840 ** flag_plussign TRUE if a '+' is present.
19841 ** flag_leftjustify TRUE if a '-' is present or if the
19842 ** field width was negative.
19843 ** flag_zeropad TRUE if the width began with 0.
19844 ** flag_long TRUE if the letter 'l' (ell) prefixed
19845 ** the conversion character.
19846 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
19847 ** the conversion character.
19848 ** flag_blanksign TRUE if a ' ' is present.
19849 ** width The specified field width. This is
19850 ** always non-negative. Zero is the default.
19851 ** precision The specified precision. The default
19852 ** is -1.
19853 ** xtype The class of the conversion.
19854 ** infop Pointer to the appropriate info struct.
19856 switch( xtype ){
19857 case etPOINTER:
19858 flag_longlong = sizeof(char*)==sizeof(i64);
19859 flag_long = sizeof(char*)==sizeof(long int);
19860 /* Fall through into the next case */
19861 case etORDINAL:
19862 case etRADIX:
19863 if( infop->flags & FLAG_SIGNED ){
19864 i64 v;
19865 if( flag_longlong ){
19866 v = va_arg(ap,i64);
19867 }else if( flag_long ){
19868 v = va_arg(ap,long int);
19869 }else{
19870 v = va_arg(ap,int);
19872 if( v<0 ){
19873 if( v==SMALLEST_INT64 ){
19874 longvalue = ((u64)1)<<63;
19875 }else{
19876 longvalue = -v;
19878 prefix = '-';
19879 }else{
19880 longvalue = v;
19881 if( flag_plussign ) prefix = '+';
19882 else if( flag_blanksign ) prefix = ' ';
19883 else prefix = 0;
19885 }else{
19886 if( flag_longlong ){
19887 longvalue = va_arg(ap,u64);
19888 }else if( flag_long ){
19889 longvalue = va_arg(ap,unsigned long int);
19890 }else{
19891 longvalue = va_arg(ap,unsigned int);
19893 prefix = 0;
19895 if( longvalue==0 ) flag_alternateform = 0;
19896 if( flag_zeropad && precision<width-(prefix!=0) ){
19897 precision = width-(prefix!=0);
19899 if( precision<etBUFSIZE-10 ){
19900 nOut = etBUFSIZE;
19901 zOut = buf;
19902 }else{
19903 nOut = precision + 10;
19904 zOut = zExtra = sqlite3Malloc( nOut );
19905 if( zOut==0 ){
19906 pAccum->accError = STRACCUM_NOMEM;
19907 return;
19910 bufpt = &zOut[nOut-1];
19911 if( xtype==etORDINAL ){
19912 static const char zOrd[] = "thstndrd";
19913 int x = (int)(longvalue % 10);
19914 if( x>=4 || (longvalue/10)%10==1 ){
19915 x = 0;
19917 *(--bufpt) = zOrd[x*2+1];
19918 *(--bufpt) = zOrd[x*2];
19921 register const char *cset; /* Use registers for speed */
19922 register int base;
19923 cset = &aDigits[infop->charset];
19924 base = infop->base;
19925 do{ /* Convert to ascii */
19926 *(--bufpt) = cset[longvalue%base];
19927 longvalue = longvalue/base;
19928 }while( longvalue>0 );
19930 length = (int)(&zOut[nOut-1]-bufpt);
19931 for(idx=precision-length; idx>0; idx--){
19932 *(--bufpt) = '0'; /* Zero pad */
19934 if( prefix ) *(--bufpt) = prefix; /* Add sign */
19935 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
19936 const char *pre;
19937 char x;
19938 pre = &aPrefix[infop->prefix];
19939 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19941 length = (int)(&zOut[nOut-1]-bufpt);
19942 break;
19943 case etFLOAT:
19944 case etEXP:
19945 case etGENERIC:
19946 realvalue = va_arg(ap,double);
19947 #ifdef SQLITE_OMIT_FLOATING_POINT
19948 length = 0;
19949 #else
19950 if( precision<0 ) precision = 6; /* Set default precision */
19951 if( realvalue<0.0 ){
19952 realvalue = -realvalue;
19953 prefix = '-';
19954 }else{
19955 if( flag_plussign ) prefix = '+';
19956 else if( flag_blanksign ) prefix = ' ';
19957 else prefix = 0;
19959 if( xtype==etGENERIC && precision>0 ) precision--;
19960 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19961 if( xtype==etFLOAT ) realvalue += rounder;
19962 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19963 exp = 0;
19964 if( sqlite3IsNaN((double)realvalue) ){
19965 bufpt = "NaN";
19966 length = 3;
19967 break;
19969 if( realvalue>0.0 ){
19970 LONGDOUBLE_TYPE scale = 1.0;
19971 while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
19972 while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
19973 while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
19974 while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
19975 realvalue /= scale;
19976 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19977 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19978 if( exp>350 ){
19979 if( prefix=='-' ){
19980 bufpt = "-Inf";
19981 }else if( prefix=='+' ){
19982 bufpt = "+Inf";
19983 }else{
19984 bufpt = "Inf";
19986 length = sqlite3Strlen30(bufpt);
19987 break;
19990 bufpt = buf;
19992 ** If the field type is etGENERIC, then convert to either etEXP
19993 ** or etFLOAT, as appropriate.
19995 if( xtype!=etFLOAT ){
19996 realvalue += rounder;
19997 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19999 if( xtype==etGENERIC ){
20000 flag_rtz = !flag_alternateform;
20001 if( exp<-4 || exp>precision ){
20002 xtype = etEXP;
20003 }else{
20004 precision = precision - exp;
20005 xtype = etFLOAT;
20007 }else{
20008 flag_rtz = flag_altform2;
20010 if( xtype==etEXP ){
20011 e2 = 0;
20012 }else{
20013 e2 = exp;
20015 if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
20016 bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
20017 if( bufpt==0 ){
20018 pAccum->accError = STRACCUM_NOMEM;
20019 return;
20022 zOut = bufpt;
20023 nsd = 16 + flag_altform2*10;
20024 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
20025 /* The sign in front of the number */
20026 if( prefix ){
20027 *(bufpt++) = prefix;
20029 /* Digits prior to the decimal point */
20030 if( e2<0 ){
20031 *(bufpt++) = '0';
20032 }else{
20033 for(; e2>=0; e2--){
20034 *(bufpt++) = et_getdigit(&realvalue,&nsd);
20037 /* The decimal point */
20038 if( flag_dp ){
20039 *(bufpt++) = '.';
20041 /* "0" digits after the decimal point but before the first
20042 ** significant digit of the number */
20043 for(e2++; e2<0; precision--, e2++){
20044 assert( precision>0 );
20045 *(bufpt++) = '0';
20047 /* Significant digits after the decimal point */
20048 while( (precision--)>0 ){
20049 *(bufpt++) = et_getdigit(&realvalue,&nsd);
20051 /* Remove trailing zeros and the "." if no digits follow the "." */
20052 if( flag_rtz && flag_dp ){
20053 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
20054 assert( bufpt>zOut );
20055 if( bufpt[-1]=='.' ){
20056 if( flag_altform2 ){
20057 *(bufpt++) = '0';
20058 }else{
20059 *(--bufpt) = 0;
20063 /* Add the "eNNN" suffix */
20064 if( xtype==etEXP ){
20065 *(bufpt++) = aDigits[infop->charset];
20066 if( exp<0 ){
20067 *(bufpt++) = '-'; exp = -exp;
20068 }else{
20069 *(bufpt++) = '+';
20071 if( exp>=100 ){
20072 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
20073 exp %= 100;
20075 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
20076 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
20078 *bufpt = 0;
20080 /* The converted number is in buf[] and zero terminated. Output it.
20081 ** Note that the number is in the usual order, not reversed as with
20082 ** integer conversions. */
20083 length = (int)(bufpt-zOut);
20084 bufpt = zOut;
20086 /* Special case: Add leading zeros if the flag_zeropad flag is
20087 ** set and we are not left justified */
20088 if( flag_zeropad && !flag_leftjustify && length < width){
20089 int i;
20090 int nPad = width - length;
20091 for(i=width; i>=nPad; i--){
20092 bufpt[i] = bufpt[i-nPad];
20094 i = prefix!=0;
20095 while( nPad-- ) bufpt[i++] = '0';
20096 length = width;
20098 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
20099 break;
20100 case etSIZE:
20101 *(va_arg(ap,int*)) = pAccum->nChar;
20102 length = width = 0;
20103 break;
20104 case etPERCENT:
20105 buf[0] = '%';
20106 bufpt = buf;
20107 length = 1;
20108 break;
20109 case etCHARX:
20110 c = va_arg(ap,int);
20111 buf[0] = (char)c;
20112 if( precision>=0 ){
20113 for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
20114 length = precision;
20115 }else{
20116 length =1;
20118 bufpt = buf;
20119 break;
20120 case etSTRING:
20121 case etDYNSTRING:
20122 bufpt = va_arg(ap,char*);
20123 if( bufpt==0 ){
20124 bufpt = "";
20125 }else if( xtype==etDYNSTRING ){
20126 zExtra = bufpt;
20128 if( precision>=0 ){
20129 for(length=0; length<precision && bufpt[length]; length++){}
20130 }else{
20131 length = sqlite3Strlen30(bufpt);
20133 break;
20134 case etSQLESCAPE:
20135 case etSQLESCAPE2:
20136 case etSQLESCAPE3: {
20137 int i, j, k, n, isnull;
20138 int needQuote;
20139 char ch;
20140 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
20141 char *escarg = va_arg(ap,char*);
20142 isnull = escarg==0;
20143 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
20144 k = precision;
20145 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
20146 if( ch==q ) n++;
20148 needQuote = !isnull && xtype==etSQLESCAPE2;
20149 n += i + 1 + needQuote*2;
20150 if( n>etBUFSIZE ){
20151 bufpt = zExtra = sqlite3Malloc( n );
20152 if( bufpt==0 ){
20153 pAccum->accError = STRACCUM_NOMEM;
20154 return;
20156 }else{
20157 bufpt = buf;
20159 j = 0;
20160 if( needQuote ) bufpt[j++] = q;
20161 k = i;
20162 for(i=0; i<k; i++){
20163 bufpt[j++] = ch = escarg[i];
20164 if( ch==q ) bufpt[j++] = ch;
20166 if( needQuote ) bufpt[j++] = q;
20167 bufpt[j] = 0;
20168 length = j;
20169 /* The precision in %q and %Q means how many input characters to
20170 ** consume, not the length of the output...
20171 ** if( precision>=0 && precision<length ) length = precision; */
20172 break;
20174 case etTOKEN: {
20175 Token *pToken = va_arg(ap, Token*);
20176 if( pToken ){
20177 sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20179 length = width = 0;
20180 break;
20182 case etSRCLIST: {
20183 SrcList *pSrc = va_arg(ap, SrcList*);
20184 int k = va_arg(ap, int);
20185 struct SrcList_item *pItem = &pSrc->a[k];
20186 assert( k>=0 && k<pSrc->nSrc );
20187 if( pItem->zDatabase ){
20188 sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
20189 sqlite3StrAccumAppend(pAccum, ".", 1);
20191 sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
20192 length = width = 0;
20193 break;
20195 default: {
20196 assert( xtype==etINVALID );
20197 return;
20199 }/* End switch over the format type */
20201 ** The text of the conversion is pointed to by "bufpt" and is
20202 ** "length" characters long. The field width is "width". Do
20203 ** the output.
20205 if( !flag_leftjustify ){
20206 register int nspace;
20207 nspace = width-length;
20208 if( nspace>0 ){
20209 sqlite3AppendSpace(pAccum, nspace);
20212 if( length>0 ){
20213 sqlite3StrAccumAppend(pAccum, bufpt, length);
20215 if( flag_leftjustify ){
20216 register int nspace;
20217 nspace = width-length;
20218 if( nspace>0 ){
20219 sqlite3AppendSpace(pAccum, nspace);
20222 sqlite3_free(zExtra);
20223 }/* End for loop over the format string */
20224 } /* End of function */
20227 ** Append N bytes of text from z to the StrAccum object.
20229 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20230 assert( z!=0 || N==0 );
20231 if( p->accError ){
20232 testcase(p->accError==STRACCUM_TOOBIG);
20233 testcase(p->accError==STRACCUM_NOMEM);
20234 return;
20236 assert( p->zText!=0 || p->nChar==0 );
20237 if( N<=0 ){
20238 if( N==0 || z[0]==0 ) return;
20239 N = sqlite3Strlen30(z);
20241 if( p->nChar+N >= p->nAlloc ){
20242 char *zNew;
20243 if( !p->useMalloc ){
20244 p->accError = STRACCUM_TOOBIG;
20245 N = p->nAlloc - p->nChar - 1;
20246 if( N<=0 ){
20247 return;
20249 }else{
20250 char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20251 i64 szNew = p->nChar;
20252 szNew += N + 1;
20253 if( szNew > p->mxAlloc ){
20254 sqlite3StrAccumReset(p);
20255 p->accError = STRACCUM_TOOBIG;
20256 return;
20257 }else{
20258 p->nAlloc = (int)szNew;
20260 if( p->useMalloc==1 ){
20261 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20262 }else{
20263 zNew = sqlite3_realloc(zOld, p->nAlloc);
20265 if( zNew ){
20266 if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20267 p->zText = zNew;
20268 }else{
20269 p->accError = STRACCUM_NOMEM;
20270 sqlite3StrAccumReset(p);
20271 return;
20275 assert( p->zText );
20276 memcpy(&p->zText[p->nChar], z, N);
20277 p->nChar += N;
20281 ** Finish off a string by making sure it is zero-terminated.
20282 ** Return a pointer to the resulting string. Return a NULL
20283 ** pointer if any kind of error was encountered.
20285 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20286 if( p->zText ){
20287 p->zText[p->nChar] = 0;
20288 if( p->useMalloc && p->zText==p->zBase ){
20289 if( p->useMalloc==1 ){
20290 p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20291 }else{
20292 p->zText = sqlite3_malloc(p->nChar+1);
20294 if( p->zText ){
20295 memcpy(p->zText, p->zBase, p->nChar+1);
20296 }else{
20297 p->accError = STRACCUM_NOMEM;
20301 return p->zText;
20305 ** Reset an StrAccum string. Reclaim all malloced memory.
20307 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20308 if( p->zText!=p->zBase ){
20309 if( p->useMalloc==1 ){
20310 sqlite3DbFree(p->db, p->zText);
20311 }else{
20312 sqlite3_free(p->zText);
20315 p->zText = 0;
20319 ** Initialize a string accumulator
20321 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20322 p->zText = p->zBase = zBase;
20323 p->db = 0;
20324 p->nChar = 0;
20325 p->nAlloc = n;
20326 p->mxAlloc = mx;
20327 p->useMalloc = 1;
20328 p->accError = 0;
20332 ** Print into memory obtained from sqliteMalloc(). Use the internal
20333 ** %-conversion extensions.
20335 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20336 char *z;
20337 char zBase[SQLITE_PRINT_BUF_SIZE];
20338 StrAccum acc;
20339 assert( db!=0 );
20340 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20341 db->aLimit[SQLITE_LIMIT_LENGTH]);
20342 acc.db = db;
20343 sqlite3VXPrintf(&acc, 1, zFormat, ap);
20344 z = sqlite3StrAccumFinish(&acc);
20345 if( acc.accError==STRACCUM_NOMEM ){
20346 db->mallocFailed = 1;
20348 return z;
20352 ** Print into memory obtained from sqliteMalloc(). Use the internal
20353 ** %-conversion extensions.
20355 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20356 va_list ap;
20357 char *z;
20358 va_start(ap, zFormat);
20359 z = sqlite3VMPrintf(db, zFormat, ap);
20360 va_end(ap);
20361 return z;
20365 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20366 ** the string and before returnning. This routine is intended to be used
20367 ** to modify an existing string. For example:
20369 ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20372 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20373 va_list ap;
20374 char *z;
20375 va_start(ap, zFormat);
20376 z = sqlite3VMPrintf(db, zFormat, ap);
20377 va_end(ap);
20378 sqlite3DbFree(db, zStr);
20379 return z;
20383 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
20384 ** %-conversion extensions.
20386 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20387 char *z;
20388 char zBase[SQLITE_PRINT_BUF_SIZE];
20389 StrAccum acc;
20390 #ifndef SQLITE_OMIT_AUTOINIT
20391 if( sqlite3_initialize() ) return 0;
20392 #endif
20393 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20394 acc.useMalloc = 2;
20395 sqlite3VXPrintf(&acc, 0, zFormat, ap);
20396 z = sqlite3StrAccumFinish(&acc);
20397 return z;
20401 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
20402 ** %-conversion extensions.
20404 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20405 va_list ap;
20406 char *z;
20407 #ifndef SQLITE_OMIT_AUTOINIT
20408 if( sqlite3_initialize() ) return 0;
20409 #endif
20410 va_start(ap, zFormat);
20411 z = sqlite3_vmprintf(zFormat, ap);
20412 va_end(ap);
20413 return z;
20417 ** sqlite3_snprintf() works like snprintf() except that it ignores the
20418 ** current locale settings. This is important for SQLite because we
20419 ** are not able to use a "," as the decimal point in place of "." as
20420 ** specified by some locales.
20422 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
20423 ** from the snprintf() standard. Unfortunately, it is too late to change
20424 ** this without breaking compatibility, so we just have to live with the
20425 ** mistake.
20427 ** sqlite3_vsnprintf() is the varargs version.
20429 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20430 StrAccum acc;
20431 if( n<=0 ) return zBuf;
20432 sqlite3StrAccumInit(&acc, zBuf, n, 0);
20433 acc.useMalloc = 0;
20434 sqlite3VXPrintf(&acc, 0, zFormat, ap);
20435 return sqlite3StrAccumFinish(&acc);
20437 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20438 char *z;
20439 va_list ap;
20440 va_start(ap,zFormat);
20441 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20442 va_end(ap);
20443 return z;
20447 ** This is the routine that actually formats the sqlite3_log() message.
20448 ** We house it in a separate routine from sqlite3_log() to avoid using
20449 ** stack space on small-stack systems when logging is disabled.
20451 ** sqlite3_log() must render into a static buffer. It cannot dynamically
20452 ** allocate memory because it might be called while the memory allocator
20453 ** mutex is held.
20455 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20456 StrAccum acc; /* String accumulator */
20457 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
20459 sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20460 acc.useMalloc = 0;
20461 sqlite3VXPrintf(&acc, 0, zFormat, ap);
20462 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20463 sqlite3StrAccumFinish(&acc));
20467 ** Format and write a message to the log if logging is enabled.
20469 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20470 va_list ap; /* Vararg list */
20471 if( sqlite3GlobalConfig.xLog ){
20472 va_start(ap, zFormat);
20473 renderLogMsg(iErrCode, zFormat, ap);
20474 va_end(ap);
20478 #if defined(SQLITE_DEBUG)
20480 ** A version of printf() that understands %lld. Used for debugging.
20481 ** The printf() built into some versions of windows does not understand %lld
20482 ** and segfaults if you give it a long long int.
20484 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20485 va_list ap;
20486 StrAccum acc;
20487 char zBuf[500];
20488 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20489 acc.useMalloc = 0;
20490 va_start(ap,zFormat);
20491 sqlite3VXPrintf(&acc, 0, zFormat, ap);
20492 va_end(ap);
20493 sqlite3StrAccumFinish(&acc);
20494 fprintf(stdout,"%s", zBuf);
20495 fflush(stdout);
20497 #endif
20499 #ifndef SQLITE_OMIT_TRACE
20501 ** variable-argument wrapper around sqlite3VXPrintf().
20503 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20504 va_list ap;
20505 va_start(ap,zFormat);
20506 sqlite3VXPrintf(p, 1, zFormat, ap);
20507 va_end(ap);
20509 #endif
20511 /************** End of printf.c **********************************************/
20512 /************** Begin file random.c ******************************************/
20514 ** 2001 September 15
20516 ** The author disclaims copyright to this source code. In place of
20517 ** a legal notice, here is a blessing:
20519 ** May you do good and not evil.
20520 ** May you find forgiveness for yourself and forgive others.
20521 ** May you share freely, never taking more than you give.
20523 *************************************************************************
20524 ** This file contains code to implement a pseudo-random number
20525 ** generator (PRNG) for SQLite.
20527 ** Random numbers are used by some of the database backends in order
20528 ** to generate random integer keys for tables or random filenames.
20532 /* All threads share a single random number generator.
20533 ** This structure is the current state of the generator.
20535 static SQLITE_WSD struct sqlite3PrngType {
20536 unsigned char isInit; /* True if initialized */
20537 unsigned char i, j; /* State variables */
20538 unsigned char s[256]; /* State variables */
20539 } sqlite3Prng;
20542 ** Return N random bytes.
20544 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20545 unsigned char t;
20546 unsigned char *zBuf = pBuf;
20548 /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20549 ** state vector. If writable static data is unsupported on the target,
20550 ** we have to locate the state vector at run-time. In the more common
20551 ** case where writable static data is supported, wsdPrng can refer directly
20552 ** to the "sqlite3Prng" state vector declared above.
20554 #ifdef SQLITE_OMIT_WSD
20555 struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20556 # define wsdPrng p[0]
20557 #else
20558 # define wsdPrng sqlite3Prng
20559 #endif
20561 #if SQLITE_THREADSAFE
20562 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20563 sqlite3_mutex_enter(mutex);
20564 #endif
20566 /* Initialize the state of the random number generator once,
20567 ** the first time this routine is called. The seed value does
20568 ** not need to contain a lot of randomness since we are not
20569 ** trying to do secure encryption or anything like that...
20571 ** Nothing in this file or anywhere else in SQLite does any kind of
20572 ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
20573 ** number generator) not as an encryption device.
20575 if( !wsdPrng.isInit ){
20576 int i;
20577 char k[256];
20578 wsdPrng.j = 0;
20579 wsdPrng.i = 0;
20580 sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20581 for(i=0; i<256; i++){
20582 wsdPrng.s[i] = (u8)i;
20584 for(i=0; i<256; i++){
20585 wsdPrng.j += wsdPrng.s[i] + k[i];
20586 t = wsdPrng.s[wsdPrng.j];
20587 wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20588 wsdPrng.s[i] = t;
20590 wsdPrng.isInit = 1;
20593 while( N-- ){
20594 wsdPrng.i++;
20595 t = wsdPrng.s[wsdPrng.i];
20596 wsdPrng.j += t;
20597 wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20598 wsdPrng.s[wsdPrng.j] = t;
20599 t += wsdPrng.s[wsdPrng.i];
20600 *(zBuf++) = wsdPrng.s[t];
20602 sqlite3_mutex_leave(mutex);
20605 #ifndef SQLITE_OMIT_BUILTIN_TEST
20607 ** For testing purposes, we sometimes want to preserve the state of
20608 ** PRNG and restore the PRNG to its saved state at a later time, or
20609 ** to reset the PRNG to its initial state. These routines accomplish
20610 ** those tasks.
20612 ** The sqlite3_test_control() interface calls these routines to
20613 ** control the PRNG.
20615 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20616 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20617 memcpy(
20618 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20619 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20620 sizeof(sqlite3Prng)
20623 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20624 memcpy(
20625 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20626 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20627 sizeof(sqlite3Prng)
20630 SQLITE_PRIVATE void sqlite3PrngResetState(void){
20631 GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20633 #endif /* SQLITE_OMIT_BUILTIN_TEST */
20635 /************** End of random.c **********************************************/
20636 /************** Begin file utf.c *********************************************/
20638 ** 2004 April 13
20640 ** The author disclaims copyright to this source code. In place of
20641 ** a legal notice, here is a blessing:
20643 ** May you do good and not evil.
20644 ** May you find forgiveness for yourself and forgive others.
20645 ** May you share freely, never taking more than you give.
20647 *************************************************************************
20648 ** This file contains routines used to translate between UTF-8,
20649 ** UTF-16, UTF-16BE, and UTF-16LE.
20651 ** Notes on UTF-8:
20653 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
20654 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
20655 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
20656 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
20657 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
20660 ** Notes on UTF-16: (with wwww+1==uuuuu)
20662 ** Word-0 Word-1 Value
20663 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
20664 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
20667 ** BOM or Byte Order Mark:
20668 ** 0xff 0xfe little-endian utf-16 follows
20669 ** 0xfe 0xff big-endian utf-16 follows
20672 /* #include <assert.h> */
20674 #ifndef SQLITE_AMALGAMATION
20676 ** The following constant value is used by the SQLITE_BIGENDIAN and
20677 ** SQLITE_LITTLEENDIAN macros.
20679 SQLITE_PRIVATE const int sqlite3one = 1;
20680 #endif /* SQLITE_AMALGAMATION */
20683 ** This lookup table is used to help decode the first byte of
20684 ** a multi-byte UTF8 character.
20686 static const unsigned char sqlite3Utf8Trans1[] = {
20687 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20688 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20689 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20690 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20691 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20692 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20693 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20694 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20698 #define WRITE_UTF8(zOut, c) { \
20699 if( c<0x00080 ){ \
20700 *zOut++ = (u8)(c&0xFF); \
20702 else if( c<0x00800 ){ \
20703 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
20704 *zOut++ = 0x80 + (u8)(c & 0x3F); \
20706 else if( c<0x10000 ){ \
20707 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
20708 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
20709 *zOut++ = 0x80 + (u8)(c & 0x3F); \
20710 }else{ \
20711 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
20712 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
20713 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
20714 *zOut++ = 0x80 + (u8)(c & 0x3F); \
20718 #define WRITE_UTF16LE(zOut, c) { \
20719 if( c<=0xFFFF ){ \
20720 *zOut++ = (u8)(c&0x00FF); \
20721 *zOut++ = (u8)((c>>8)&0x00FF); \
20722 }else{ \
20723 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
20724 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
20725 *zOut++ = (u8)(c&0x00FF); \
20726 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
20730 #define WRITE_UTF16BE(zOut, c) { \
20731 if( c<=0xFFFF ){ \
20732 *zOut++ = (u8)((c>>8)&0x00FF); \
20733 *zOut++ = (u8)(c&0x00FF); \
20734 }else{ \
20735 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
20736 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
20737 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
20738 *zOut++ = (u8)(c&0x00FF); \
20742 #define READ_UTF16LE(zIn, TERM, c){ \
20743 c = (*zIn++); \
20744 c += ((*zIn++)<<8); \
20745 if( c>=0xD800 && c<0xE000 && TERM ){ \
20746 int c2 = (*zIn++); \
20747 c2 += ((*zIn++)<<8); \
20748 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
20752 #define READ_UTF16BE(zIn, TERM, c){ \
20753 c = ((*zIn++)<<8); \
20754 c += (*zIn++); \
20755 if( c>=0xD800 && c<0xE000 && TERM ){ \
20756 int c2 = ((*zIn++)<<8); \
20757 c2 += (*zIn++); \
20758 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
20763 ** Translate a single UTF-8 character. Return the unicode value.
20765 ** During translation, assume that the byte that zTerm points
20766 ** is a 0x00.
20768 ** Write a pointer to the next unread byte back into *pzNext.
20770 ** Notes On Invalid UTF-8:
20772 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
20773 ** be encoded as a multi-byte character. Any multi-byte character that
20774 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20776 ** * This routine never allows a UTF16 surrogate value to be encoded.
20777 ** If a multi-byte character attempts to encode a value between
20778 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
20780 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
20781 ** byte of a character are interpreted as single-byte characters
20782 ** and rendered as themselves even though they are technically
20783 ** invalid characters.
20785 ** * This routine accepts an infinite number of different UTF8 encodings
20786 ** for unicode values 0x80 and greater. It do not change over-length
20787 ** encodings to 0xfffd as some systems recommend.
20789 #define READ_UTF8(zIn, zTerm, c) \
20790 c = *(zIn++); \
20791 if( c>=0xc0 ){ \
20792 c = sqlite3Utf8Trans1[c-0xc0]; \
20793 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
20794 c = (c<<6) + (0x3f & *(zIn++)); \
20796 if( c<0x80 \
20797 || (c&0xFFFFF800)==0xD800 \
20798 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
20800 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20801 const unsigned char **pz /* Pointer to string from which to read char */
20803 unsigned int c;
20805 /* Same as READ_UTF8() above but without the zTerm parameter.
20806 ** For this routine, we assume the UTF8 string is always zero-terminated.
20808 c = *((*pz)++);
20809 if( c>=0xc0 ){
20810 c = sqlite3Utf8Trans1[c-0xc0];
20811 while( (*(*pz) & 0xc0)==0x80 ){
20812 c = (c<<6) + (0x3f & *((*pz)++));
20814 if( c<0x80
20815 || (c&0xFFFFF800)==0xD800
20816 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
20818 return c;
20825 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20826 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20828 /* #define TRANSLATE_TRACE 1 */
20830 #ifndef SQLITE_OMIT_UTF16
20832 ** This routine transforms the internal text encoding used by pMem to
20833 ** desiredEnc. It is an error if the string is already of the desired
20834 ** encoding, or if *pMem does not contain a string value.
20836 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20837 int len; /* Maximum length of output string in bytes */
20838 unsigned char *zOut; /* Output buffer */
20839 unsigned char *zIn; /* Input iterator */
20840 unsigned char *zTerm; /* End of input */
20841 unsigned char *z; /* Output iterator */
20842 unsigned int c;
20844 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20845 assert( pMem->flags&MEM_Str );
20846 assert( pMem->enc!=desiredEnc );
20847 assert( pMem->enc!=0 );
20848 assert( pMem->n>=0 );
20850 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20852 char zBuf[100];
20853 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20854 fprintf(stderr, "INPUT: %s\n", zBuf);
20856 #endif
20858 /* If the translation is between UTF-16 little and big endian, then
20859 ** all that is required is to swap the byte order. This case is handled
20860 ** differently from the others.
20862 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20863 u8 temp;
20864 int rc;
20865 rc = sqlite3VdbeMemMakeWriteable(pMem);
20866 if( rc!=SQLITE_OK ){
20867 assert( rc==SQLITE_NOMEM );
20868 return SQLITE_NOMEM;
20870 zIn = (u8*)pMem->z;
20871 zTerm = &zIn[pMem->n&~1];
20872 while( zIn<zTerm ){
20873 temp = *zIn;
20874 *zIn = *(zIn+1);
20875 zIn++;
20876 *zIn++ = temp;
20878 pMem->enc = desiredEnc;
20879 goto translate_out;
20882 /* Set len to the maximum number of bytes required in the output buffer. */
20883 if( desiredEnc==SQLITE_UTF8 ){
20884 /* When converting from UTF-16, the maximum growth results from
20885 ** translating a 2-byte character to a 4-byte UTF-8 character.
20886 ** A single byte is required for the output string
20887 ** nul-terminator.
20889 pMem->n &= ~1;
20890 len = pMem->n * 2 + 1;
20891 }else{
20892 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20893 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20894 ** character. Two bytes are required in the output buffer for the
20895 ** nul-terminator.
20897 len = pMem->n * 2 + 2;
20900 /* Set zIn to point at the start of the input buffer and zTerm to point 1
20901 ** byte past the end.
20903 ** Variable zOut is set to point at the output buffer, space obtained
20904 ** from sqlite3_malloc().
20906 zIn = (u8*)pMem->z;
20907 zTerm = &zIn[pMem->n];
20908 zOut = sqlite3DbMallocRaw(pMem->db, len);
20909 if( !zOut ){
20910 return SQLITE_NOMEM;
20912 z = zOut;
20914 if( pMem->enc==SQLITE_UTF8 ){
20915 if( desiredEnc==SQLITE_UTF16LE ){
20916 /* UTF-8 -> UTF-16 Little-endian */
20917 while( zIn<zTerm ){
20918 READ_UTF8(zIn, zTerm, c);
20919 WRITE_UTF16LE(z, c);
20921 }else{
20922 assert( desiredEnc==SQLITE_UTF16BE );
20923 /* UTF-8 -> UTF-16 Big-endian */
20924 while( zIn<zTerm ){
20925 READ_UTF8(zIn, zTerm, c);
20926 WRITE_UTF16BE(z, c);
20929 pMem->n = (int)(z - zOut);
20930 *z++ = 0;
20931 }else{
20932 assert( desiredEnc==SQLITE_UTF8 );
20933 if( pMem->enc==SQLITE_UTF16LE ){
20934 /* UTF-16 Little-endian -> UTF-8 */
20935 while( zIn<zTerm ){
20936 READ_UTF16LE(zIn, zIn<zTerm, c);
20937 WRITE_UTF8(z, c);
20939 }else{
20940 /* UTF-16 Big-endian -> UTF-8 */
20941 while( zIn<zTerm ){
20942 READ_UTF16BE(zIn, zIn<zTerm, c);
20943 WRITE_UTF8(z, c);
20946 pMem->n = (int)(z - zOut);
20948 *z = 0;
20949 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20951 sqlite3VdbeMemRelease(pMem);
20952 pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20953 pMem->enc = desiredEnc;
20954 pMem->flags |= (MEM_Term|MEM_Dyn);
20955 pMem->z = (char*)zOut;
20956 pMem->zMalloc = pMem->z;
20958 translate_out:
20959 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20961 char zBuf[100];
20962 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20963 fprintf(stderr, "OUTPUT: %s\n", zBuf);
20965 #endif
20966 return SQLITE_OK;
20970 ** This routine checks for a byte-order mark at the beginning of the
20971 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20972 ** the encoding of the Mem adjusted. This routine does not do any
20973 ** byte-swapping, it just sets Mem.enc appropriately.
20975 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20976 ** changed by this function.
20978 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20979 int rc = SQLITE_OK;
20980 u8 bom = 0;
20982 assert( pMem->n>=0 );
20983 if( pMem->n>1 ){
20984 u8 b1 = *(u8 *)pMem->z;
20985 u8 b2 = *(((u8 *)pMem->z) + 1);
20986 if( b1==0xFE && b2==0xFF ){
20987 bom = SQLITE_UTF16BE;
20989 if( b1==0xFF && b2==0xFE ){
20990 bom = SQLITE_UTF16LE;
20994 if( bom ){
20995 rc = sqlite3VdbeMemMakeWriteable(pMem);
20996 if( rc==SQLITE_OK ){
20997 pMem->n -= 2;
20998 memmove(pMem->z, &pMem->z[2], pMem->n);
20999 pMem->z[pMem->n] = '\0';
21000 pMem->z[pMem->n+1] = '\0';
21001 pMem->flags |= MEM_Term;
21002 pMem->enc = bom;
21005 return rc;
21007 #endif /* SQLITE_OMIT_UTF16 */
21010 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
21011 ** return the number of unicode characters in pZ up to (but not including)
21012 ** the first 0x00 byte. If nByte is not less than zero, return the
21013 ** number of unicode characters in the first nByte of pZ (or up to
21014 ** the first 0x00, whichever comes first).
21016 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
21017 int r = 0;
21018 const u8 *z = (const u8*)zIn;
21019 const u8 *zTerm;
21020 if( nByte>=0 ){
21021 zTerm = &z[nByte];
21022 }else{
21023 zTerm = (const u8*)(-1);
21025 assert( z<=zTerm );
21026 while( *z!=0 && z<zTerm ){
21027 SQLITE_SKIP_UTF8(z);
21028 r++;
21030 return r;
21033 /* This test function is not currently used by the automated test-suite.
21034 ** Hence it is only available in debug builds.
21036 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
21038 ** Translate UTF-8 to UTF-8.
21040 ** This has the effect of making sure that the string is well-formed
21041 ** UTF-8. Miscoded characters are removed.
21043 ** The translation is done in-place and aborted if the output
21044 ** overruns the input.
21046 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
21047 unsigned char *zOut = zIn;
21048 unsigned char *zStart = zIn;
21049 u32 c;
21051 while( zIn[0] && zOut<=zIn ){
21052 c = sqlite3Utf8Read((const u8**)&zIn);
21053 if( c!=0xfffd ){
21054 WRITE_UTF8(zOut, c);
21057 *zOut = 0;
21058 return (int)(zOut - zStart);
21060 #endif
21062 #ifndef SQLITE_OMIT_UTF16
21064 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
21065 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
21066 ** be freed by the calling function.
21068 ** NULL is returned if there is an allocation error.
21070 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
21071 Mem m;
21072 memset(&m, 0, sizeof(m));
21073 m.db = db;
21074 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
21075 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
21076 if( db->mallocFailed ){
21077 sqlite3VdbeMemRelease(&m);
21078 m.z = 0;
21080 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
21081 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
21082 assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
21083 assert( m.z || db->mallocFailed );
21084 return m.z;
21088 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
21089 ** enc. A pointer to the new string is returned, and the value of *pnOut
21090 ** is set to the length of the returned string in bytes. The call should
21091 ** arrange to call sqlite3DbFree() on the returned pointer when it is
21092 ** no longer required.
21094 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
21095 ** flag set.
21097 #ifdef SQLITE_ENABLE_STAT3
21098 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
21099 Mem m;
21100 memset(&m, 0, sizeof(m));
21101 m.db = db;
21102 sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
21103 if( sqlite3VdbeMemTranslate(&m, enc) ){
21104 assert( db->mallocFailed );
21105 return 0;
21107 assert( m.z==m.zMalloc );
21108 *pnOut = m.n;
21109 return m.z;
21111 #endif
21114 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
21115 ** Return the number of bytes in the first nChar unicode characters
21116 ** in pZ. nChar must be non-negative.
21118 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
21119 int c;
21120 unsigned char const *z = zIn;
21121 int n = 0;
21123 if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
21124 while( n<nChar ){
21125 READ_UTF16BE(z, 1, c);
21126 n++;
21128 }else{
21129 while( n<nChar ){
21130 READ_UTF16LE(z, 1, c);
21131 n++;
21134 return (int)(z-(unsigned char const *)zIn);
21137 #if defined(SQLITE_TEST)
21139 ** This routine is called from the TCL test function "translate_selftest".
21140 ** It checks that the primitives for serializing and deserializing
21141 ** characters in each encoding are inverses of each other.
21143 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
21144 unsigned int i, t;
21145 unsigned char zBuf[20];
21146 unsigned char *z;
21147 int n;
21148 unsigned int c;
21150 for(i=0; i<0x00110000; i++){
21151 z = zBuf;
21152 WRITE_UTF8(z, i);
21153 n = (int)(z-zBuf);
21154 assert( n>0 && n<=4 );
21155 z[0] = 0;
21156 z = zBuf;
21157 c = sqlite3Utf8Read((const u8**)&z);
21158 t = i;
21159 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21160 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21161 assert( c==t );
21162 assert( (z-zBuf)==n );
21164 for(i=0; i<0x00110000; i++){
21165 if( i>=0xD800 && i<0xE000 ) continue;
21166 z = zBuf;
21167 WRITE_UTF16LE(z, i);
21168 n = (int)(z-zBuf);
21169 assert( n>0 && n<=4 );
21170 z[0] = 0;
21171 z = zBuf;
21172 READ_UTF16LE(z, 1, c);
21173 assert( c==i );
21174 assert( (z-zBuf)==n );
21176 for(i=0; i<0x00110000; i++){
21177 if( i>=0xD800 && i<0xE000 ) continue;
21178 z = zBuf;
21179 WRITE_UTF16BE(z, i);
21180 n = (int)(z-zBuf);
21181 assert( n>0 && n<=4 );
21182 z[0] = 0;
21183 z = zBuf;
21184 READ_UTF16BE(z, 1, c);
21185 assert( c==i );
21186 assert( (z-zBuf)==n );
21189 #endif /* SQLITE_TEST */
21190 #endif /* SQLITE_OMIT_UTF16 */
21192 /************** End of utf.c *************************************************/
21193 /************** Begin file util.c ********************************************/
21195 ** 2001 September 15
21197 ** The author disclaims copyright to this source code. In place of
21198 ** a legal notice, here is a blessing:
21200 ** May you do good and not evil.
21201 ** May you find forgiveness for yourself and forgive others.
21202 ** May you share freely, never taking more than you give.
21204 *************************************************************************
21205 ** Utility functions used throughout sqlite.
21207 ** This file contains functions for allocating memory, comparing
21208 ** strings, and stuff like that.
21211 /* #include <stdarg.h> */
21212 #ifdef SQLITE_HAVE_ISNAN
21213 # include <math.h>
21214 #endif
21217 ** Routine needed to support the testcase() macro.
21219 #ifdef SQLITE_COVERAGE_TEST
21220 SQLITE_PRIVATE void sqlite3Coverage(int x){
21221 static unsigned dummy = 0;
21222 dummy += (unsigned)x;
21224 #endif
21226 #ifndef SQLITE_OMIT_FLOATING_POINT
21228 ** Return true if the floating point value is Not a Number (NaN).
21230 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21231 ** Otherwise, we have our own implementation that works on most systems.
21233 SQLITE_PRIVATE int sqlite3IsNaN(double x){
21234 int rc; /* The value return */
21235 #if !defined(SQLITE_HAVE_ISNAN)
21237 ** Systems that support the isnan() library function should probably
21238 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
21239 ** found that many systems do not have a working isnan() function so
21240 ** this implementation is provided as an alternative.
21242 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21243 ** On the other hand, the use of -ffast-math comes with the following
21244 ** warning:
21246 ** This option [-ffast-math] should never be turned on by any
21247 ** -O option since it can result in incorrect output for programs
21248 ** which depend on an exact implementation of IEEE or ISO
21249 ** rules/specifications for math functions.
21251 ** Under MSVC, this NaN test may fail if compiled with a floating-
21252 ** point precision mode other than /fp:precise. From the MSDN
21253 ** documentation:
21255 ** The compiler [with /fp:precise] will properly handle comparisons
21256 ** involving NaN. For example, x != x evaluates to true if x is NaN
21257 ** ...
21259 #ifdef __FAST_MATH__
21260 # error SQLite will not work correctly with the -ffast-math option of GCC.
21261 #endif
21262 volatile double y = x;
21263 volatile double z = y;
21264 rc = (y!=z);
21265 #else /* if defined(SQLITE_HAVE_ISNAN) */
21266 rc = isnan(x);
21267 #endif /* SQLITE_HAVE_ISNAN */
21268 testcase( rc );
21269 return rc;
21271 #endif /* SQLITE_OMIT_FLOATING_POINT */
21274 ** Compute a string length that is limited to what can be stored in
21275 ** lower 30 bits of a 32-bit signed integer.
21277 ** The value returned will never be negative. Nor will it ever be greater
21278 ** than the actual length of the string. For very long strings (greater
21279 ** than 1GiB) the value returned might be less than the true string length.
21281 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21282 const char *z2 = z;
21283 if( z==0 ) return 0;
21284 while( *z2 ){ z2++; }
21285 return 0x3fffffff & (int)(z2 - z);
21289 ** Set the most recent error code and error string for the sqlite
21290 ** handle "db". The error code is set to "err_code".
21292 ** If it is not NULL, string zFormat specifies the format of the
21293 ** error string in the style of the printf functions: The following
21294 ** format characters are allowed:
21296 ** %s Insert a string
21297 ** %z A string that should be freed after use
21298 ** %d Insert an integer
21299 ** %T Insert a token
21300 ** %S Insert the first element of a SrcList
21302 ** zFormat and any string tokens that follow it are assumed to be
21303 ** encoded in UTF-8.
21305 ** To clear the most recent error for sqlite handle "db", sqlite3Error
21306 ** should be called with err_code set to SQLITE_OK and zFormat set
21307 ** to NULL.
21309 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21310 if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21311 db->errCode = err_code;
21312 if( zFormat ){
21313 char *z;
21314 va_list ap;
21315 va_start(ap, zFormat);
21316 z = sqlite3VMPrintf(db, zFormat, ap);
21317 va_end(ap);
21318 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21319 }else{
21320 sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21326 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21327 ** The following formatting characters are allowed:
21329 ** %s Insert a string
21330 ** %z A string that should be freed after use
21331 ** %d Insert an integer
21332 ** %T Insert a token
21333 ** %S Insert the first element of a SrcList
21335 ** This function should be used to report any error that occurs whilst
21336 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21337 ** last thing the sqlite3_prepare() function does is copy the error
21338 ** stored by this function into the database handle using sqlite3Error().
21339 ** Function sqlite3Error() should be used during statement execution
21340 ** (sqlite3_step() etc.).
21342 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21343 char *zMsg;
21344 va_list ap;
21345 sqlite3 *db = pParse->db;
21346 va_start(ap, zFormat);
21347 zMsg = sqlite3VMPrintf(db, zFormat, ap);
21348 va_end(ap);
21349 if( db->suppressErr ){
21350 sqlite3DbFree(db, zMsg);
21351 }else{
21352 pParse->nErr++;
21353 sqlite3DbFree(db, pParse->zErrMsg);
21354 pParse->zErrMsg = zMsg;
21355 pParse->rc = SQLITE_ERROR;
21360 ** Convert an SQL-style quoted string into a normal string by removing
21361 ** the quote characters. The conversion is done in-place. If the
21362 ** input does not begin with a quote character, then this routine
21363 ** is a no-op.
21365 ** The input string must be zero-terminated. A new zero-terminator
21366 ** is added to the dequoted string.
21368 ** The return value is -1 if no dequoting occurs or the length of the
21369 ** dequoted string, exclusive of the zero terminator, if dequoting does
21370 ** occur.
21372 ** 2002-Feb-14: This routine is extended to remove MS-Access style
21373 ** brackets from around identifers. For example: "[a-b-c]" becomes
21374 ** "a-b-c".
21376 SQLITE_PRIVATE int sqlite3Dequote(char *z){
21377 char quote;
21378 int i, j;
21379 if( z==0 ) return -1;
21380 quote = z[0];
21381 switch( quote ){
21382 case '\'': break;
21383 case '"': break;
21384 case '`': break; /* For MySQL compatibility */
21385 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
21386 default: return -1;
21388 for(i=1, j=0; ALWAYS(z[i]); i++){
21389 if( z[i]==quote ){
21390 if( z[i+1]==quote ){
21391 z[j++] = quote;
21392 i++;
21393 }else{
21394 break;
21396 }else{
21397 z[j++] = z[i];
21400 z[j] = 0;
21401 return j;
21404 /* Convenient short-hand */
21405 #define UpperToLower sqlite3UpperToLower
21408 ** Some systems have stricmp(). Others have strcasecmp(). Because
21409 ** there is no consistency, we will define our own.
21411 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21412 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
21413 ** the contents of two buffers containing UTF-8 strings in a
21414 ** case-independent fashion, using the same definition of "case
21415 ** independence" that SQLite uses internally when comparing identifiers.
21417 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21418 register unsigned char *a, *b;
21419 a = (unsigned char *)zLeft;
21420 b = (unsigned char *)zRight;
21421 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21422 return UpperToLower[*a] - UpperToLower[*b];
21424 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21425 register unsigned char *a, *b;
21426 a = (unsigned char *)zLeft;
21427 b = (unsigned char *)zRight;
21428 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21429 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21433 ** The string z[] is an text representation of a real number.
21434 ** Convert this string to a double and write it into *pResult.
21436 ** The string z[] is length bytes in length (bytes, not characters) and
21437 ** uses the encoding enc. The string is not necessarily zero-terminated.
21439 ** Return TRUE if the result is a valid real number (or integer) and FALSE
21440 ** if the string is empty or contains extraneous text. Valid numbers
21441 ** are in one of these formats:
21443 ** [+-]digits[E[+-]digits]
21444 ** [+-]digits.[digits][E[+-]digits]
21445 ** [+-].digits[E[+-]digits]
21447 ** Leading and trailing whitespace is ignored for the purpose of determining
21448 ** validity.
21450 ** If some prefix of the input string is a valid number, this routine
21451 ** returns FALSE but it still converts the prefix and writes the result
21452 ** into *pResult.
21454 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21455 #ifndef SQLITE_OMIT_FLOATING_POINT
21456 int incr;
21457 const char *zEnd = z + length;
21458 /* sign * significand * (10 ^ (esign * exponent)) */
21459 int sign = 1; /* sign of significand */
21460 i64 s = 0; /* significand */
21461 int d = 0; /* adjust exponent for shifting decimal point */
21462 int esign = 1; /* sign of exponent */
21463 int e = 0; /* exponent */
21464 int eValid = 1; /* True exponent is either not used or is well-formed */
21465 double result;
21466 int nDigits = 0;
21467 int nonNum = 0;
21469 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21470 *pResult = 0.0; /* Default return value, in case of an error */
21472 if( enc==SQLITE_UTF8 ){
21473 incr = 1;
21474 }else{
21475 int i;
21476 incr = 2;
21477 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21478 for(i=3-enc; i<length && z[i]==0; i+=2){}
21479 nonNum = i<length;
21480 zEnd = z+i+enc-3;
21481 z += (enc&1);
21484 /* skip leading spaces */
21485 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21486 if( z>=zEnd ) return 0;
21488 /* get sign of significand */
21489 if( *z=='-' ){
21490 sign = -1;
21491 z+=incr;
21492 }else if( *z=='+' ){
21493 z+=incr;
21496 /* skip leading zeroes */
21497 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21499 /* copy max significant digits to significand */
21500 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21501 s = s*10 + (*z - '0');
21502 z+=incr, nDigits++;
21505 /* skip non-significant significand digits
21506 ** (increase exponent by d to shift decimal left) */
21507 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21508 if( z>=zEnd ) goto do_atof_calc;
21510 /* if decimal point is present */
21511 if( *z=='.' ){
21512 z+=incr;
21513 /* copy digits from after decimal to significand
21514 ** (decrease exponent by d to shift decimal right) */
21515 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21516 s = s*10 + (*z - '0');
21517 z+=incr, nDigits++, d--;
21519 /* skip non-significant digits */
21520 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21522 if( z>=zEnd ) goto do_atof_calc;
21524 /* if exponent is present */
21525 if( *z=='e' || *z=='E' ){
21526 z+=incr;
21527 eValid = 0;
21528 if( z>=zEnd ) goto do_atof_calc;
21529 /* get sign of exponent */
21530 if( *z=='-' ){
21531 esign = -1;
21532 z+=incr;
21533 }else if( *z=='+' ){
21534 z+=incr;
21536 /* copy digits to exponent */
21537 while( z<zEnd && sqlite3Isdigit(*z) ){
21538 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21539 z+=incr;
21540 eValid = 1;
21544 /* skip trailing spaces */
21545 if( nDigits && eValid ){
21546 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21549 do_atof_calc:
21550 /* adjust exponent by d, and update sign */
21551 e = (e*esign) + d;
21552 if( e<0 ) {
21553 esign = -1;
21554 e *= -1;
21555 } else {
21556 esign = 1;
21559 /* if 0 significand */
21560 if( !s ) {
21561 /* In the IEEE 754 standard, zero is signed.
21562 ** Add the sign if we've seen at least one digit */
21563 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21564 } else {
21565 /* attempt to reduce exponent */
21566 if( esign>0 ){
21567 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21568 }else{
21569 while( !(s%10) && e>0 ) e--,s/=10;
21572 /* adjust the sign of significand */
21573 s = sign<0 ? -s : s;
21575 /* if exponent, scale significand as appropriate
21576 ** and store in result. */
21577 if( e ){
21578 LONGDOUBLE_TYPE scale = 1.0;
21579 /* attempt to handle extremely small/large numbers better */
21580 if( e>307 && e<342 ){
21581 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21582 if( esign<0 ){
21583 result = s / scale;
21584 result /= 1.0e+308;
21585 }else{
21586 result = s * scale;
21587 result *= 1.0e+308;
21589 }else if( e>=342 ){
21590 if( esign<0 ){
21591 result = 0.0*s;
21592 }else{
21593 result = 1e308*1e308*s; /* Infinity */
21595 }else{
21596 /* 1.0e+22 is the largest power of 10 than can be
21597 ** represented exactly. */
21598 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21599 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21600 if( esign<0 ){
21601 result = s / scale;
21602 }else{
21603 result = s * scale;
21606 } else {
21607 result = (double)s;
21611 /* store the result */
21612 *pResult = result;
21614 /* return true if number and no extra non-whitespace chracters after */
21615 return z>=zEnd && nDigits>0 && eValid && nonNum==0;
21616 #else
21617 return !sqlite3Atoi64(z, pResult, length, enc);
21618 #endif /* SQLITE_OMIT_FLOATING_POINT */
21622 ** Compare the 19-character string zNum against the text representation
21623 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
21624 ** if zNum is less than, equal to, or greater than the string.
21625 ** Note that zNum must contain exactly 19 characters.
21627 ** Unlike memcmp() this routine is guaranteed to return the difference
21628 ** in the values of the last digit if the only difference is in the
21629 ** last digit. So, for example,
21631 ** compare2pow63("9223372036854775800", 1)
21633 ** will return -8.
21635 static int compare2pow63(const char *zNum, int incr){
21636 int c = 0;
21637 int i;
21638 /* 012345678901234567 */
21639 const char *pow63 = "922337203685477580";
21640 for(i=0; c==0 && i<18; i++){
21641 c = (zNum[i*incr]-pow63[i])*10;
21643 if( c==0 ){
21644 c = zNum[18*incr] - '8';
21645 testcase( c==(-1) );
21646 testcase( c==0 );
21647 testcase( c==(+1) );
21649 return c;
21654 ** Convert zNum to a 64-bit signed integer.
21656 ** If the zNum value is representable as a 64-bit twos-complement
21657 ** integer, then write that value into *pNum and return 0.
21659 ** If zNum is exactly 9223372036854665808, return 2. This special
21660 ** case is broken out because while 9223372036854665808 cannot be a
21661 ** signed 64-bit integer, its negative -9223372036854665808 can be.
21663 ** If zNum is too big for a 64-bit integer and is not
21664 ** 9223372036854665808 or if zNum contains any non-numeric text,
21665 ** then return 1.
21667 ** length is the number of bytes in the string (bytes, not characters).
21668 ** The string is not necessarily zero-terminated. The encoding is
21669 ** given by enc.
21671 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21672 int incr;
21673 u64 u = 0;
21674 int neg = 0; /* assume positive */
21675 int i;
21676 int c = 0;
21677 int nonNum = 0;
21678 const char *zStart;
21679 const char *zEnd = zNum + length;
21680 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21681 if( enc==SQLITE_UTF8 ){
21682 incr = 1;
21683 }else{
21684 incr = 2;
21685 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21686 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
21687 nonNum = i<length;
21688 zEnd = zNum+i+enc-3;
21689 zNum += (enc&1);
21691 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21692 if( zNum<zEnd ){
21693 if( *zNum=='-' ){
21694 neg = 1;
21695 zNum+=incr;
21696 }else if( *zNum=='+' ){
21697 zNum+=incr;
21700 zStart = zNum;
21701 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21702 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21703 u = u*10 + c - '0';
21705 if( u>LARGEST_INT64 ){
21706 *pNum = SMALLEST_INT64;
21707 }else if( neg ){
21708 *pNum = -(i64)u;
21709 }else{
21710 *pNum = (i64)u;
21712 testcase( i==18 );
21713 testcase( i==19 );
21714 testcase( i==20 );
21715 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
21716 /* zNum is empty or contains non-numeric text or is longer
21717 ** than 19 digits (thus guaranteeing that it is too large) */
21718 return 1;
21719 }else if( i<19*incr ){
21720 /* Less than 19 digits, so we know that it fits in 64 bits */
21721 assert( u<=LARGEST_INT64 );
21722 return 0;
21723 }else{
21724 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
21725 c = compare2pow63(zNum, incr);
21726 if( c<0 ){
21727 /* zNum is less than 9223372036854775808 so it fits */
21728 assert( u<=LARGEST_INT64 );
21729 return 0;
21730 }else if( c>0 ){
21731 /* zNum is greater than 9223372036854775808 so it overflows */
21732 return 1;
21733 }else{
21734 /* zNum is exactly 9223372036854775808. Fits if negative. The
21735 ** special case 2 overflow if positive */
21736 assert( u-1==LARGEST_INT64 );
21737 assert( (*pNum)==SMALLEST_INT64 );
21738 return neg ? 0 : 2;
21744 ** If zNum represents an integer that will fit in 32-bits, then set
21745 ** *pValue to that integer and return true. Otherwise return false.
21747 ** Any non-numeric characters that following zNum are ignored.
21748 ** This is different from sqlite3Atoi64() which requires the
21749 ** input number to be zero-terminated.
21751 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21752 sqlite_int64 v = 0;
21753 int i, c;
21754 int neg = 0;
21755 if( zNum[0]=='-' ){
21756 neg = 1;
21757 zNum++;
21758 }else if( zNum[0]=='+' ){
21759 zNum++;
21761 while( zNum[0]=='0' ) zNum++;
21762 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21763 v = v*10 + c;
21766 /* The longest decimal representation of a 32 bit integer is 10 digits:
21768 ** 1234567890
21769 ** 2^31 -> 2147483648
21771 testcase( i==10 );
21772 if( i>10 ){
21773 return 0;
21775 testcase( v-neg==2147483647 );
21776 if( v-neg>2147483647 ){
21777 return 0;
21779 if( neg ){
21780 v = -v;
21782 *pValue = (int)v;
21783 return 1;
21787 ** Return a 32-bit integer value extracted from a string. If the
21788 ** string is not an integer, just return 0.
21790 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21791 int x = 0;
21792 if( z ) sqlite3GetInt32(z, &x);
21793 return x;
21797 ** The variable-length integer encoding is as follows:
21799 ** KEY:
21800 ** A = 0xxxxxxx 7 bits of data and one flag bit
21801 ** B = 1xxxxxxx 7 bits of data and one flag bit
21802 ** C = xxxxxxxx 8 bits of data
21804 ** 7 bits - A
21805 ** 14 bits - BA
21806 ** 21 bits - BBA
21807 ** 28 bits - BBBA
21808 ** 35 bits - BBBBA
21809 ** 42 bits - BBBBBA
21810 ** 49 bits - BBBBBBA
21811 ** 56 bits - BBBBBBBA
21812 ** 64 bits - BBBBBBBBC
21816 ** Write a 64-bit variable-length integer to memory starting at p[0].
21817 ** The length of data write will be between 1 and 9 bytes. The number
21818 ** of bytes written is returned.
21820 ** A variable-length integer consists of the lower 7 bits of each byte
21821 ** for all bytes that have the 8th bit set and one byte with the 8th
21822 ** bit clear. Except, if we get to the 9th byte, it stores the full
21823 ** 8 bits and is the last byte.
21825 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21826 int i, j, n;
21827 u8 buf[10];
21828 if( v & (((u64)0xff000000)<<32) ){
21829 p[8] = (u8)v;
21830 v >>= 8;
21831 for(i=7; i>=0; i--){
21832 p[i] = (u8)((v & 0x7f) | 0x80);
21833 v >>= 7;
21835 return 9;
21837 n = 0;
21839 buf[n++] = (u8)((v & 0x7f) | 0x80);
21840 v >>= 7;
21841 }while( v!=0 );
21842 buf[0] &= 0x7f;
21843 assert( n<=9 );
21844 for(i=0, j=n-1; j>=0; j--, i++){
21845 p[i] = buf[j];
21847 return n;
21851 ** This routine is a faster version of sqlite3PutVarint() that only
21852 ** works for 32-bit positive integers and which is optimized for
21853 ** the common case of small integers. A MACRO version, putVarint32,
21854 ** is provided which inlines the single-byte case. All code should use
21855 ** the MACRO version as this function assumes the single-byte case has
21856 ** already been handled.
21858 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21859 #ifndef putVarint32
21860 if( (v & ~0x7f)==0 ){
21861 p[0] = v;
21862 return 1;
21864 #endif
21865 if( (v & ~0x3fff)==0 ){
21866 p[0] = (u8)((v>>7) | 0x80);
21867 p[1] = (u8)(v & 0x7f);
21868 return 2;
21870 return sqlite3PutVarint(p, v);
21874 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
21875 ** are defined here rather than simply putting the constant expressions
21876 ** inline in order to work around bugs in the RVT compiler.
21878 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
21880 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
21882 #define SLOT_2_0 0x001fc07f
21883 #define SLOT_4_2_0 0xf01fc07f
21887 ** Read a 64-bit variable-length integer from memory starting at p[0].
21888 ** Return the number of bytes read. The value is stored in *v.
21890 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21891 u32 a,b,s;
21893 a = *p;
21894 /* a: p0 (unmasked) */
21895 if (!(a&0x80))
21897 *v = a;
21898 return 1;
21901 p++;
21902 b = *p;
21903 /* b: p1 (unmasked) */
21904 if (!(b&0x80))
21906 a &= 0x7f;
21907 a = a<<7;
21908 a |= b;
21909 *v = a;
21910 return 2;
21913 /* Verify that constants are precomputed correctly */
21914 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21915 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21917 p++;
21918 a = a<<14;
21919 a |= *p;
21920 /* a: p0<<14 | p2 (unmasked) */
21921 if (!(a&0x80))
21923 a &= SLOT_2_0;
21924 b &= 0x7f;
21925 b = b<<7;
21926 a |= b;
21927 *v = a;
21928 return 3;
21931 /* CSE1 from below */
21932 a &= SLOT_2_0;
21933 p++;
21934 b = b<<14;
21935 b |= *p;
21936 /* b: p1<<14 | p3 (unmasked) */
21937 if (!(b&0x80))
21939 b &= SLOT_2_0;
21940 /* moved CSE1 up */
21941 /* a &= (0x7f<<14)|(0x7f); */
21942 a = a<<7;
21943 a |= b;
21944 *v = a;
21945 return 4;
21948 /* a: p0<<14 | p2 (masked) */
21949 /* b: p1<<14 | p3 (unmasked) */
21950 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21951 /* moved CSE1 up */
21952 /* a &= (0x7f<<14)|(0x7f); */
21953 b &= SLOT_2_0;
21954 s = a;
21955 /* s: p0<<14 | p2 (masked) */
21957 p++;
21958 a = a<<14;
21959 a |= *p;
21960 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21961 if (!(a&0x80))
21963 /* we can skip these cause they were (effectively) done above in calc'ing s */
21964 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21965 /* b &= (0x7f<<14)|(0x7f); */
21966 b = b<<7;
21967 a |= b;
21968 s = s>>18;
21969 *v = ((u64)s)<<32 | a;
21970 return 5;
21973 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21974 s = s<<7;
21975 s |= b;
21976 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21978 p++;
21979 b = b<<14;
21980 b |= *p;
21981 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21982 if (!(b&0x80))
21984 /* we can skip this cause it was (effectively) done above in calc'ing s */
21985 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21986 a &= SLOT_2_0;
21987 a = a<<7;
21988 a |= b;
21989 s = s>>18;
21990 *v = ((u64)s)<<32 | a;
21991 return 6;
21994 p++;
21995 a = a<<14;
21996 a |= *p;
21997 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21998 if (!(a&0x80))
22000 a &= SLOT_4_2_0;
22001 b &= SLOT_2_0;
22002 b = b<<7;
22003 a |= b;
22004 s = s>>11;
22005 *v = ((u64)s)<<32 | a;
22006 return 7;
22009 /* CSE2 from below */
22010 a &= SLOT_2_0;
22011 p++;
22012 b = b<<14;
22013 b |= *p;
22014 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
22015 if (!(b&0x80))
22017 b &= SLOT_4_2_0;
22018 /* moved CSE2 up */
22019 /* a &= (0x7f<<14)|(0x7f); */
22020 a = a<<7;
22021 a |= b;
22022 s = s>>4;
22023 *v = ((u64)s)<<32 | a;
22024 return 8;
22027 p++;
22028 a = a<<15;
22029 a |= *p;
22030 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
22032 /* moved CSE2 up */
22033 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
22034 b &= SLOT_2_0;
22035 b = b<<8;
22036 a |= b;
22038 s = s<<4;
22039 b = p[-4];
22040 b &= 0x7f;
22041 b = b>>3;
22042 s |= b;
22044 *v = ((u64)s)<<32 | a;
22046 return 9;
22050 ** Read a 32-bit variable-length integer from memory starting at p[0].
22051 ** Return the number of bytes read. The value is stored in *v.
22053 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
22054 ** integer, then set *v to 0xffffffff.
22056 ** A MACRO version, getVarint32, is provided which inlines the
22057 ** single-byte case. All code should use the MACRO version as
22058 ** this function assumes the single-byte case has already been handled.
22060 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
22061 u32 a,b;
22063 /* The 1-byte case. Overwhelmingly the most common. Handled inline
22064 ** by the getVarin32() macro */
22065 a = *p;
22066 /* a: p0 (unmasked) */
22067 #ifndef getVarint32
22068 if (!(a&0x80))
22070 /* Values between 0 and 127 */
22071 *v = a;
22072 return 1;
22074 #endif
22076 /* The 2-byte case */
22077 p++;
22078 b = *p;
22079 /* b: p1 (unmasked) */
22080 if (!(b&0x80))
22082 /* Values between 128 and 16383 */
22083 a &= 0x7f;
22084 a = a<<7;
22085 *v = a | b;
22086 return 2;
22089 /* The 3-byte case */
22090 p++;
22091 a = a<<14;
22092 a |= *p;
22093 /* a: p0<<14 | p2 (unmasked) */
22094 if (!(a&0x80))
22096 /* Values between 16384 and 2097151 */
22097 a &= (0x7f<<14)|(0x7f);
22098 b &= 0x7f;
22099 b = b<<7;
22100 *v = a | b;
22101 return 3;
22104 /* A 32-bit varint is used to store size information in btrees.
22105 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
22106 ** A 3-byte varint is sufficient, for example, to record the size
22107 ** of a 1048569-byte BLOB or string.
22109 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
22110 ** rare larger cases can be handled by the slower 64-bit varint
22111 ** routine.
22113 #if 1
22115 u64 v64;
22116 u8 n;
22118 p -= 2;
22119 n = sqlite3GetVarint(p, &v64);
22120 assert( n>3 && n<=9 );
22121 if( (v64 & SQLITE_MAX_U32)!=v64 ){
22122 *v = 0xffffffff;
22123 }else{
22124 *v = (u32)v64;
22126 return n;
22129 #else
22130 /* For following code (kept for historical record only) shows an
22131 ** unrolling for the 3- and 4-byte varint cases. This code is
22132 ** slightly faster, but it is also larger and much harder to test.
22134 p++;
22135 b = b<<14;
22136 b |= *p;
22137 /* b: p1<<14 | p3 (unmasked) */
22138 if (!(b&0x80))
22140 /* Values between 2097152 and 268435455 */
22141 b &= (0x7f<<14)|(0x7f);
22142 a &= (0x7f<<14)|(0x7f);
22143 a = a<<7;
22144 *v = a | b;
22145 return 4;
22148 p++;
22149 a = a<<14;
22150 a |= *p;
22151 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22152 if (!(a&0x80))
22154 /* Values between 268435456 and 34359738367 */
22155 a &= SLOT_4_2_0;
22156 b &= SLOT_4_2_0;
22157 b = b<<7;
22158 *v = a | b;
22159 return 5;
22162 /* We can only reach this point when reading a corrupt database
22163 ** file. In that case we are not in any hurry. Use the (relatively
22164 ** slow) general-purpose sqlite3GetVarint() routine to extract the
22165 ** value. */
22167 u64 v64;
22168 u8 n;
22170 p -= 4;
22171 n = sqlite3GetVarint(p, &v64);
22172 assert( n>5 && n<=9 );
22173 *v = (u32)v64;
22174 return n;
22176 #endif
22180 ** Return the number of bytes that will be needed to store the given
22181 ** 64-bit integer.
22183 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22184 int i = 0;
22186 i++;
22187 v >>= 7;
22188 }while( v!=0 && ALWAYS(i<9) );
22189 return i;
22194 ** Read or write a four-byte big-endian integer value.
22196 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22197 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22199 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22200 p[0] = (u8)(v>>24);
22201 p[1] = (u8)(v>>16);
22202 p[2] = (u8)(v>>8);
22203 p[3] = (u8)v;
22209 ** Translate a single byte of Hex into an integer.
22210 ** This routine only works if h really is a valid hexadecimal
22211 ** character: 0..9a..fA..F
22213 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22214 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
22215 #ifdef SQLITE_ASCII
22216 h += 9*(1&(h>>6));
22217 #endif
22218 #ifdef SQLITE_EBCDIC
22219 h += 9*(1&~(h>>4));
22220 #endif
22221 return (u8)(h & 0xf);
22224 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22226 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22227 ** value. Return a pointer to its binary value. Space to hold the
22228 ** binary value has been obtained from malloc and must be freed by
22229 ** the calling routine.
22231 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22232 char *zBlob;
22233 int i;
22235 zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22236 n--;
22237 if( zBlob ){
22238 for(i=0; i<n; i+=2){
22239 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22241 zBlob[i/2] = 0;
22243 return zBlob;
22245 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22248 ** Log an error that is an API call on a connection pointer that should
22249 ** not have been used. The "type" of connection pointer is given as the
22250 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
22252 static void logBadConnection(const char *zType){
22253 sqlite3_log(SQLITE_MISUSE,
22254 "API call with %s database connection pointer",
22255 zType
22260 ** Check to make sure we have a valid db pointer. This test is not
22261 ** foolproof but it does provide some measure of protection against
22262 ** misuse of the interface such as passing in db pointers that are
22263 ** NULL or which have been previously closed. If this routine returns
22264 ** 1 it means that the db pointer is valid and 0 if it should not be
22265 ** dereferenced for any reason. The calling function should invoke
22266 ** SQLITE_MISUSE immediately.
22268 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22269 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22270 ** open properly and is not fit for general use but which can be
22271 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
22273 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22274 u32 magic;
22275 if( db==0 ){
22276 logBadConnection("NULL");
22277 return 0;
22279 magic = db->magic;
22280 if( magic!=SQLITE_MAGIC_OPEN ){
22281 if( sqlite3SafetyCheckSickOrOk(db) ){
22282 testcase( sqlite3GlobalConfig.xLog!=0 );
22283 logBadConnection("unopened");
22285 return 0;
22286 }else{
22287 return 1;
22290 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22291 u32 magic;
22292 magic = db->magic;
22293 if( magic!=SQLITE_MAGIC_SICK &&
22294 magic!=SQLITE_MAGIC_OPEN &&
22295 magic!=SQLITE_MAGIC_BUSY ){
22296 testcase( sqlite3GlobalConfig.xLog!=0 );
22297 logBadConnection("invalid");
22298 return 0;
22299 }else{
22300 return 1;
22305 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
22306 ** the other 64-bit signed integer at *pA and store the result in *pA.
22307 ** Return 0 on success. Or if the operation would have resulted in an
22308 ** overflow, leave *pA unchanged and return 1.
22310 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22311 i64 iA = *pA;
22312 testcase( iA==0 ); testcase( iA==1 );
22313 testcase( iB==-1 ); testcase( iB==0 );
22314 if( iB>=0 ){
22315 testcase( iA>0 && LARGEST_INT64 - iA == iB );
22316 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22317 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22318 *pA += iB;
22319 }else{
22320 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22321 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22322 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22323 *pA += iB;
22325 return 0;
22327 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22328 testcase( iB==SMALLEST_INT64+1 );
22329 if( iB==SMALLEST_INT64 ){
22330 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22331 if( (*pA)>=0 ) return 1;
22332 *pA -= iB;
22333 return 0;
22334 }else{
22335 return sqlite3AddInt64(pA, -iB);
22338 #define TWOPOWER32 (((i64)1)<<32)
22339 #define TWOPOWER31 (((i64)1)<<31)
22340 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22341 i64 iA = *pA;
22342 i64 iA1, iA0, iB1, iB0, r;
22344 iA1 = iA/TWOPOWER32;
22345 iA0 = iA % TWOPOWER32;
22346 iB1 = iB/TWOPOWER32;
22347 iB0 = iB % TWOPOWER32;
22348 if( iA1*iB1 != 0 ) return 1;
22349 assert( iA1*iB0==0 || iA0*iB1==0 );
22350 r = iA1*iB0 + iA0*iB1;
22351 testcase( r==(-TWOPOWER31)-1 );
22352 testcase( r==(-TWOPOWER31) );
22353 testcase( r==TWOPOWER31 );
22354 testcase( r==TWOPOWER31-1 );
22355 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22356 r *= TWOPOWER32;
22357 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22358 *pA = r;
22359 return 0;
22363 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
22364 ** if the integer has a value of -2147483648, return +2147483647
22366 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22367 if( x>=0 ) return x;
22368 if( x==(int)0x80000000 ) return 0x7fffffff;
22369 return -x;
22372 #ifdef SQLITE_ENABLE_8_3_NAMES
22374 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22375 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22376 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22377 ** three characters, then shorten the suffix on z[] to be the last three
22378 ** characters of the original suffix.
22380 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22381 ** do the suffix shortening regardless of URI parameter.
22383 ** Examples:
22385 ** test.db-journal => test.nal
22386 ** test.db-wal => test.wal
22387 ** test.db-shm => test.shm
22388 ** test.db-mj7f3319fa => test.9fa
22390 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22391 #if SQLITE_ENABLE_8_3_NAMES<2
22392 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22393 #endif
22395 int i, sz;
22396 sz = sqlite3Strlen30(z);
22397 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22398 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22401 #endif
22403 /************** End of util.c ************************************************/
22404 /************** Begin file hash.c ********************************************/
22406 ** 2001 September 22
22408 ** The author disclaims copyright to this source code. In place of
22409 ** a legal notice, here is a blessing:
22411 ** May you do good and not evil.
22412 ** May you find forgiveness for yourself and forgive others.
22413 ** May you share freely, never taking more than you give.
22415 *************************************************************************
22416 ** This is the implementation of generic hash-tables
22417 ** used in SQLite.
22419 /* #include <assert.h> */
22421 /* Turn bulk memory into a hash table object by initializing the
22422 ** fields of the Hash structure.
22424 ** "pNew" is a pointer to the hash table that is to be initialized.
22426 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22427 assert( pNew!=0 );
22428 pNew->first = 0;
22429 pNew->count = 0;
22430 pNew->htsize = 0;
22431 pNew->ht = 0;
22434 /* Remove all entries from a hash table. Reclaim all memory.
22435 ** Call this routine to delete a hash table or to reset a hash table
22436 ** to the empty state.
22438 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22439 HashElem *elem; /* For looping over all elements of the table */
22441 assert( pH!=0 );
22442 elem = pH->first;
22443 pH->first = 0;
22444 sqlite3_free(pH->ht);
22445 pH->ht = 0;
22446 pH->htsize = 0;
22447 while( elem ){
22448 HashElem *next_elem = elem->next;
22449 sqlite3_free(elem);
22450 elem = next_elem;
22452 pH->count = 0;
22456 ** The hashing function.
22458 static unsigned int strHash(const char *z, int nKey){
22459 int h = 0;
22460 assert( nKey>=0 );
22461 while( nKey > 0 ){
22462 h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22463 nKey--;
22465 return h;
22469 /* Link pNew element into the hash table pH. If pEntry!=0 then also
22470 ** insert pNew into the pEntry hash bucket.
22472 static void insertElement(
22473 Hash *pH, /* The complete hash table */
22474 struct _ht *pEntry, /* The entry into which pNew is inserted */
22475 HashElem *pNew /* The element to be inserted */
22477 HashElem *pHead; /* First element already in pEntry */
22478 if( pEntry ){
22479 pHead = pEntry->count ? pEntry->chain : 0;
22480 pEntry->count++;
22481 pEntry->chain = pNew;
22482 }else{
22483 pHead = 0;
22485 if( pHead ){
22486 pNew->next = pHead;
22487 pNew->prev = pHead->prev;
22488 if( pHead->prev ){ pHead->prev->next = pNew; }
22489 else { pH->first = pNew; }
22490 pHead->prev = pNew;
22491 }else{
22492 pNew->next = pH->first;
22493 if( pH->first ){ pH->first->prev = pNew; }
22494 pNew->prev = 0;
22495 pH->first = pNew;
22500 /* Resize the hash table so that it cantains "new_size" buckets.
22502 ** The hash table might fail to resize if sqlite3_malloc() fails or
22503 ** if the new size is the same as the prior size.
22504 ** Return TRUE if the resize occurs and false if not.
22506 static int rehash(Hash *pH, unsigned int new_size){
22507 struct _ht *new_ht; /* The new hash table */
22508 HashElem *elem, *next_elem; /* For looping over existing elements */
22510 #if SQLITE_MALLOC_SOFT_LIMIT>0
22511 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22512 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22514 if( new_size==pH->htsize ) return 0;
22515 #endif
22517 /* The inability to allocates space for a larger hash table is
22518 ** a performance hit but it is not a fatal error. So mark the
22519 ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
22520 ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
22521 ** only zeroes the requested number of bytes whereas this module will
22522 ** use the actual amount of space allocated for the hash table (which
22523 ** may be larger than the requested amount).
22525 sqlite3BeginBenignMalloc();
22526 new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22527 sqlite3EndBenignMalloc();
22529 if( new_ht==0 ) return 0;
22530 sqlite3_free(pH->ht);
22531 pH->ht = new_ht;
22532 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22533 memset(new_ht, 0, new_size*sizeof(struct _ht));
22534 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22535 unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22536 next_elem = elem->next;
22537 insertElement(pH, &new_ht[h], elem);
22539 return 1;
22542 /* This function (for internal use only) locates an element in an
22543 ** hash table that matches the given key. The hash for this key has
22544 ** already been computed and is passed as the 4th parameter.
22546 static HashElem *findElementGivenHash(
22547 const Hash *pH, /* The pH to be searched */
22548 const char *pKey, /* The key we are searching for */
22549 int nKey, /* Bytes in key (not counting zero terminator) */
22550 unsigned int h /* The hash for this key. */
22552 HashElem *elem; /* Used to loop thru the element list */
22553 int count; /* Number of elements left to test */
22555 if( pH->ht ){
22556 struct _ht *pEntry = &pH->ht[h];
22557 elem = pEntry->chain;
22558 count = pEntry->count;
22559 }else{
22560 elem = pH->first;
22561 count = pH->count;
22563 while( count-- && ALWAYS(elem) ){
22564 if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
22565 return elem;
22567 elem = elem->next;
22569 return 0;
22572 /* Remove a single entry from the hash table given a pointer to that
22573 ** element and a hash on the element's key.
22575 static void removeElementGivenHash(
22576 Hash *pH, /* The pH containing "elem" */
22577 HashElem* elem, /* The element to be removed from the pH */
22578 unsigned int h /* Hash value for the element */
22580 struct _ht *pEntry;
22581 if( elem->prev ){
22582 elem->prev->next = elem->next;
22583 }else{
22584 pH->first = elem->next;
22586 if( elem->next ){
22587 elem->next->prev = elem->prev;
22589 if( pH->ht ){
22590 pEntry = &pH->ht[h];
22591 if( pEntry->chain==elem ){
22592 pEntry->chain = elem->next;
22594 pEntry->count--;
22595 assert( pEntry->count>=0 );
22597 sqlite3_free( elem );
22598 pH->count--;
22599 if( pH->count==0 ){
22600 assert( pH->first==0 );
22601 assert( pH->count==0 );
22602 sqlite3HashClear(pH);
22606 /* Attempt to locate an element of the hash table pH with a key
22607 ** that matches pKey,nKey. Return the data for this element if it is
22608 ** found, or NULL if there is no match.
22610 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22611 HashElem *elem; /* The element that matches key */
22612 unsigned int h; /* A hash on key */
22614 assert( pH!=0 );
22615 assert( pKey!=0 );
22616 assert( nKey>=0 );
22617 if( pH->ht ){
22618 h = strHash(pKey, nKey) % pH->htsize;
22619 }else{
22620 h = 0;
22622 elem = findElementGivenHash(pH, pKey, nKey, h);
22623 return elem ? elem->data : 0;
22626 /* Insert an element into the hash table pH. The key is pKey,nKey
22627 ** and the data is "data".
22629 ** If no element exists with a matching key, then a new
22630 ** element is created and NULL is returned.
22632 ** If another element already exists with the same key, then the
22633 ** new data replaces the old data and the old data is returned.
22634 ** The key is not copied in this instance. If a malloc fails, then
22635 ** the new data is returned and the hash table is unchanged.
22637 ** If the "data" parameter to this function is NULL, then the
22638 ** element corresponding to "key" is removed from the hash table.
22640 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22641 unsigned int h; /* the hash of the key modulo hash table size */
22642 HashElem *elem; /* Used to loop thru the element list */
22643 HashElem *new_elem; /* New element added to the pH */
22645 assert( pH!=0 );
22646 assert( pKey!=0 );
22647 assert( nKey>=0 );
22648 if( pH->htsize ){
22649 h = strHash(pKey, nKey) % pH->htsize;
22650 }else{
22651 h = 0;
22653 elem = findElementGivenHash(pH,pKey,nKey,h);
22654 if( elem ){
22655 void *old_data = elem->data;
22656 if( data==0 ){
22657 removeElementGivenHash(pH,elem,h);
22658 }else{
22659 elem->data = data;
22660 elem->pKey = pKey;
22661 assert(nKey==elem->nKey);
22663 return old_data;
22665 if( data==0 ) return 0;
22666 new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22667 if( new_elem==0 ) return data;
22668 new_elem->pKey = pKey;
22669 new_elem->nKey = nKey;
22670 new_elem->data = data;
22671 pH->count++;
22672 if( pH->count>=10 && pH->count > 2*pH->htsize ){
22673 if( rehash(pH, pH->count*2) ){
22674 assert( pH->htsize>0 );
22675 h = strHash(pKey, nKey) % pH->htsize;
22678 if( pH->ht ){
22679 insertElement(pH, &pH->ht[h], new_elem);
22680 }else{
22681 insertElement(pH, 0, new_elem);
22683 return 0;
22686 /************** End of hash.c ************************************************/
22687 /************** Begin file opcodes.c *****************************************/
22688 /* Automatically generated. Do not edit */
22689 /* See the mkopcodec.awk script for details. */
22690 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22691 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22692 static const char *const azName[] = { "?",
22693 /* 1 */ "Function",
22694 /* 2 */ "Savepoint",
22695 /* 3 */ "AutoCommit",
22696 /* 4 */ "Transaction",
22697 /* 5 */ "SorterNext",
22698 /* 6 */ "Prev",
22699 /* 7 */ "Next",
22700 /* 8 */ "AggStep",
22701 /* 9 */ "Checkpoint",
22702 /* 10 */ "JournalMode",
22703 /* 11 */ "Vacuum",
22704 /* 12 */ "VFilter",
22705 /* 13 */ "VUpdate",
22706 /* 14 */ "Goto",
22707 /* 15 */ "Gosub",
22708 /* 16 */ "Return",
22709 /* 17 */ "Yield",
22710 /* 18 */ "HaltIfNull",
22711 /* 19 */ "Not",
22712 /* 20 */ "Halt",
22713 /* 21 */ "Integer",
22714 /* 22 */ "Int64",
22715 /* 23 */ "String",
22716 /* 24 */ "Null",
22717 /* 25 */ "Blob",
22718 /* 26 */ "Variable",
22719 /* 27 */ "Move",
22720 /* 28 */ "Copy",
22721 /* 29 */ "SCopy",
22722 /* 30 */ "ResultRow",
22723 /* 31 */ "CollSeq",
22724 /* 32 */ "AddImm",
22725 /* 33 */ "MustBeInt",
22726 /* 34 */ "RealAffinity",
22727 /* 35 */ "Permutation",
22728 /* 36 */ "Compare",
22729 /* 37 */ "Jump",
22730 /* 38 */ "Once",
22731 /* 39 */ "If",
22732 /* 40 */ "IfNot",
22733 /* 41 */ "Column",
22734 /* 42 */ "Affinity",
22735 /* 43 */ "MakeRecord",
22736 /* 44 */ "Count",
22737 /* 45 */ "ReadCookie",
22738 /* 46 */ "SetCookie",
22739 /* 47 */ "VerifyCookie",
22740 /* 48 */ "OpenRead",
22741 /* 49 */ "OpenWrite",
22742 /* 50 */ "OpenAutoindex",
22743 /* 51 */ "OpenEphemeral",
22744 /* 52 */ "SorterOpen",
22745 /* 53 */ "OpenPseudo",
22746 /* 54 */ "Close",
22747 /* 55 */ "SeekLt",
22748 /* 56 */ "SeekLe",
22749 /* 57 */ "SeekGe",
22750 /* 58 */ "SeekGt",
22751 /* 59 */ "Seek",
22752 /* 60 */ "NotFound",
22753 /* 61 */ "Found",
22754 /* 62 */ "IsUnique",
22755 /* 63 */ "NotExists",
22756 /* 64 */ "Sequence",
22757 /* 65 */ "NewRowid",
22758 /* 66 */ "Insert",
22759 /* 67 */ "InsertInt",
22760 /* 68 */ "Or",
22761 /* 69 */ "And",
22762 /* 70 */ "Delete",
22763 /* 71 */ "ResetCount",
22764 /* 72 */ "SorterCompare",
22765 /* 73 */ "IsNull",
22766 /* 74 */ "NotNull",
22767 /* 75 */ "Ne",
22768 /* 76 */ "Eq",
22769 /* 77 */ "Gt",
22770 /* 78 */ "Le",
22771 /* 79 */ "Lt",
22772 /* 80 */ "Ge",
22773 /* 81 */ "SorterData",
22774 /* 82 */ "BitAnd",
22775 /* 83 */ "BitOr",
22776 /* 84 */ "ShiftLeft",
22777 /* 85 */ "ShiftRight",
22778 /* 86 */ "Add",
22779 /* 87 */ "Subtract",
22780 /* 88 */ "Multiply",
22781 /* 89 */ "Divide",
22782 /* 90 */ "Remainder",
22783 /* 91 */ "Concat",
22784 /* 92 */ "RowKey",
22785 /* 93 */ "BitNot",
22786 /* 94 */ "String8",
22787 /* 95 */ "RowData",
22788 /* 96 */ "Rowid",
22789 /* 97 */ "NullRow",
22790 /* 98 */ "Last",
22791 /* 99 */ "SorterSort",
22792 /* 100 */ "Sort",
22793 /* 101 */ "Rewind",
22794 /* 102 */ "SorterInsert",
22795 /* 103 */ "IdxInsert",
22796 /* 104 */ "IdxDelete",
22797 /* 105 */ "IdxRowid",
22798 /* 106 */ "IdxLT",
22799 /* 107 */ "IdxGE",
22800 /* 108 */ "Destroy",
22801 /* 109 */ "Clear",
22802 /* 110 */ "CreateIndex",
22803 /* 111 */ "CreateTable",
22804 /* 112 */ "ParseSchema",
22805 /* 113 */ "LoadAnalysis",
22806 /* 114 */ "DropTable",
22807 /* 115 */ "DropIndex",
22808 /* 116 */ "DropTrigger",
22809 /* 117 */ "IntegrityCk",
22810 /* 118 */ "RowSetAdd",
22811 /* 119 */ "RowSetRead",
22812 /* 120 */ "RowSetTest",
22813 /* 121 */ "Program",
22814 /* 122 */ "Param",
22815 /* 123 */ "FkCounter",
22816 /* 124 */ "FkIfZero",
22817 /* 125 */ "MemMax",
22818 /* 126 */ "IfPos",
22819 /* 127 */ "IfNeg",
22820 /* 128 */ "IfZero",
22821 /* 129 */ "AggFinal",
22822 /* 130 */ "Real",
22823 /* 131 */ "IncrVacuum",
22824 /* 132 */ "Expire",
22825 /* 133 */ "TableLock",
22826 /* 134 */ "VBegin",
22827 /* 135 */ "VCreate",
22828 /* 136 */ "VDestroy",
22829 /* 137 */ "VOpen",
22830 /* 138 */ "VColumn",
22831 /* 139 */ "VNext",
22832 /* 140 */ "VRename",
22833 /* 141 */ "ToText",
22834 /* 142 */ "ToBlob",
22835 /* 143 */ "ToNumeric",
22836 /* 144 */ "ToInt",
22837 /* 145 */ "ToReal",
22838 /* 146 */ "Pagecount",
22839 /* 147 */ "MaxPgcnt",
22840 /* 148 */ "Trace",
22841 /* 149 */ "Noop",
22842 /* 150 */ "Explain",
22844 return azName[i];
22846 #endif
22848 /************** End of opcodes.c *********************************************/
22849 /************** Begin file os_unix.c *****************************************/
22851 ** 2004 May 22
22853 ** The author disclaims copyright to this source code. In place of
22854 ** a legal notice, here is a blessing:
22856 ** May you do good and not evil.
22857 ** May you find forgiveness for yourself and forgive others.
22858 ** May you share freely, never taking more than you give.
22860 ******************************************************************************
22862 ** This file contains the VFS implementation for unix-like operating systems
22863 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22865 ** There are actually several different VFS implementations in this file.
22866 ** The differences are in the way that file locking is done. The default
22867 ** implementation uses Posix Advisory Locks. Alternative implementations
22868 ** use flock(), dot-files, various proprietary locking schemas, or simply
22869 ** skip locking all together.
22871 ** This source file is organized into divisions where the logic for various
22872 ** subfunctions is contained within the appropriate division. PLEASE
22873 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
22874 ** in the correct division and should be clearly labeled.
22876 ** The layout of divisions is as follows:
22878 ** * General-purpose declarations and utility functions.
22879 ** * Unique file ID logic used by VxWorks.
22880 ** * Various locking primitive implementations (all except proxy locking):
22881 ** + for Posix Advisory Locks
22882 ** + for no-op locks
22883 ** + for dot-file locks
22884 ** + for flock() locking
22885 ** + for named semaphore locks (VxWorks only)
22886 ** + for AFP filesystem locks (MacOSX only)
22887 ** * sqlite3_file methods not associated with locking.
22888 ** * Definitions of sqlite3_io_methods objects for all locking
22889 ** methods plus "finder" functions for each locking method.
22890 ** * sqlite3_vfs method implementations.
22891 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
22892 ** * Definitions of sqlite3_vfs objects for all locking methods
22893 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
22895 #if SQLITE_OS_UNIX /* This file is used on unix only */
22898 ** There are various methods for file locking used for concurrency
22899 ** control:
22901 ** 1. POSIX locking (the default),
22902 ** 2. No locking,
22903 ** 3. Dot-file locking,
22904 ** 4. flock() locking,
22905 ** 5. AFP locking (OSX only),
22906 ** 6. Named POSIX semaphores (VXWorks only),
22907 ** 7. proxy locking. (OSX only)
22909 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22910 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22911 ** selection of the appropriate locking style based on the filesystem
22912 ** where the database is located.
22914 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22915 # if defined(__APPLE__)
22916 # define SQLITE_ENABLE_LOCKING_STYLE 1
22917 # else
22918 # define SQLITE_ENABLE_LOCKING_STYLE 0
22919 # endif
22920 #endif
22923 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
22924 ** vxworks, or 0 otherwise.
22926 #ifndef OS_VXWORKS
22927 # if defined(__RTP__) || defined(_WRS_KERNEL)
22928 # define OS_VXWORKS 1
22929 # else
22930 # define OS_VXWORKS 0
22931 # endif
22932 #endif
22935 ** These #defines should enable >2GB file support on Posix if the
22936 ** underlying operating system supports it. If the OS lacks
22937 ** large file support, these should be no-ops.
22939 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22940 ** on the compiler command line. This is necessary if you are compiling
22941 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22942 ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
22943 ** without this option, LFS is enable. But LFS does not exist in the kernel
22944 ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
22945 ** portability you should omit LFS.
22947 ** The previous paragraph was written in 2005. (This paragraph is written
22948 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22949 ** you should probably leave LFS enabled. But some embedded platforms might
22950 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22952 #ifndef SQLITE_DISABLE_LFS
22953 # define _LARGE_FILE 1
22954 # ifndef _FILE_OFFSET_BITS
22955 # define _FILE_OFFSET_BITS 64
22956 # endif
22957 # define _LARGEFILE_SOURCE 1
22958 #endif
22961 ** standard include files.
22963 #include <sys/types.h>
22964 #include <sys/stat.h>
22965 #include <fcntl.h>
22966 #include <unistd.h>
22967 /* #include <time.h> */
22968 #include <sys/time.h>
22969 #include <errno.h>
22970 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
22971 #include <sys/mman.h>
22972 #endif
22975 #if SQLITE_ENABLE_LOCKING_STYLE
22976 # include <sys/ioctl.h>
22977 # if OS_VXWORKS
22978 # include <semaphore.h>
22979 # include <limits.h>
22980 # else
22981 # include <sys/file.h>
22982 # include <sys/param.h>
22983 # endif
22984 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
22986 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22987 # include <sys/mount.h>
22988 #endif
22990 #ifdef HAVE_UTIME
22991 # include <utime.h>
22992 #endif
22995 ** Allowed values of unixFile.fsFlags
22997 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
23000 ** If we are to be thread-safe, include the pthreads header and define
23001 ** the SQLITE_UNIX_THREADS macro.
23003 #if SQLITE_THREADSAFE
23004 /* # include <pthread.h> */
23005 # define SQLITE_UNIX_THREADS 1
23006 #endif
23009 ** Default permissions when creating a new file
23011 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
23012 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
23013 #endif
23016 ** Default permissions when creating auto proxy dir
23018 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
23019 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
23020 #endif
23023 ** Maximum supported path-length.
23025 #define MAX_PATHNAME 512
23028 ** Only set the lastErrno if the error code is a real error and not
23029 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
23031 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
23033 /* Forward references */
23034 typedef struct unixShm unixShm; /* Connection shared memory */
23035 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
23036 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
23037 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
23040 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
23041 ** cannot be closed immediately. In these cases, instances of the following
23042 ** structure are used to store the file descriptor while waiting for an
23043 ** opportunity to either close or reuse it.
23045 struct UnixUnusedFd {
23046 int fd; /* File descriptor to close */
23047 int flags; /* Flags this file descriptor was opened with */
23048 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
23052 ** The unixFile structure is subclass of sqlite3_file specific to the unix
23053 ** VFS implementations.
23055 typedef struct unixFile unixFile;
23056 struct unixFile {
23057 sqlite3_io_methods const *pMethod; /* Always the first entry */
23058 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
23059 unixInodeInfo *pInode; /* Info about locks on this inode */
23060 int h; /* The file descriptor */
23061 unsigned char eFileLock; /* The type of lock held on this fd */
23062 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
23063 int lastErrno; /* The unix errno from last I/O error */
23064 void *lockingContext; /* Locking style specific state */
23065 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
23066 const char *zPath; /* Name of the file */
23067 unixShm *pShm; /* Shared memory segment information */
23068 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
23069 int nFetchOut; /* Number of outstanding xFetch refs */
23070 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
23071 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
23072 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
23073 void *pMapRegion; /* Memory mapped region */
23074 #ifdef __QNXNTO__
23075 int sectorSize; /* Device sector size */
23076 int deviceCharacteristics; /* Precomputed device characteristics */
23077 #endif
23078 #if SQLITE_ENABLE_LOCKING_STYLE
23079 int openFlags; /* The flags specified at open() */
23080 #endif
23081 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
23082 unsigned fsFlags; /* cached details from statfs() */
23083 #endif
23084 #if OS_VXWORKS
23085 struct vxworksFileId *pId; /* Unique file ID */
23086 #endif
23087 #ifdef SQLITE_DEBUG
23088 /* The next group of variables are used to track whether or not the
23089 ** transaction counter in bytes 24-27 of database files are updated
23090 ** whenever any part of the database changes. An assertion fault will
23091 ** occur if a file is updated without also updating the transaction
23092 ** counter. This test is made to avoid new problems similar to the
23093 ** one described by ticket #3584.
23095 unsigned char transCntrChng; /* True if the transaction counter changed */
23096 unsigned char dbUpdate; /* True if any part of database file changed */
23097 unsigned char inNormalWrite; /* True if in a normal write operation */
23099 #endif
23101 #ifdef SQLITE_TEST
23102 /* In test mode, increase the size of this structure a bit so that
23103 ** it is larger than the struct CrashFile defined in test6.c.
23105 char aPadding[32];
23106 #endif
23110 ** Allowed values for the unixFile.ctrlFlags bitmask:
23112 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
23113 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
23114 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
23115 #ifndef SQLITE_DISABLE_DIRSYNC
23116 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
23117 #else
23118 # define UNIXFILE_DIRSYNC 0x00
23119 #endif
23120 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
23121 #define UNIXFILE_DELETE 0x20 /* Delete on close */
23122 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
23123 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
23124 #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
23127 ** Include code that is common to all os_*.c files
23129 /************** Include os_common.h in the middle of os_unix.c ***************/
23130 /************** Begin file os_common.h ***************************************/
23132 ** 2004 May 22
23134 ** The author disclaims copyright to this source code. In place of
23135 ** a legal notice, here is a blessing:
23137 ** May you do good and not evil.
23138 ** May you find forgiveness for yourself and forgive others.
23139 ** May you share freely, never taking more than you give.
23141 ******************************************************************************
23143 ** This file contains macros and a little bit of code that is common to
23144 ** all of the platform-specific files (os_*.c) and is #included into those
23145 ** files.
23147 ** This file should be #included by the os_*.c files only. It is not a
23148 ** general purpose header file.
23150 #ifndef _OS_COMMON_H_
23151 #define _OS_COMMON_H_
23154 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23155 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23156 ** switch. The following code should catch this problem at compile-time.
23158 #ifdef MEMORY_DEBUG
23159 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
23160 #endif
23162 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23163 # ifndef SQLITE_DEBUG_OS_TRACE
23164 # define SQLITE_DEBUG_OS_TRACE 0
23165 # endif
23166 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
23167 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
23168 #else
23169 # define OSTRACE(X)
23170 #endif
23173 ** Macros for performance tracing. Normally turned off. Only works
23174 ** on i486 hardware.
23176 #ifdef SQLITE_PERFORMANCE_TRACE
23179 ** hwtime.h contains inline assembler code for implementing
23180 ** high-performance timing routines.
23182 /************** Include hwtime.h in the middle of os_common.h ****************/
23183 /************** Begin file hwtime.h ******************************************/
23185 ** 2008 May 27
23187 ** The author disclaims copyright to this source code. In place of
23188 ** a legal notice, here is a blessing:
23190 ** May you do good and not evil.
23191 ** May you find forgiveness for yourself and forgive others.
23192 ** May you share freely, never taking more than you give.
23194 ******************************************************************************
23196 ** This file contains inline asm code for retrieving "high-performance"
23197 ** counters for x86 class CPUs.
23199 #ifndef _HWTIME_H_
23200 #define _HWTIME_H_
23203 ** The following routine only works on pentium-class (or newer) processors.
23204 ** It uses the RDTSC opcode to read the cycle count value out of the
23205 ** processor and returns that value. This can be used for high-res
23206 ** profiling.
23208 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23209 (defined(i386) || defined(__i386__) || defined(_M_IX86))
23211 #if defined(__GNUC__)
23213 __inline__ sqlite_uint64 sqlite3Hwtime(void){
23214 unsigned int lo, hi;
23215 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23216 return (sqlite_uint64)hi << 32 | lo;
23219 #elif defined(_MSC_VER)
23221 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23222 __asm {
23223 rdtsc
23224 ret ; return value at EDX:EAX
23228 #endif
23230 #elif (defined(__GNUC__) && defined(__x86_64__))
23232 __inline__ sqlite_uint64 sqlite3Hwtime(void){
23233 unsigned long val;
23234 __asm__ __volatile__ ("rdtsc" : "=A" (val));
23235 return val;
23238 #elif (defined(__GNUC__) && defined(__ppc__))
23240 __inline__ sqlite_uint64 sqlite3Hwtime(void){
23241 unsigned long long retval;
23242 unsigned long junk;
23243 __asm__ __volatile__ ("\n\
23244 1: mftbu %1\n\
23245 mftb %L0\n\
23246 mftbu %0\n\
23247 cmpw %0,%1\n\
23248 bne 1b"
23249 : "=r" (retval), "=r" (junk));
23250 return retval;
23253 #else
23255 #error Need implementation of sqlite3Hwtime() for your platform.
23258 ** To compile without implementing sqlite3Hwtime() for your platform,
23259 ** you can remove the above #error and use the following
23260 ** stub function. You will lose timing support for many
23261 ** of the debugging and testing utilities, but it should at
23262 ** least compile and run.
23264 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23266 #endif
23268 #endif /* !defined(_HWTIME_H_) */
23270 /************** End of hwtime.h **********************************************/
23271 /************** Continuing where we left off in os_common.h ******************/
23273 static sqlite_uint64 g_start;
23274 static sqlite_uint64 g_elapsed;
23275 #define TIMER_START g_start=sqlite3Hwtime()
23276 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
23277 #define TIMER_ELAPSED g_elapsed
23278 #else
23279 #define TIMER_START
23280 #define TIMER_END
23281 #define TIMER_ELAPSED ((sqlite_uint64)0)
23282 #endif
23285 ** If we compile with the SQLITE_TEST macro set, then the following block
23286 ** of code will give us the ability to simulate a disk I/O error. This
23287 ** is used for testing the I/O recovery logic.
23289 #ifdef SQLITE_TEST
23290 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
23291 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
23292 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
23293 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
23294 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
23295 SQLITE_API int sqlite3_diskfull_pending = 0;
23296 SQLITE_API int sqlite3_diskfull = 0;
23297 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23298 #define SimulateIOError(CODE) \
23299 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23300 || sqlite3_io_error_pending-- == 1 ) \
23301 { local_ioerr(); CODE; }
23302 static void local_ioerr(){
23303 IOTRACE(("IOERR\n"));
23304 sqlite3_io_error_hit++;
23305 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23307 #define SimulateDiskfullError(CODE) \
23308 if( sqlite3_diskfull_pending ){ \
23309 if( sqlite3_diskfull_pending == 1 ){ \
23310 local_ioerr(); \
23311 sqlite3_diskfull = 1; \
23312 sqlite3_io_error_hit = 1; \
23313 CODE; \
23314 }else{ \
23315 sqlite3_diskfull_pending--; \
23318 #else
23319 #define SimulateIOErrorBenign(X)
23320 #define SimulateIOError(A)
23321 #define SimulateDiskfullError(A)
23322 #endif
23325 ** When testing, keep a count of the number of open files.
23327 #ifdef SQLITE_TEST
23328 SQLITE_API int sqlite3_open_file_count = 0;
23329 #define OpenCounter(X) sqlite3_open_file_count+=(X)
23330 #else
23331 #define OpenCounter(X)
23332 #endif
23334 #endif /* !defined(_OS_COMMON_H_) */
23336 /************** End of os_common.h *******************************************/
23337 /************** Continuing where we left off in os_unix.c ********************/
23340 ** Define various macros that are missing from some systems.
23342 #ifndef O_LARGEFILE
23343 # define O_LARGEFILE 0
23344 #endif
23345 #ifdef SQLITE_DISABLE_LFS
23346 # undef O_LARGEFILE
23347 # define O_LARGEFILE 0
23348 #endif
23349 #ifndef O_NOFOLLOW
23350 # define O_NOFOLLOW 0
23351 #endif
23352 #ifndef O_BINARY
23353 # define O_BINARY 0
23354 #endif
23357 ** The threadid macro resolves to the thread-id or to 0. Used for
23358 ** testing and debugging only.
23360 #if SQLITE_THREADSAFE
23361 #define threadid pthread_self()
23362 #else
23363 #define threadid 0
23364 #endif
23367 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
23369 #if !defined(HAVE_MREMAP)
23370 # if defined(__linux__) && defined(_GNU_SOURCE)
23371 # define HAVE_MREMAP 1
23372 # else
23373 # define HAVE_MREMAP 0
23374 # endif
23375 #endif
23378 ** Different Unix systems declare open() in different ways. Same use
23379 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
23380 ** The difference is important when using a pointer to the function.
23382 ** The safest way to deal with the problem is to always use this wrapper
23383 ** which always has the same well-defined interface.
23385 static int posixOpen(const char *zFile, int flags, int mode){
23386 return open(zFile, flags, mode);
23390 ** On some systems, calls to fchown() will trigger a message in a security
23391 ** log if they come from non-root processes. So avoid calling fchown() if
23392 ** we are not running as root.
23394 static int posixFchown(int fd, uid_t uid, gid_t gid){
23395 return geteuid() ? 0 : fchown(fd,uid,gid);
23398 /* Forward reference */
23399 static int openDirectory(const char*, int*);
23402 ** Many system calls are accessed through pointer-to-functions so that
23403 ** they may be overridden at runtime to facilitate fault injection during
23404 ** testing and sandboxing. The following array holds the names and pointers
23405 ** to all overrideable system calls.
23407 static struct unix_syscall {
23408 const char *zName; /* Name of the system call */
23409 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
23410 sqlite3_syscall_ptr pDefault; /* Default value */
23411 } aSyscall[] = {
23412 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
23413 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
23415 { "close", (sqlite3_syscall_ptr)close, 0 },
23416 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
23418 { "access", (sqlite3_syscall_ptr)access, 0 },
23419 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
23421 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
23422 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
23424 { "stat", (sqlite3_syscall_ptr)stat, 0 },
23425 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
23428 ** The DJGPP compiler environment looks mostly like Unix, but it
23429 ** lacks the fcntl() system call. So redefine fcntl() to be something
23430 ** that always succeeds. This means that locking does not occur under
23431 ** DJGPP. But it is DOS - what did you expect?
23433 #ifdef __DJGPP__
23434 { "fstat", 0, 0 },
23435 #define osFstat(a,b,c) 0
23436 #else
23437 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
23438 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
23439 #endif
23441 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
23442 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
23444 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
23445 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
23447 { "read", (sqlite3_syscall_ptr)read, 0 },
23448 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
23450 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23451 { "pread", (sqlite3_syscall_ptr)pread, 0 },
23452 #else
23453 { "pread", (sqlite3_syscall_ptr)0, 0 },
23454 #endif
23455 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
23457 #if defined(USE_PREAD64)
23458 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
23459 #else
23460 { "pread64", (sqlite3_syscall_ptr)0, 0 },
23461 #endif
23462 #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
23464 { "write", (sqlite3_syscall_ptr)write, 0 },
23465 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
23467 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23468 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
23469 #else
23470 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
23471 #endif
23472 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
23473 aSyscall[12].pCurrent)
23475 #if defined(USE_PREAD64)
23476 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
23477 #else
23478 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
23479 #endif
23480 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
23481 aSyscall[13].pCurrent)
23483 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
23484 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
23486 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
23487 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
23488 #else
23489 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
23490 #endif
23491 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
23493 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
23494 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
23496 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
23497 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
23499 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
23500 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
23502 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
23503 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
23505 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
23506 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
23508 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
23509 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
23511 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
23512 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
23514 #if HAVE_MREMAP
23515 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
23516 #else
23517 { "mremap", (sqlite3_syscall_ptr)0, 0 },
23518 #endif
23519 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
23521 }; /* End of the overrideable system calls */
23524 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
23525 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
23526 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
23527 ** system call named zName.
23529 static int unixSetSystemCall(
23530 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
23531 const char *zName, /* Name of system call to override */
23532 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
23534 unsigned int i;
23535 int rc = SQLITE_NOTFOUND;
23537 UNUSED_PARAMETER(pNotUsed);
23538 if( zName==0 ){
23539 /* If no zName is given, restore all system calls to their default
23540 ** settings and return NULL
23542 rc = SQLITE_OK;
23543 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23544 if( aSyscall[i].pDefault ){
23545 aSyscall[i].pCurrent = aSyscall[i].pDefault;
23548 }else{
23549 /* If zName is specified, operate on only the one system call
23550 ** specified.
23552 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23553 if( strcmp(zName, aSyscall[i].zName)==0 ){
23554 if( aSyscall[i].pDefault==0 ){
23555 aSyscall[i].pDefault = aSyscall[i].pCurrent;
23557 rc = SQLITE_OK;
23558 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
23559 aSyscall[i].pCurrent = pNewFunc;
23560 break;
23564 return rc;
23568 ** Return the value of a system call. Return NULL if zName is not a
23569 ** recognized system call name. NULL is also returned if the system call
23570 ** is currently undefined.
23572 static sqlite3_syscall_ptr unixGetSystemCall(
23573 sqlite3_vfs *pNotUsed,
23574 const char *zName
23576 unsigned int i;
23578 UNUSED_PARAMETER(pNotUsed);
23579 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23580 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
23582 return 0;
23586 ** Return the name of the first system call after zName. If zName==NULL
23587 ** then return the name of the first system call. Return NULL if zName
23588 ** is the last system call or if zName is not the name of a valid
23589 ** system call.
23591 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
23592 int i = -1;
23594 UNUSED_PARAMETER(p);
23595 if( zName ){
23596 for(i=0; i<ArraySize(aSyscall)-1; i++){
23597 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
23600 for(i++; i<ArraySize(aSyscall); i++){
23601 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
23603 return 0;
23607 ** Invoke open(). Do so multiple times, until it either succeeds or
23608 ** fails for some reason other than EINTR.
23610 ** If the file creation mode "m" is 0 then set it to the default for
23611 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
23612 ** 0644) as modified by the system umask. If m is not 0, then
23613 ** make the file creation mode be exactly m ignoring the umask.
23615 ** The m parameter will be non-zero only when creating -wal, -journal,
23616 ** and -shm files. We want those files to have *exactly* the same
23617 ** permissions as their original database, unadulterated by the umask.
23618 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
23619 ** transaction crashes and leaves behind hot journals, then any
23620 ** process that is able to write to the database will also be able to
23621 ** recover the hot journals.
23623 static int robust_open(const char *z, int f, mode_t m){
23624 int fd;
23625 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
23627 #if defined(O_CLOEXEC)
23628 fd = osOpen(z,f|O_CLOEXEC,m2);
23629 #else
23630 fd = osOpen(z,f,m2);
23631 #endif
23632 }while( fd<0 && errno==EINTR );
23633 if( fd>=0 ){
23634 if( m!=0 ){
23635 struct stat statbuf;
23636 if( osFstat(fd, &statbuf)==0
23637 && statbuf.st_size==0
23638 && (statbuf.st_mode&0777)!=m
23640 osFchmod(fd, m);
23643 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
23644 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
23645 #endif
23647 return fd;
23651 ** Helper functions to obtain and relinquish the global mutex. The
23652 ** global mutex is used to protect the unixInodeInfo and
23653 ** vxworksFileId objects used by this file, all of which may be
23654 ** shared by multiple threads.
23656 ** Function unixMutexHeld() is used to assert() that the global mutex
23657 ** is held when required. This function is only used as part of assert()
23658 ** statements. e.g.
23660 ** unixEnterMutex()
23661 ** assert( unixMutexHeld() );
23662 ** unixEnterLeave()
23664 static void unixEnterMutex(void){
23665 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23667 static void unixLeaveMutex(void){
23668 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23670 #ifdef SQLITE_DEBUG
23671 static int unixMutexHeld(void) {
23672 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23674 #endif
23677 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23679 ** Helper function for printing out trace information from debugging
23680 ** binaries. This returns the string represetation of the supplied
23681 ** integer lock-type.
23683 static const char *azFileLock(int eFileLock){
23684 switch( eFileLock ){
23685 case NO_LOCK: return "NONE";
23686 case SHARED_LOCK: return "SHARED";
23687 case RESERVED_LOCK: return "RESERVED";
23688 case PENDING_LOCK: return "PENDING";
23689 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23691 return "ERROR";
23693 #endif
23695 #ifdef SQLITE_LOCK_TRACE
23697 ** Print out information about all locking operations.
23699 ** This routine is used for troubleshooting locks on multithreaded
23700 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
23701 ** command-line option on the compiler. This code is normally
23702 ** turned off.
23704 static int lockTrace(int fd, int op, struct flock *p){
23705 char *zOpName, *zType;
23706 int s;
23707 int savedErrno;
23708 if( op==F_GETLK ){
23709 zOpName = "GETLK";
23710 }else if( op==F_SETLK ){
23711 zOpName = "SETLK";
23712 }else{
23713 s = osFcntl(fd, op, p);
23714 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23715 return s;
23717 if( p->l_type==F_RDLCK ){
23718 zType = "RDLCK";
23719 }else if( p->l_type==F_WRLCK ){
23720 zType = "WRLCK";
23721 }else if( p->l_type==F_UNLCK ){
23722 zType = "UNLCK";
23723 }else{
23724 assert( 0 );
23726 assert( p->l_whence==SEEK_SET );
23727 s = osFcntl(fd, op, p);
23728 savedErrno = errno;
23729 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
23730 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
23731 (int)p->l_pid, s);
23732 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
23733 struct flock l2;
23734 l2 = *p;
23735 osFcntl(fd, F_GETLK, &l2);
23736 if( l2.l_type==F_RDLCK ){
23737 zType = "RDLCK";
23738 }else if( l2.l_type==F_WRLCK ){
23739 zType = "WRLCK";
23740 }else if( l2.l_type==F_UNLCK ){
23741 zType = "UNLCK";
23742 }else{
23743 assert( 0 );
23745 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23746 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23748 errno = savedErrno;
23749 return s;
23751 #undef osFcntl
23752 #define osFcntl lockTrace
23753 #endif /* SQLITE_LOCK_TRACE */
23756 ** Retry ftruncate() calls that fail due to EINTR
23758 static int robust_ftruncate(int h, sqlite3_int64 sz){
23759 int rc;
23760 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
23761 return rc;
23765 ** This routine translates a standard POSIX errno code into something
23766 ** useful to the clients of the sqlite3 functions. Specifically, it is
23767 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
23768 ** and a variety of "please close the file descriptor NOW" errors into
23769 ** SQLITE_IOERR
23771 ** Errors during initialization of locks, or file system support for locks,
23772 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23774 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23775 switch (posixError) {
23776 #if 0
23777 /* At one point this code was not commented out. In theory, this branch
23778 ** should never be hit, as this function should only be called after
23779 ** a locking-related function (i.e. fcntl()) has returned non-zero with
23780 ** the value of errno as the first argument. Since a system call has failed,
23781 ** errno should be non-zero.
23783 ** Despite this, if errno really is zero, we still don't want to return
23784 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
23785 ** propagated back to the caller. Commenting this branch out means errno==0
23786 ** will be handled by the "default:" case below.
23788 case 0:
23789 return SQLITE_OK;
23790 #endif
23792 case EAGAIN:
23793 case ETIMEDOUT:
23794 case EBUSY:
23795 case EINTR:
23796 case ENOLCK:
23797 /* random NFS retry error, unless during file system support
23798 * introspection, in which it actually means what it says */
23799 return SQLITE_BUSY;
23801 case EACCES:
23802 /* EACCES is like EAGAIN during locking operations, but not any other time*/
23803 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
23804 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
23805 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23806 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23807 return SQLITE_BUSY;
23809 /* else fall through */
23810 case EPERM:
23811 return SQLITE_PERM;
23813 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
23814 ** this module never makes such a call. And the code in SQLite itself
23815 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
23816 ** this case is also commented out. If the system does set errno to EDEADLK,
23817 ** the default SQLITE_IOERR_XXX code will be returned. */
23818 #if 0
23819 case EDEADLK:
23820 return SQLITE_IOERR_BLOCKED;
23821 #endif
23823 #if EOPNOTSUPP!=ENOTSUP
23824 case EOPNOTSUPP:
23825 /* something went terribly awry, unless during file system support
23826 * introspection, in which it actually means what it says */
23827 #endif
23828 #ifdef ENOTSUP
23829 case ENOTSUP:
23830 /* invalid fd, unless during file system support introspection, in which
23831 * it actually means what it says */
23832 #endif
23833 case EIO:
23834 case EBADF:
23835 case EINVAL:
23836 case ENOTCONN:
23837 case ENODEV:
23838 case ENXIO:
23839 case ENOENT:
23840 #ifdef ESTALE /* ESTALE is not defined on Interix systems */
23841 case ESTALE:
23842 #endif
23843 case ENOSYS:
23844 /* these should force the client to close the file and reconnect */
23846 default:
23847 return sqliteIOErr;
23852 /******************************************************************************
23853 ****************** Begin Unique File ID Utility Used By VxWorks ***************
23855 ** On most versions of unix, we can get a unique ID for a file by concatenating
23856 ** the device number and the inode number. But this does not work on VxWorks.
23857 ** On VxWorks, a unique file id must be based on the canonical filename.
23859 ** A pointer to an instance of the following structure can be used as a
23860 ** unique file ID in VxWorks. Each instance of this structure contains
23861 ** a copy of the canonical filename. There is also a reference count.
23862 ** The structure is reclaimed when the number of pointers to it drops to
23863 ** zero.
23865 ** There are never very many files open at one time and lookups are not
23866 ** a performance-critical path, so it is sufficient to put these
23867 ** structures on a linked list.
23869 struct vxworksFileId {
23870 struct vxworksFileId *pNext; /* Next in a list of them all */
23871 int nRef; /* Number of references to this one */
23872 int nName; /* Length of the zCanonicalName[] string */
23873 char *zCanonicalName; /* Canonical filename */
23876 #if OS_VXWORKS
23878 ** All unique filenames are held on a linked list headed by this
23879 ** variable:
23881 static struct vxworksFileId *vxworksFileList = 0;
23884 ** Simplify a filename into its canonical form
23885 ** by making the following changes:
23887 ** * removing any trailing and duplicate /
23888 ** * convert /./ into just /
23889 ** * convert /A/../ where A is any simple name into just /
23891 ** Changes are made in-place. Return the new name length.
23893 ** The original filename is in z[0..n-1]. Return the number of
23894 ** characters in the simplified name.
23896 static int vxworksSimplifyName(char *z, int n){
23897 int i, j;
23898 while( n>1 && z[n-1]=='/' ){ n--; }
23899 for(i=j=0; i<n; i++){
23900 if( z[i]=='/' ){
23901 if( z[i+1]=='/' ) continue;
23902 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23903 i += 1;
23904 continue;
23906 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23907 while( j>0 && z[j-1]!='/' ){ j--; }
23908 if( j>0 ){ j--; }
23909 i += 2;
23910 continue;
23913 z[j++] = z[i];
23915 z[j] = 0;
23916 return j;
23920 ** Find a unique file ID for the given absolute pathname. Return
23921 ** a pointer to the vxworksFileId object. This pointer is the unique
23922 ** file ID.
23924 ** The nRef field of the vxworksFileId object is incremented before
23925 ** the object is returned. A new vxworksFileId object is created
23926 ** and added to the global list if necessary.
23928 ** If a memory allocation error occurs, return NULL.
23930 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23931 struct vxworksFileId *pNew; /* search key and new file ID */
23932 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
23933 int n; /* Length of zAbsoluteName string */
23935 assert( zAbsoluteName[0]=='/' );
23936 n = (int)strlen(zAbsoluteName);
23937 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23938 if( pNew==0 ) return 0;
23939 pNew->zCanonicalName = (char*)&pNew[1];
23940 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23941 n = vxworksSimplifyName(pNew->zCanonicalName, n);
23943 /* Search for an existing entry that matching the canonical name.
23944 ** If found, increment the reference count and return a pointer to
23945 ** the existing file ID.
23947 unixEnterMutex();
23948 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23949 if( pCandidate->nName==n
23950 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23952 sqlite3_free(pNew);
23953 pCandidate->nRef++;
23954 unixLeaveMutex();
23955 return pCandidate;
23959 /* No match was found. We will make a new file ID */
23960 pNew->nRef = 1;
23961 pNew->nName = n;
23962 pNew->pNext = vxworksFileList;
23963 vxworksFileList = pNew;
23964 unixLeaveMutex();
23965 return pNew;
23969 ** Decrement the reference count on a vxworksFileId object. Free
23970 ** the object when the reference count reaches zero.
23972 static void vxworksReleaseFileId(struct vxworksFileId *pId){
23973 unixEnterMutex();
23974 assert( pId->nRef>0 );
23975 pId->nRef--;
23976 if( pId->nRef==0 ){
23977 struct vxworksFileId **pp;
23978 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23979 assert( *pp==pId );
23980 *pp = pId->pNext;
23981 sqlite3_free(pId);
23983 unixLeaveMutex();
23985 #endif /* OS_VXWORKS */
23986 /*************** End of Unique File ID Utility Used By VxWorks ****************
23987 ******************************************************************************/
23990 /******************************************************************************
23991 *************************** Posix Advisory Locking ****************************
23993 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
23994 ** section 6.5.2.2 lines 483 through 490 specify that when a process
23995 ** sets or clears a lock, that operation overrides any prior locks set
23996 ** by the same process. It does not explicitly say so, but this implies
23997 ** that it overrides locks set by the same process using a different
23998 ** file descriptor. Consider this test case:
24000 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24001 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24003 ** Suppose ./file1 and ./file2 are really the same file (because
24004 ** one is a hard or symbolic link to the other) then if you set
24005 ** an exclusive lock on fd1, then try to get an exclusive lock
24006 ** on fd2, it works. I would have expected the second lock to
24007 ** fail since there was already a lock on the file due to fd1.
24008 ** But not so. Since both locks came from the same process, the
24009 ** second overrides the first, even though they were on different
24010 ** file descriptors opened on different file names.
24012 ** This means that we cannot use POSIX locks to synchronize file access
24013 ** among competing threads of the same process. POSIX locks will work fine
24014 ** to synchronize access for threads in separate processes, but not
24015 ** threads within the same process.
24017 ** To work around the problem, SQLite has to manage file locks internally
24018 ** on its own. Whenever a new database is opened, we have to find the
24019 ** specific inode of the database file (the inode is determined by the
24020 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
24021 ** and check for locks already existing on that inode. When locks are
24022 ** created or removed, we have to look at our own internal record of the
24023 ** locks to see if another thread has previously set a lock on that same
24024 ** inode.
24026 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
24027 ** For VxWorks, we have to use the alternative unique ID system based on
24028 ** canonical filename and implemented in the previous division.)
24030 ** The sqlite3_file structure for POSIX is no longer just an integer file
24031 ** descriptor. It is now a structure that holds the integer file
24032 ** descriptor and a pointer to a structure that describes the internal
24033 ** locks on the corresponding inode. There is one locking structure
24034 ** per inode, so if the same inode is opened twice, both unixFile structures
24035 ** point to the same locking structure. The locking structure keeps
24036 ** a reference count (so we will know when to delete it) and a "cnt"
24037 ** field that tells us its internal lock status. cnt==0 means the
24038 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
24039 ** cnt>0 means there are cnt shared locks on the file.
24041 ** Any attempt to lock or unlock a file first checks the locking
24042 ** structure. The fcntl() system call is only invoked to set a
24043 ** POSIX lock if the internal lock structure transitions between
24044 ** a locked and an unlocked state.
24046 ** But wait: there are yet more problems with POSIX advisory locks.
24048 ** If you close a file descriptor that points to a file that has locks,
24049 ** all locks on that file that are owned by the current process are
24050 ** released. To work around this problem, each unixInodeInfo object
24051 ** maintains a count of the number of pending locks on tha inode.
24052 ** When an attempt is made to close an unixFile, if there are
24053 ** other unixFile open on the same inode that are holding locks, the call
24054 ** to close() the file descriptor is deferred until all of the locks clear.
24055 ** The unixInodeInfo structure keeps a list of file descriptors that need to
24056 ** be closed and that list is walked (and cleared) when the last lock
24057 ** clears.
24059 ** Yet another problem: LinuxThreads do not play well with posix locks.
24061 ** Many older versions of linux use the LinuxThreads library which is
24062 ** not posix compliant. Under LinuxThreads, a lock created by thread
24063 ** A cannot be modified or overridden by a different thread B.
24064 ** Only thread A can modify the lock. Locking behavior is correct
24065 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
24066 ** on linux - with NPTL a lock created by thread A can override locks
24067 ** in thread B. But there is no way to know at compile-time which
24068 ** threading library is being used. So there is no way to know at
24069 ** compile-time whether or not thread A can override locks on thread B.
24070 ** One has to do a run-time check to discover the behavior of the
24071 ** current process.
24073 ** SQLite used to support LinuxThreads. But support for LinuxThreads
24074 ** was dropped beginning with version 3.7.0. SQLite will still work with
24075 ** LinuxThreads provided that (1) there is no more than one connection
24076 ** per database file in the same process and (2) database connections
24077 ** do not move across threads.
24081 ** An instance of the following structure serves as the key used
24082 ** to locate a particular unixInodeInfo object.
24084 struct unixFileId {
24085 dev_t dev; /* Device number */
24086 #if OS_VXWORKS
24087 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
24088 #else
24089 ino_t ino; /* Inode number */
24090 #endif
24094 ** An instance of the following structure is allocated for each open
24095 ** inode. Or, on LinuxThreads, there is one of these structures for
24096 ** each inode opened by each thread.
24098 ** A single inode can have multiple file descriptors, so each unixFile
24099 ** structure contains a pointer to an instance of this object and this
24100 ** object keeps a count of the number of unixFile pointing to it.
24102 struct unixInodeInfo {
24103 struct unixFileId fileId; /* The lookup key */
24104 int nShared; /* Number of SHARED locks held */
24105 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
24106 unsigned char bProcessLock; /* An exclusive process lock is held */
24107 int nRef; /* Number of pointers to this structure */
24108 unixShmNode *pShmNode; /* Shared memory associated with this inode */
24109 int nLock; /* Number of outstanding file locks */
24110 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
24111 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
24112 unixInodeInfo *pPrev; /* .... doubly linked */
24113 #if SQLITE_ENABLE_LOCKING_STYLE
24114 unsigned long long sharedByte; /* for AFP simulated shared lock */
24115 #endif
24116 #if OS_VXWORKS
24117 sem_t *pSem; /* Named POSIX semaphore */
24118 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
24119 #endif
24123 ** A lists of all unixInodeInfo objects.
24125 static unixInodeInfo *inodeList = 0;
24129 ** This function - unixLogError_x(), is only ever called via the macro
24130 ** unixLogError().
24132 ** It is invoked after an error occurs in an OS function and errno has been
24133 ** set. It logs a message using sqlite3_log() containing the current value of
24134 ** errno and, if possible, the human-readable equivalent from strerror() or
24135 ** strerror_r().
24137 ** The first argument passed to the macro should be the error code that
24138 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
24139 ** The two subsequent arguments should be the name of the OS function that
24140 ** failed (e.g. "unlink", "open") and the associated file-system path,
24141 ** if any.
24143 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
24144 static int unixLogErrorAtLine(
24145 int errcode, /* SQLite error code */
24146 const char *zFunc, /* Name of OS function that failed */
24147 const char *zPath, /* File path associated with error */
24148 int iLine /* Source line number where error occurred */
24150 char *zErr; /* Message from strerror() or equivalent */
24151 int iErrno = errno; /* Saved syscall error number */
24153 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
24154 ** the strerror() function to obtain the human-readable error message
24155 ** equivalent to errno. Otherwise, use strerror_r().
24157 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
24158 char aErr[80];
24159 memset(aErr, 0, sizeof(aErr));
24160 zErr = aErr;
24162 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
24163 ** assume that the system provides the GNU version of strerror_r() that
24164 ** returns a pointer to a buffer containing the error message. That pointer
24165 ** may point to aErr[], or it may point to some static storage somewhere.
24166 ** Otherwise, assume that the system provides the POSIX version of
24167 ** strerror_r(), which always writes an error message into aErr[].
24169 ** If the code incorrectly assumes that it is the POSIX version that is
24170 ** available, the error message will often be an empty string. Not a
24171 ** huge problem. Incorrectly concluding that the GNU version is available
24172 ** could lead to a segfault though.
24174 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
24175 zErr =
24176 # endif
24177 strerror_r(iErrno, aErr, sizeof(aErr)-1);
24179 #elif SQLITE_THREADSAFE
24180 /* This is a threadsafe build, but strerror_r() is not available. */
24181 zErr = "";
24182 #else
24183 /* Non-threadsafe build, use strerror(). */
24184 zErr = strerror(iErrno);
24185 #endif
24187 if( zPath==0 ) zPath = "";
24188 sqlite3_log(errcode,
24189 "os_unix.c:%d: (%d) %s(%s) - %s",
24190 iLine, iErrno, zFunc, zPath, zErr
24193 return errcode;
24197 ** Close a file descriptor.
24199 ** We assume that close() almost always works, since it is only in a
24200 ** very sick application or on a very sick platform that it might fail.
24201 ** If it does fail, simply leak the file descriptor, but do log the
24202 ** error.
24204 ** Note that it is not safe to retry close() after EINTR since the
24205 ** file descriptor might have already been reused by another thread.
24206 ** So we don't even try to recover from an EINTR. Just log the error
24207 ** and move on.
24209 static void robust_close(unixFile *pFile, int h, int lineno){
24210 if( osClose(h) ){
24211 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
24212 pFile ? pFile->zPath : 0, lineno);
24217 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
24219 static void closePendingFds(unixFile *pFile){
24220 unixInodeInfo *pInode = pFile->pInode;
24221 UnixUnusedFd *p;
24222 UnixUnusedFd *pNext;
24223 for(p=pInode->pUnused; p; p=pNext){
24224 pNext = p->pNext;
24225 robust_close(pFile, p->fd, __LINE__);
24226 sqlite3_free(p);
24228 pInode->pUnused = 0;
24232 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
24234 ** The mutex entered using the unixEnterMutex() function must be held
24235 ** when this function is called.
24237 static void releaseInodeInfo(unixFile *pFile){
24238 unixInodeInfo *pInode = pFile->pInode;
24239 assert( unixMutexHeld() );
24240 if( ALWAYS(pInode) ){
24241 pInode->nRef--;
24242 if( pInode->nRef==0 ){
24243 assert( pInode->pShmNode==0 );
24244 closePendingFds(pFile);
24245 if( pInode->pPrev ){
24246 assert( pInode->pPrev->pNext==pInode );
24247 pInode->pPrev->pNext = pInode->pNext;
24248 }else{
24249 assert( inodeList==pInode );
24250 inodeList = pInode->pNext;
24252 if( pInode->pNext ){
24253 assert( pInode->pNext->pPrev==pInode );
24254 pInode->pNext->pPrev = pInode->pPrev;
24256 sqlite3_free(pInode);
24262 ** Given a file descriptor, locate the unixInodeInfo object that
24263 ** describes that file descriptor. Create a new one if necessary. The
24264 ** return value might be uninitialized if an error occurs.
24266 ** The mutex entered using the unixEnterMutex() function must be held
24267 ** when this function is called.
24269 ** Return an appropriate error code.
24271 static int findInodeInfo(
24272 unixFile *pFile, /* Unix file with file desc used in the key */
24273 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
24275 int rc; /* System call return code */
24276 int fd; /* The file descriptor for pFile */
24277 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
24278 struct stat statbuf; /* Low-level file information */
24279 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
24281 assert( unixMutexHeld() );
24283 /* Get low-level information about the file that we can used to
24284 ** create a unique name for the file.
24286 fd = pFile->h;
24287 rc = osFstat(fd, &statbuf);
24288 if( rc!=0 ){
24289 pFile->lastErrno = errno;
24290 #ifdef EOVERFLOW
24291 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
24292 #endif
24293 return SQLITE_IOERR;
24296 #ifdef __APPLE__
24297 /* On OS X on an msdos filesystem, the inode number is reported
24298 ** incorrectly for zero-size files. See ticket #3260. To work
24299 ** around this problem (we consider it a bug in OS X, not SQLite)
24300 ** we always increase the file size to 1 by writing a single byte
24301 ** prior to accessing the inode number. The one byte written is
24302 ** an ASCII 'S' character which also happens to be the first byte
24303 ** in the header of every SQLite database. In this way, if there
24304 ** is a race condition such that another thread has already populated
24305 ** the first page of the database, no damage is done.
24307 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
24308 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
24309 if( rc!=1 ){
24310 pFile->lastErrno = errno;
24311 return SQLITE_IOERR;
24313 rc = osFstat(fd, &statbuf);
24314 if( rc!=0 ){
24315 pFile->lastErrno = errno;
24316 return SQLITE_IOERR;
24319 #endif
24321 memset(&fileId, 0, sizeof(fileId));
24322 fileId.dev = statbuf.st_dev;
24323 #if OS_VXWORKS
24324 fileId.pId = pFile->pId;
24325 #else
24326 fileId.ino = statbuf.st_ino;
24327 #endif
24328 pInode = inodeList;
24329 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
24330 pInode = pInode->pNext;
24332 if( pInode==0 ){
24333 pInode = sqlite3_malloc( sizeof(*pInode) );
24334 if( pInode==0 ){
24335 return SQLITE_NOMEM;
24337 memset(pInode, 0, sizeof(*pInode));
24338 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
24339 pInode->nRef = 1;
24340 pInode->pNext = inodeList;
24341 pInode->pPrev = 0;
24342 if( inodeList ) inodeList->pPrev = pInode;
24343 inodeList = pInode;
24344 }else{
24345 pInode->nRef++;
24347 *ppInode = pInode;
24348 return SQLITE_OK;
24353 ** Check a unixFile that is a database. Verify the following:
24355 ** (1) There is exactly one hard link on the file
24356 ** (2) The file is not a symbolic link
24357 ** (3) The file has not been renamed or unlinked
24359 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
24361 static void verifyDbFile(unixFile *pFile){
24362 struct stat buf;
24363 int rc;
24364 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
24365 /* One or more of the following warnings have already been issued. Do not
24366 ** repeat them so as not to clutter the error log */
24367 return;
24369 rc = osFstat(pFile->h, &buf);
24370 if( rc!=0 ){
24371 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
24372 pFile->ctrlFlags |= UNIXFILE_WARNED;
24373 return;
24375 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
24376 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
24377 pFile->ctrlFlags |= UNIXFILE_WARNED;
24378 return;
24380 if( buf.st_nlink>1 ){
24381 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
24382 pFile->ctrlFlags |= UNIXFILE_WARNED;
24383 return;
24385 if( pFile->pInode!=0
24386 && ((rc = osStat(pFile->zPath, &buf))!=0
24387 || buf.st_ino!=pFile->pInode->fileId.ino)
24389 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
24390 pFile->ctrlFlags |= UNIXFILE_WARNED;
24391 return;
24397 ** This routine checks if there is a RESERVED lock held on the specified
24398 ** file by this or any other process. If such a lock is held, set *pResOut
24399 ** to a non-zero value otherwise *pResOut is set to zero. The return value
24400 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24402 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
24403 int rc = SQLITE_OK;
24404 int reserved = 0;
24405 unixFile *pFile = (unixFile*)id;
24407 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24409 assert( pFile );
24410 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24412 /* Check if a thread in this process holds such a lock */
24413 if( pFile->pInode->eFileLock>SHARED_LOCK ){
24414 reserved = 1;
24417 /* Otherwise see if some other process holds it.
24419 #ifndef __DJGPP__
24420 if( !reserved && !pFile->pInode->bProcessLock ){
24421 struct flock lock;
24422 lock.l_whence = SEEK_SET;
24423 lock.l_start = RESERVED_BYTE;
24424 lock.l_len = 1;
24425 lock.l_type = F_WRLCK;
24426 if( osFcntl(pFile->h, F_GETLK, &lock) ){
24427 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
24428 pFile->lastErrno = errno;
24429 } else if( lock.l_type!=F_UNLCK ){
24430 reserved = 1;
24433 #endif
24435 unixLeaveMutex();
24436 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
24438 *pResOut = reserved;
24439 return rc;
24443 ** Attempt to set a system-lock on the file pFile. The lock is
24444 ** described by pLock.
24446 ** If the pFile was opened read/write from unix-excl, then the only lock
24447 ** ever obtained is an exclusive lock, and it is obtained exactly once
24448 ** the first time any lock is attempted. All subsequent system locking
24449 ** operations become no-ops. Locking operations still happen internally,
24450 ** in order to coordinate access between separate database connections
24451 ** within this process, but all of that is handled in memory and the
24452 ** operating system does not participate.
24454 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
24455 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
24456 ** and is read-only.
24458 ** Zero is returned if the call completes successfully, or -1 if a call
24459 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
24461 static int unixFileLock(unixFile *pFile, struct flock *pLock){
24462 int rc;
24463 unixInodeInfo *pInode = pFile->pInode;
24464 assert( unixMutexHeld() );
24465 assert( pInode!=0 );
24466 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
24467 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
24469 if( pInode->bProcessLock==0 ){
24470 struct flock lock;
24471 assert( pInode->nLock==0 );
24472 lock.l_whence = SEEK_SET;
24473 lock.l_start = SHARED_FIRST;
24474 lock.l_len = SHARED_SIZE;
24475 lock.l_type = F_WRLCK;
24476 rc = osFcntl(pFile->h, F_SETLK, &lock);
24477 if( rc<0 ) return rc;
24478 pInode->bProcessLock = 1;
24479 pInode->nLock++;
24480 }else{
24481 rc = 0;
24483 }else{
24484 rc = osFcntl(pFile->h, F_SETLK, pLock);
24486 return rc;
24490 ** Lock the file with the lock specified by parameter eFileLock - one
24491 ** of the following:
24493 ** (1) SHARED_LOCK
24494 ** (2) RESERVED_LOCK
24495 ** (3) PENDING_LOCK
24496 ** (4) EXCLUSIVE_LOCK
24498 ** Sometimes when requesting one lock state, additional lock states
24499 ** are inserted in between. The locking might fail on one of the later
24500 ** transitions leaving the lock state different from what it started but
24501 ** still short of its goal. The following chart shows the allowed
24502 ** transitions and the inserted intermediate states:
24504 ** UNLOCKED -> SHARED
24505 ** SHARED -> RESERVED
24506 ** SHARED -> (PENDING) -> EXCLUSIVE
24507 ** RESERVED -> (PENDING) -> EXCLUSIVE
24508 ** PENDING -> EXCLUSIVE
24510 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
24511 ** routine to lower a locking level.
24513 static int unixLock(sqlite3_file *id, int eFileLock){
24514 /* The following describes the implementation of the various locks and
24515 ** lock transitions in terms of the POSIX advisory shared and exclusive
24516 ** lock primitives (called read-locks and write-locks below, to avoid
24517 ** confusion with SQLite lock names). The algorithms are complicated
24518 ** slightly in order to be compatible with windows systems simultaneously
24519 ** accessing the same database file, in case that is ever required.
24521 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
24522 ** byte', each single bytes at well known offsets, and the 'shared byte
24523 ** range', a range of 510 bytes at a well known offset.
24525 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
24526 ** byte'. If this is successful, a random byte from the 'shared byte
24527 ** range' is read-locked and the lock on the 'pending byte' released.
24529 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
24530 ** A RESERVED lock is implemented by grabbing a write-lock on the
24531 ** 'reserved byte'.
24533 ** A process may only obtain a PENDING lock after it has obtained a
24534 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
24535 ** on the 'pending byte'. This ensures that no new SHARED locks can be
24536 ** obtained, but existing SHARED locks are allowed to persist. A process
24537 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
24538 ** This property is used by the algorithm for rolling back a journal file
24539 ** after a crash.
24541 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
24542 ** implemented by obtaining a write-lock on the entire 'shared byte
24543 ** range'. Since all other locks require a read-lock on one of the bytes
24544 ** within this range, this ensures that no other locks are held on the
24545 ** database.
24547 ** The reason a single byte cannot be used instead of the 'shared byte
24548 ** range' is that some versions of windows do not support read-locks. By
24549 ** locking a random byte from a range, concurrent SHARED locks may exist
24550 ** even if the locking primitive used is always a write-lock.
24552 int rc = SQLITE_OK;
24553 unixFile *pFile = (unixFile*)id;
24554 unixInodeInfo *pInode;
24555 struct flock lock;
24556 int tErrno = 0;
24558 assert( pFile );
24559 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
24560 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24561 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
24563 /* If there is already a lock of this type or more restrictive on the
24564 ** unixFile, do nothing. Don't use the end_lock: exit path, as
24565 ** unixEnterMutex() hasn't been called yet.
24567 if( pFile->eFileLock>=eFileLock ){
24568 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
24569 azFileLock(eFileLock)));
24570 return SQLITE_OK;
24573 /* Make sure the locking sequence is correct.
24574 ** (1) We never move from unlocked to anything higher than shared lock.
24575 ** (2) SQLite never explicitly requests a pendig lock.
24576 ** (3) A shared lock is always held when a reserve lock is requested.
24578 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24579 assert( eFileLock!=PENDING_LOCK );
24580 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24582 /* This mutex is needed because pFile->pInode is shared across threads
24584 unixEnterMutex();
24585 pInode = pFile->pInode;
24587 /* If some thread using this PID has a lock via a different unixFile*
24588 ** handle that precludes the requested lock, return BUSY.
24590 if( (pFile->eFileLock!=pInode->eFileLock &&
24591 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24593 rc = SQLITE_BUSY;
24594 goto end_lock;
24597 /* If a SHARED lock is requested, and some thread using this PID already
24598 ** has a SHARED or RESERVED lock, then increment reference counts and
24599 ** return SQLITE_OK.
24601 if( eFileLock==SHARED_LOCK &&
24602 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24603 assert( eFileLock==SHARED_LOCK );
24604 assert( pFile->eFileLock==0 );
24605 assert( pInode->nShared>0 );
24606 pFile->eFileLock = SHARED_LOCK;
24607 pInode->nShared++;
24608 pInode->nLock++;
24609 goto end_lock;
24613 /* A PENDING lock is needed before acquiring a SHARED lock and before
24614 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
24615 ** be released.
24617 lock.l_len = 1L;
24618 lock.l_whence = SEEK_SET;
24619 if( eFileLock==SHARED_LOCK
24620 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24622 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
24623 lock.l_start = PENDING_BYTE;
24624 if( unixFileLock(pFile, &lock) ){
24625 tErrno = errno;
24626 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24627 if( rc!=SQLITE_BUSY ){
24628 pFile->lastErrno = tErrno;
24630 goto end_lock;
24635 /* If control gets to this point, then actually go ahead and make
24636 ** operating system calls for the specified lock.
24638 if( eFileLock==SHARED_LOCK ){
24639 assert( pInode->nShared==0 );
24640 assert( pInode->eFileLock==0 );
24641 assert( rc==SQLITE_OK );
24643 /* Now get the read-lock */
24644 lock.l_start = SHARED_FIRST;
24645 lock.l_len = SHARED_SIZE;
24646 if( unixFileLock(pFile, &lock) ){
24647 tErrno = errno;
24648 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24651 /* Drop the temporary PENDING lock */
24652 lock.l_start = PENDING_BYTE;
24653 lock.l_len = 1L;
24654 lock.l_type = F_UNLCK;
24655 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
24656 /* This could happen with a network mount */
24657 tErrno = errno;
24658 rc = SQLITE_IOERR_UNLOCK;
24661 if( rc ){
24662 if( rc!=SQLITE_BUSY ){
24663 pFile->lastErrno = tErrno;
24665 goto end_lock;
24666 }else{
24667 pFile->eFileLock = SHARED_LOCK;
24668 pInode->nLock++;
24669 pInode->nShared = 1;
24671 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24672 /* We are trying for an exclusive lock but another thread in this
24673 ** same process is still holding a shared lock. */
24674 rc = SQLITE_BUSY;
24675 }else{
24676 /* The request was for a RESERVED or EXCLUSIVE lock. It is
24677 ** assumed that there is a SHARED or greater lock on the file
24678 ** already.
24680 assert( 0!=pFile->eFileLock );
24681 lock.l_type = F_WRLCK;
24683 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
24684 if( eFileLock==RESERVED_LOCK ){
24685 lock.l_start = RESERVED_BYTE;
24686 lock.l_len = 1L;
24687 }else{
24688 lock.l_start = SHARED_FIRST;
24689 lock.l_len = SHARED_SIZE;
24692 if( unixFileLock(pFile, &lock) ){
24693 tErrno = errno;
24694 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24695 if( rc!=SQLITE_BUSY ){
24696 pFile->lastErrno = tErrno;
24702 #ifdef SQLITE_DEBUG
24703 /* Set up the transaction-counter change checking flags when
24704 ** transitioning from a SHARED to a RESERVED lock. The change
24705 ** from SHARED to RESERVED marks the beginning of a normal
24706 ** write operation (not a hot journal rollback).
24708 if( rc==SQLITE_OK
24709 && pFile->eFileLock<=SHARED_LOCK
24710 && eFileLock==RESERVED_LOCK
24712 pFile->transCntrChng = 0;
24713 pFile->dbUpdate = 0;
24714 pFile->inNormalWrite = 1;
24716 #endif
24719 if( rc==SQLITE_OK ){
24720 pFile->eFileLock = eFileLock;
24721 pInode->eFileLock = eFileLock;
24722 }else if( eFileLock==EXCLUSIVE_LOCK ){
24723 pFile->eFileLock = PENDING_LOCK;
24724 pInode->eFileLock = PENDING_LOCK;
24727 end_lock:
24728 unixLeaveMutex();
24729 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
24730 rc==SQLITE_OK ? "ok" : "failed"));
24731 return rc;
24735 ** Add the file descriptor used by file handle pFile to the corresponding
24736 ** pUnused list.
24738 static void setPendingFd(unixFile *pFile){
24739 unixInodeInfo *pInode = pFile->pInode;
24740 UnixUnusedFd *p = pFile->pUnused;
24741 p->pNext = pInode->pUnused;
24742 pInode->pUnused = p;
24743 pFile->h = -1;
24744 pFile->pUnused = 0;
24748 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
24749 ** must be either NO_LOCK or SHARED_LOCK.
24751 ** If the locking level of the file descriptor is already at or below
24752 ** the requested locking level, this routine is a no-op.
24754 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
24755 ** the byte range is divided into 2 parts and the first part is unlocked then
24756 ** set to a read lock, then the other part is simply unlocked. This works
24757 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
24758 ** remove the write lock on a region when a read lock is set.
24760 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
24761 unixFile *pFile = (unixFile*)id;
24762 unixInodeInfo *pInode;
24763 struct flock lock;
24764 int rc = SQLITE_OK;
24766 assert( pFile );
24767 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
24768 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24769 getpid()));
24771 assert( eFileLock<=SHARED_LOCK );
24772 if( pFile->eFileLock<=eFileLock ){
24773 return SQLITE_OK;
24775 unixEnterMutex();
24776 pInode = pFile->pInode;
24777 assert( pInode->nShared!=0 );
24778 if( pFile->eFileLock>SHARED_LOCK ){
24779 assert( pInode->eFileLock==pFile->eFileLock );
24781 #ifdef SQLITE_DEBUG
24782 /* When reducing a lock such that other processes can start
24783 ** reading the database file again, make sure that the
24784 ** transaction counter was updated if any part of the database
24785 ** file changed. If the transaction counter is not updated,
24786 ** other connections to the same file might not realize that
24787 ** the file has changed and hence might not know to flush their
24788 ** cache. The use of a stale cache can lead to database corruption.
24790 pFile->inNormalWrite = 0;
24791 #endif
24793 /* downgrading to a shared lock on NFS involves clearing the write lock
24794 ** before establishing the readlock - to avoid a race condition we downgrade
24795 ** the lock in 2 blocks, so that part of the range will be covered by a
24796 ** write lock until the rest is covered by a read lock:
24797 ** 1: [WWWWW]
24798 ** 2: [....W]
24799 ** 3: [RRRRW]
24800 ** 4: [RRRR.]
24802 if( eFileLock==SHARED_LOCK ){
24804 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
24805 (void)handleNFSUnlock;
24806 assert( handleNFSUnlock==0 );
24807 #endif
24808 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24809 if( handleNFSUnlock ){
24810 int tErrno; /* Error code from system call errors */
24811 off_t divSize = SHARED_SIZE - 1;
24813 lock.l_type = F_UNLCK;
24814 lock.l_whence = SEEK_SET;
24815 lock.l_start = SHARED_FIRST;
24816 lock.l_len = divSize;
24817 if( unixFileLock(pFile, &lock)==(-1) ){
24818 tErrno = errno;
24819 rc = SQLITE_IOERR_UNLOCK;
24820 if( IS_LOCK_ERROR(rc) ){
24821 pFile->lastErrno = tErrno;
24823 goto end_unlock;
24825 lock.l_type = F_RDLCK;
24826 lock.l_whence = SEEK_SET;
24827 lock.l_start = SHARED_FIRST;
24828 lock.l_len = divSize;
24829 if( unixFileLock(pFile, &lock)==(-1) ){
24830 tErrno = errno;
24831 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24832 if( IS_LOCK_ERROR(rc) ){
24833 pFile->lastErrno = tErrno;
24835 goto end_unlock;
24837 lock.l_type = F_UNLCK;
24838 lock.l_whence = SEEK_SET;
24839 lock.l_start = SHARED_FIRST+divSize;
24840 lock.l_len = SHARED_SIZE-divSize;
24841 if( unixFileLock(pFile, &lock)==(-1) ){
24842 tErrno = errno;
24843 rc = SQLITE_IOERR_UNLOCK;
24844 if( IS_LOCK_ERROR(rc) ){
24845 pFile->lastErrno = tErrno;
24847 goto end_unlock;
24849 }else
24850 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24852 lock.l_type = F_RDLCK;
24853 lock.l_whence = SEEK_SET;
24854 lock.l_start = SHARED_FIRST;
24855 lock.l_len = SHARED_SIZE;
24856 if( unixFileLock(pFile, &lock) ){
24857 /* In theory, the call to unixFileLock() cannot fail because another
24858 ** process is holding an incompatible lock. If it does, this
24859 ** indicates that the other process is not following the locking
24860 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
24861 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
24862 ** an assert to fail). */
24863 rc = SQLITE_IOERR_RDLOCK;
24864 pFile->lastErrno = errno;
24865 goto end_unlock;
24869 lock.l_type = F_UNLCK;
24870 lock.l_whence = SEEK_SET;
24871 lock.l_start = PENDING_BYTE;
24872 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
24873 if( unixFileLock(pFile, &lock)==0 ){
24874 pInode->eFileLock = SHARED_LOCK;
24875 }else{
24876 rc = SQLITE_IOERR_UNLOCK;
24877 pFile->lastErrno = errno;
24878 goto end_unlock;
24881 if( eFileLock==NO_LOCK ){
24882 /* Decrement the shared lock counter. Release the lock using an
24883 ** OS call only when all threads in this same process have released
24884 ** the lock.
24886 pInode->nShared--;
24887 if( pInode->nShared==0 ){
24888 lock.l_type = F_UNLCK;
24889 lock.l_whence = SEEK_SET;
24890 lock.l_start = lock.l_len = 0L;
24891 if( unixFileLock(pFile, &lock)==0 ){
24892 pInode->eFileLock = NO_LOCK;
24893 }else{
24894 rc = SQLITE_IOERR_UNLOCK;
24895 pFile->lastErrno = errno;
24896 pInode->eFileLock = NO_LOCK;
24897 pFile->eFileLock = NO_LOCK;
24901 /* Decrement the count of locks against this same file. When the
24902 ** count reaches zero, close any other file descriptors whose close
24903 ** was deferred because of outstanding locks.
24905 pInode->nLock--;
24906 assert( pInode->nLock>=0 );
24907 if( pInode->nLock==0 ){
24908 closePendingFds(pFile);
24912 end_unlock:
24913 unixLeaveMutex();
24914 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24915 return rc;
24919 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
24920 ** must be either NO_LOCK or SHARED_LOCK.
24922 ** If the locking level of the file descriptor is already at or below
24923 ** the requested locking level, this routine is a no-op.
24925 static int unixUnlock(sqlite3_file *id, int eFileLock){
24926 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
24927 return posixUnlock(id, eFileLock, 0);
24930 static int unixMapfile(unixFile *pFd, i64 nByte);
24931 static void unixUnmapfile(unixFile *pFd);
24934 ** This function performs the parts of the "close file" operation
24935 ** common to all locking schemes. It closes the directory and file
24936 ** handles, if they are valid, and sets all fields of the unixFile
24937 ** structure to 0.
24939 ** It is *not* necessary to hold the mutex when this routine is called,
24940 ** even on VxWorks. A mutex will be acquired on VxWorks by the
24941 ** vxworksReleaseFileId() routine.
24943 static int closeUnixFile(sqlite3_file *id){
24944 unixFile *pFile = (unixFile*)id;
24945 unixUnmapfile(pFile);
24946 if( pFile->h>=0 ){
24947 robust_close(pFile, pFile->h, __LINE__);
24948 pFile->h = -1;
24950 #if OS_VXWORKS
24951 if( pFile->pId ){
24952 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
24953 osUnlink(pFile->pId->zCanonicalName);
24955 vxworksReleaseFileId(pFile->pId);
24956 pFile->pId = 0;
24958 #endif
24959 OSTRACE(("CLOSE %-3d\n", pFile->h));
24960 OpenCounter(-1);
24961 sqlite3_free(pFile->pUnused);
24962 memset(pFile, 0, sizeof(unixFile));
24963 return SQLITE_OK;
24967 ** Close a file.
24969 static int unixClose(sqlite3_file *id){
24970 int rc = SQLITE_OK;
24971 unixFile *pFile = (unixFile *)id;
24972 verifyDbFile(pFile);
24973 unixUnlock(id, NO_LOCK);
24974 unixEnterMutex();
24976 /* unixFile.pInode is always valid here. Otherwise, a different close
24977 ** routine (e.g. nolockClose()) would be called instead.
24979 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
24980 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
24981 /* If there are outstanding locks, do not actually close the file just
24982 ** yet because that would clear those locks. Instead, add the file
24983 ** descriptor to pInode->pUnused list. It will be automatically closed
24984 ** when the last lock is cleared.
24986 setPendingFd(pFile);
24988 releaseInodeInfo(pFile);
24989 rc = closeUnixFile(id);
24990 unixLeaveMutex();
24991 return rc;
24994 /************** End of the posix advisory lock implementation *****************
24995 ******************************************************************************/
24997 /******************************************************************************
24998 ****************************** No-op Locking **********************************
25000 ** Of the various locking implementations available, this is by far the
25001 ** simplest: locking is ignored. No attempt is made to lock the database
25002 ** file for reading or writing.
25004 ** This locking mode is appropriate for use on read-only databases
25005 ** (ex: databases that are burned into CD-ROM, for example.) It can
25006 ** also be used if the application employs some external mechanism to
25007 ** prevent simultaneous access of the same database by two or more
25008 ** database connections. But there is a serious risk of database
25009 ** corruption if this locking mode is used in situations where multiple
25010 ** database connections are accessing the same database file at the same
25011 ** time and one or more of those connections are writing.
25014 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25015 UNUSED_PARAMETER(NotUsed);
25016 *pResOut = 0;
25017 return SQLITE_OK;
25019 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25020 UNUSED_PARAMETER2(NotUsed, NotUsed2);
25021 return SQLITE_OK;
25023 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25024 UNUSED_PARAMETER2(NotUsed, NotUsed2);
25025 return SQLITE_OK;
25029 ** Close the file.
25031 static int nolockClose(sqlite3_file *id) {
25032 return closeUnixFile(id);
25035 /******************* End of the no-op lock implementation *********************
25036 ******************************************************************************/
25038 /******************************************************************************
25039 ************************* Begin dot-file Locking ******************************
25041 ** The dotfile locking implementation uses the existence of separate lock
25042 ** files (really a directory) to control access to the database. This works
25043 ** on just about every filesystem imaginable. But there are serious downsides:
25045 ** (1) There is zero concurrency. A single reader blocks all other
25046 ** connections from reading or writing the database.
25048 ** (2) An application crash or power loss can leave stale lock files
25049 ** sitting around that need to be cleared manually.
25051 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
25052 ** other locking strategy is available.
25054 ** Dotfile locking works by creating a subdirectory in the same directory as
25055 ** the database and with the same name but with a ".lock" extension added.
25056 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
25057 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
25061 ** The file suffix added to the data base filename in order to create the
25062 ** lock directory.
25064 #define DOTLOCK_SUFFIX ".lock"
25067 ** This routine checks if there is a RESERVED lock held on the specified
25068 ** file by this or any other process. If such a lock is held, set *pResOut
25069 ** to a non-zero value otherwise *pResOut is set to zero. The return value
25070 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25072 ** In dotfile locking, either a lock exists or it does not. So in this
25073 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
25074 ** is held on the file and false if the file is unlocked.
25076 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
25077 int rc = SQLITE_OK;
25078 int reserved = 0;
25079 unixFile *pFile = (unixFile*)id;
25081 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25083 assert( pFile );
25085 /* Check if a thread in this process holds such a lock */
25086 if( pFile->eFileLock>SHARED_LOCK ){
25087 /* Either this connection or some other connection in the same process
25088 ** holds a lock on the file. No need to check further. */
25089 reserved = 1;
25090 }else{
25091 /* The lock is held if and only if the lockfile exists */
25092 const char *zLockFile = (const char*)pFile->lockingContext;
25093 reserved = osAccess(zLockFile, 0)==0;
25095 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
25096 *pResOut = reserved;
25097 return rc;
25101 ** Lock the file with the lock specified by parameter eFileLock - one
25102 ** of the following:
25104 ** (1) SHARED_LOCK
25105 ** (2) RESERVED_LOCK
25106 ** (3) PENDING_LOCK
25107 ** (4) EXCLUSIVE_LOCK
25109 ** Sometimes when requesting one lock state, additional lock states
25110 ** are inserted in between. The locking might fail on one of the later
25111 ** transitions leaving the lock state different from what it started but
25112 ** still short of its goal. The following chart shows the allowed
25113 ** transitions and the inserted intermediate states:
25115 ** UNLOCKED -> SHARED
25116 ** SHARED -> RESERVED
25117 ** SHARED -> (PENDING) -> EXCLUSIVE
25118 ** RESERVED -> (PENDING) -> EXCLUSIVE
25119 ** PENDING -> EXCLUSIVE
25121 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
25122 ** routine to lower a locking level.
25124 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
25125 ** But we track the other locking levels internally.
25127 static int dotlockLock(sqlite3_file *id, int eFileLock) {
25128 unixFile *pFile = (unixFile*)id;
25129 char *zLockFile = (char *)pFile->lockingContext;
25130 int rc = SQLITE_OK;
25133 /* If we have any lock, then the lock file already exists. All we have
25134 ** to do is adjust our internal record of the lock level.
25136 if( pFile->eFileLock > NO_LOCK ){
25137 pFile->eFileLock = eFileLock;
25138 /* Always update the timestamp on the old file */
25139 #ifdef HAVE_UTIME
25140 utime(zLockFile, NULL);
25141 #else
25142 utimes(zLockFile, NULL);
25143 #endif
25144 return SQLITE_OK;
25147 /* grab an exclusive lock */
25148 rc = osMkdir(zLockFile, 0777);
25149 if( rc<0 ){
25150 /* failed to open/create the lock directory */
25151 int tErrno = errno;
25152 if( EEXIST == tErrno ){
25153 rc = SQLITE_BUSY;
25154 } else {
25155 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25156 if( IS_LOCK_ERROR(rc) ){
25157 pFile->lastErrno = tErrno;
25160 return rc;
25163 /* got it, set the type and return ok */
25164 pFile->eFileLock = eFileLock;
25165 return rc;
25169 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25170 ** must be either NO_LOCK or SHARED_LOCK.
25172 ** If the locking level of the file descriptor is already at or below
25173 ** the requested locking level, this routine is a no-op.
25175 ** When the locking level reaches NO_LOCK, delete the lock file.
25177 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
25178 unixFile *pFile = (unixFile*)id;
25179 char *zLockFile = (char *)pFile->lockingContext;
25180 int rc;
25182 assert( pFile );
25183 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
25184 pFile->eFileLock, getpid()));
25185 assert( eFileLock<=SHARED_LOCK );
25187 /* no-op if possible */
25188 if( pFile->eFileLock==eFileLock ){
25189 return SQLITE_OK;
25192 /* To downgrade to shared, simply update our internal notion of the
25193 ** lock state. No need to mess with the file on disk.
25195 if( eFileLock==SHARED_LOCK ){
25196 pFile->eFileLock = SHARED_LOCK;
25197 return SQLITE_OK;
25200 /* To fully unlock the database, delete the lock file */
25201 assert( eFileLock==NO_LOCK );
25202 rc = osRmdir(zLockFile);
25203 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
25204 if( rc<0 ){
25205 int tErrno = errno;
25206 rc = 0;
25207 if( ENOENT != tErrno ){
25208 rc = SQLITE_IOERR_UNLOCK;
25210 if( IS_LOCK_ERROR(rc) ){
25211 pFile->lastErrno = tErrno;
25213 return rc;
25215 pFile->eFileLock = NO_LOCK;
25216 return SQLITE_OK;
25220 ** Close a file. Make sure the lock has been released before closing.
25222 static int dotlockClose(sqlite3_file *id) {
25223 int rc = SQLITE_OK;
25224 if( id ){
25225 unixFile *pFile = (unixFile*)id;
25226 dotlockUnlock(id, NO_LOCK);
25227 sqlite3_free(pFile->lockingContext);
25228 rc = closeUnixFile(id);
25230 return rc;
25232 /****************** End of the dot-file lock implementation *******************
25233 ******************************************************************************/
25235 /******************************************************************************
25236 ************************** Begin flock Locking ********************************
25238 ** Use the flock() system call to do file locking.
25240 ** flock() locking is like dot-file locking in that the various
25241 ** fine-grain locking levels supported by SQLite are collapsed into
25242 ** a single exclusive lock. In other words, SHARED, RESERVED, and
25243 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
25244 ** still works when you do this, but concurrency is reduced since
25245 ** only a single process can be reading the database at a time.
25247 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
25248 ** compiling for VXWORKS.
25250 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
25253 ** Retry flock() calls that fail with EINTR
25255 #ifdef EINTR
25256 static int robust_flock(int fd, int op){
25257 int rc;
25258 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
25259 return rc;
25261 #else
25262 # define robust_flock(a,b) flock(a,b)
25263 #endif
25267 ** This routine checks if there is a RESERVED lock held on the specified
25268 ** file by this or any other process. If such a lock is held, set *pResOut
25269 ** to a non-zero value otherwise *pResOut is set to zero. The return value
25270 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25272 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
25273 int rc = SQLITE_OK;
25274 int reserved = 0;
25275 unixFile *pFile = (unixFile*)id;
25277 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25279 assert( pFile );
25281 /* Check if a thread in this process holds such a lock */
25282 if( pFile->eFileLock>SHARED_LOCK ){
25283 reserved = 1;
25286 /* Otherwise see if some other process holds it. */
25287 if( !reserved ){
25288 /* attempt to get the lock */
25289 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
25290 if( !lrc ){
25291 /* got the lock, unlock it */
25292 lrc = robust_flock(pFile->h, LOCK_UN);
25293 if ( lrc ) {
25294 int tErrno = errno;
25295 /* unlock failed with an error */
25296 lrc = SQLITE_IOERR_UNLOCK;
25297 if( IS_LOCK_ERROR(lrc) ){
25298 pFile->lastErrno = tErrno;
25299 rc = lrc;
25302 } else {
25303 int tErrno = errno;
25304 reserved = 1;
25305 /* someone else might have it reserved */
25306 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25307 if( IS_LOCK_ERROR(lrc) ){
25308 pFile->lastErrno = tErrno;
25309 rc = lrc;
25313 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
25315 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25316 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25317 rc = SQLITE_OK;
25318 reserved=1;
25320 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25321 *pResOut = reserved;
25322 return rc;
25326 ** Lock the file with the lock specified by parameter eFileLock - one
25327 ** of the following:
25329 ** (1) SHARED_LOCK
25330 ** (2) RESERVED_LOCK
25331 ** (3) PENDING_LOCK
25332 ** (4) EXCLUSIVE_LOCK
25334 ** Sometimes when requesting one lock state, additional lock states
25335 ** are inserted in between. The locking might fail on one of the later
25336 ** transitions leaving the lock state different from what it started but
25337 ** still short of its goal. The following chart shows the allowed
25338 ** transitions and the inserted intermediate states:
25340 ** UNLOCKED -> SHARED
25341 ** SHARED -> RESERVED
25342 ** SHARED -> (PENDING) -> EXCLUSIVE
25343 ** RESERVED -> (PENDING) -> EXCLUSIVE
25344 ** PENDING -> EXCLUSIVE
25346 ** flock() only really support EXCLUSIVE locks. We track intermediate
25347 ** lock states in the sqlite3_file structure, but all locks SHARED or
25348 ** above are really EXCLUSIVE locks and exclude all other processes from
25349 ** access the file.
25351 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
25352 ** routine to lower a locking level.
25354 static int flockLock(sqlite3_file *id, int eFileLock) {
25355 int rc = SQLITE_OK;
25356 unixFile *pFile = (unixFile*)id;
25358 assert( pFile );
25360 /* if we already have a lock, it is exclusive.
25361 ** Just adjust level and punt on outta here. */
25362 if (pFile->eFileLock > NO_LOCK) {
25363 pFile->eFileLock = eFileLock;
25364 return SQLITE_OK;
25367 /* grab an exclusive lock */
25369 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
25370 int tErrno = errno;
25371 /* didn't get, must be busy */
25372 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25373 if( IS_LOCK_ERROR(rc) ){
25374 pFile->lastErrno = tErrno;
25376 } else {
25377 /* got it, set the type and return ok */
25378 pFile->eFileLock = eFileLock;
25380 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
25381 rc==SQLITE_OK ? "ok" : "failed"));
25382 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25383 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25384 rc = SQLITE_BUSY;
25386 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25387 return rc;
25392 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25393 ** must be either NO_LOCK or SHARED_LOCK.
25395 ** If the locking level of the file descriptor is already at or below
25396 ** the requested locking level, this routine is a no-op.
25398 static int flockUnlock(sqlite3_file *id, int eFileLock) {
25399 unixFile *pFile = (unixFile*)id;
25401 assert( pFile );
25402 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
25403 pFile->eFileLock, getpid()));
25404 assert( eFileLock<=SHARED_LOCK );
25406 /* no-op if possible */
25407 if( pFile->eFileLock==eFileLock ){
25408 return SQLITE_OK;
25411 /* shared can just be set because we always have an exclusive */
25412 if (eFileLock==SHARED_LOCK) {
25413 pFile->eFileLock = eFileLock;
25414 return SQLITE_OK;
25417 /* no, really, unlock. */
25418 if( robust_flock(pFile->h, LOCK_UN) ){
25419 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25420 return SQLITE_OK;
25421 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25422 return SQLITE_IOERR_UNLOCK;
25423 }else{
25424 pFile->eFileLock = NO_LOCK;
25425 return SQLITE_OK;
25430 ** Close a file.
25432 static int flockClose(sqlite3_file *id) {
25433 int rc = SQLITE_OK;
25434 if( id ){
25435 flockUnlock(id, NO_LOCK);
25436 rc = closeUnixFile(id);
25438 return rc;
25441 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
25443 /******************* End of the flock lock implementation *********************
25444 ******************************************************************************/
25446 /******************************************************************************
25447 ************************ Begin Named Semaphore Locking ************************
25449 ** Named semaphore locking is only supported on VxWorks.
25451 ** Semaphore locking is like dot-lock and flock in that it really only
25452 ** supports EXCLUSIVE locking. Only a single process can read or write
25453 ** the database file at a time. This reduces potential concurrency, but
25454 ** makes the lock implementation much easier.
25456 #if OS_VXWORKS
25459 ** This routine checks if there is a RESERVED lock held on the specified
25460 ** file by this or any other process. If such a lock is held, set *pResOut
25461 ** to a non-zero value otherwise *pResOut is set to zero. The return value
25462 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25464 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
25465 int rc = SQLITE_OK;
25466 int reserved = 0;
25467 unixFile *pFile = (unixFile*)id;
25469 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25471 assert( pFile );
25473 /* Check if a thread in this process holds such a lock */
25474 if( pFile->eFileLock>SHARED_LOCK ){
25475 reserved = 1;
25478 /* Otherwise see if some other process holds it. */
25479 if( !reserved ){
25480 sem_t *pSem = pFile->pInode->pSem;
25481 struct stat statBuf;
25483 if( sem_trywait(pSem)==-1 ){
25484 int tErrno = errno;
25485 if( EAGAIN != tErrno ){
25486 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
25487 pFile->lastErrno = tErrno;
25488 } else {
25489 /* someone else has the lock when we are in NO_LOCK */
25490 reserved = (pFile->eFileLock < SHARED_LOCK);
25492 }else{
25493 /* we could have it if we want it */
25494 sem_post(pSem);
25497 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
25499 *pResOut = reserved;
25500 return rc;
25504 ** Lock the file with the lock specified by parameter eFileLock - one
25505 ** of the following:
25507 ** (1) SHARED_LOCK
25508 ** (2) RESERVED_LOCK
25509 ** (3) PENDING_LOCK
25510 ** (4) EXCLUSIVE_LOCK
25512 ** Sometimes when requesting one lock state, additional lock states
25513 ** are inserted in between. The locking might fail on one of the later
25514 ** transitions leaving the lock state different from what it started but
25515 ** still short of its goal. The following chart shows the allowed
25516 ** transitions and the inserted intermediate states:
25518 ** UNLOCKED -> SHARED
25519 ** SHARED -> RESERVED
25520 ** SHARED -> (PENDING) -> EXCLUSIVE
25521 ** RESERVED -> (PENDING) -> EXCLUSIVE
25522 ** PENDING -> EXCLUSIVE
25524 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
25525 ** lock states in the sqlite3_file structure, but all locks SHARED or
25526 ** above are really EXCLUSIVE locks and exclude all other processes from
25527 ** access the file.
25529 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
25530 ** routine to lower a locking level.
25532 static int semLock(sqlite3_file *id, int eFileLock) {
25533 unixFile *pFile = (unixFile*)id;
25534 int fd;
25535 sem_t *pSem = pFile->pInode->pSem;
25536 int rc = SQLITE_OK;
25538 /* if we already have a lock, it is exclusive.
25539 ** Just adjust level and punt on outta here. */
25540 if (pFile->eFileLock > NO_LOCK) {
25541 pFile->eFileLock = eFileLock;
25542 rc = SQLITE_OK;
25543 goto sem_end_lock;
25546 /* lock semaphore now but bail out when already locked. */
25547 if( sem_trywait(pSem)==-1 ){
25548 rc = SQLITE_BUSY;
25549 goto sem_end_lock;
25552 /* got it, set the type and return ok */
25553 pFile->eFileLock = eFileLock;
25555 sem_end_lock:
25556 return rc;
25560 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25561 ** must be either NO_LOCK or SHARED_LOCK.
25563 ** If the locking level of the file descriptor is already at or below
25564 ** the requested locking level, this routine is a no-op.
25566 static int semUnlock(sqlite3_file *id, int eFileLock) {
25567 unixFile *pFile = (unixFile*)id;
25568 sem_t *pSem = pFile->pInode->pSem;
25570 assert( pFile );
25571 assert( pSem );
25572 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
25573 pFile->eFileLock, getpid()));
25574 assert( eFileLock<=SHARED_LOCK );
25576 /* no-op if possible */
25577 if( pFile->eFileLock==eFileLock ){
25578 return SQLITE_OK;
25581 /* shared can just be set because we always have an exclusive */
25582 if (eFileLock==SHARED_LOCK) {
25583 pFile->eFileLock = eFileLock;
25584 return SQLITE_OK;
25587 /* no, really unlock. */
25588 if ( sem_post(pSem)==-1 ) {
25589 int rc, tErrno = errno;
25590 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
25591 if( IS_LOCK_ERROR(rc) ){
25592 pFile->lastErrno = tErrno;
25594 return rc;
25596 pFile->eFileLock = NO_LOCK;
25597 return SQLITE_OK;
25601 ** Close a file.
25603 static int semClose(sqlite3_file *id) {
25604 if( id ){
25605 unixFile *pFile = (unixFile*)id;
25606 semUnlock(id, NO_LOCK);
25607 assert( pFile );
25608 unixEnterMutex();
25609 releaseInodeInfo(pFile);
25610 unixLeaveMutex();
25611 closeUnixFile(id);
25613 return SQLITE_OK;
25616 #endif /* OS_VXWORKS */
25618 ** Named semaphore locking is only available on VxWorks.
25620 *************** End of the named semaphore lock implementation ****************
25621 ******************************************************************************/
25624 /******************************************************************************
25625 *************************** Begin AFP Locking *********************************
25627 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
25628 ** on Apple Macintosh computers - both OS9 and OSX.
25630 ** Third-party implementations of AFP are available. But this code here
25631 ** only works on OSX.
25634 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25636 ** The afpLockingContext structure contains all afp lock specific state
25638 typedef struct afpLockingContext afpLockingContext;
25639 struct afpLockingContext {
25640 int reserved;
25641 const char *dbPath; /* Name of the open file */
25644 struct ByteRangeLockPB2
25646 unsigned long long offset; /* offset to first byte to lock */
25647 unsigned long long length; /* nbr of bytes to lock */
25648 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
25649 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
25650 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
25651 int fd; /* file desc to assoc this lock with */
25654 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
25657 ** This is a utility for setting or clearing a bit-range lock on an
25658 ** AFP filesystem.
25660 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25662 static int afpSetLock(
25663 const char *path, /* Name of the file to be locked or unlocked */
25664 unixFile *pFile, /* Open file descriptor on path */
25665 unsigned long long offset, /* First byte to be locked */
25666 unsigned long long length, /* Number of bytes to lock */
25667 int setLockFlag /* True to set lock. False to clear lock */
25669 struct ByteRangeLockPB2 pb;
25670 int err;
25672 pb.unLockFlag = setLockFlag ? 0 : 1;
25673 pb.startEndFlag = 0;
25674 pb.offset = offset;
25675 pb.length = length;
25676 pb.fd = pFile->h;
25678 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
25679 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25680 offset, length));
25681 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25682 if ( err==-1 ) {
25683 int rc;
25684 int tErrno = errno;
25685 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25686 path, tErrno, strerror(tErrno)));
25687 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25688 rc = SQLITE_BUSY;
25689 #else
25690 rc = sqliteErrorFromPosixError(tErrno,
25691 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25692 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25693 if( IS_LOCK_ERROR(rc) ){
25694 pFile->lastErrno = tErrno;
25696 return rc;
25697 } else {
25698 return SQLITE_OK;
25703 ** This routine checks if there is a RESERVED lock held on the specified
25704 ** file by this or any other process. If such a lock is held, set *pResOut
25705 ** to a non-zero value otherwise *pResOut is set to zero. The return value
25706 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25708 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25709 int rc = SQLITE_OK;
25710 int reserved = 0;
25711 unixFile *pFile = (unixFile*)id;
25712 afpLockingContext *context;
25714 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25716 assert( pFile );
25717 context = (afpLockingContext *) pFile->lockingContext;
25718 if( context->reserved ){
25719 *pResOut = 1;
25720 return SQLITE_OK;
25722 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25724 /* Check if a thread in this process holds such a lock */
25725 if( pFile->pInode->eFileLock>SHARED_LOCK ){
25726 reserved = 1;
25729 /* Otherwise see if some other process holds it.
25731 if( !reserved ){
25732 /* lock the RESERVED byte */
25733 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25734 if( SQLITE_OK==lrc ){
25735 /* if we succeeded in taking the reserved lock, unlock it to restore
25736 ** the original state */
25737 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25738 } else {
25739 /* if we failed to get the lock then someone else must have it */
25740 reserved = 1;
25742 if( IS_LOCK_ERROR(lrc) ){
25743 rc=lrc;
25747 unixLeaveMutex();
25748 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
25750 *pResOut = reserved;
25751 return rc;
25755 ** Lock the file with the lock specified by parameter eFileLock - one
25756 ** of the following:
25758 ** (1) SHARED_LOCK
25759 ** (2) RESERVED_LOCK
25760 ** (3) PENDING_LOCK
25761 ** (4) EXCLUSIVE_LOCK
25763 ** Sometimes when requesting one lock state, additional lock states
25764 ** are inserted in between. The locking might fail on one of the later
25765 ** transitions leaving the lock state different from what it started but
25766 ** still short of its goal. The following chart shows the allowed
25767 ** transitions and the inserted intermediate states:
25769 ** UNLOCKED -> SHARED
25770 ** SHARED -> RESERVED
25771 ** SHARED -> (PENDING) -> EXCLUSIVE
25772 ** RESERVED -> (PENDING) -> EXCLUSIVE
25773 ** PENDING -> EXCLUSIVE
25775 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
25776 ** routine to lower a locking level.
25778 static int afpLock(sqlite3_file *id, int eFileLock){
25779 int rc = SQLITE_OK;
25780 unixFile *pFile = (unixFile*)id;
25781 unixInodeInfo *pInode = pFile->pInode;
25782 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25784 assert( pFile );
25785 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
25786 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25787 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25789 /* If there is already a lock of this type or more restrictive on the
25790 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
25791 ** unixEnterMutex() hasn't been called yet.
25793 if( pFile->eFileLock>=eFileLock ){
25794 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
25795 azFileLock(eFileLock)));
25796 return SQLITE_OK;
25799 /* Make sure the locking sequence is correct
25800 ** (1) We never move from unlocked to anything higher than shared lock.
25801 ** (2) SQLite never explicitly requests a pendig lock.
25802 ** (3) A shared lock is always held when a reserve lock is requested.
25804 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25805 assert( eFileLock!=PENDING_LOCK );
25806 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25808 /* This mutex is needed because pFile->pInode is shared across threads
25810 unixEnterMutex();
25811 pInode = pFile->pInode;
25813 /* If some thread using this PID has a lock via a different unixFile*
25814 ** handle that precludes the requested lock, return BUSY.
25816 if( (pFile->eFileLock!=pInode->eFileLock &&
25817 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25819 rc = SQLITE_BUSY;
25820 goto afp_end_lock;
25823 /* If a SHARED lock is requested, and some thread using this PID already
25824 ** has a SHARED or RESERVED lock, then increment reference counts and
25825 ** return SQLITE_OK.
25827 if( eFileLock==SHARED_LOCK &&
25828 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25829 assert( eFileLock==SHARED_LOCK );
25830 assert( pFile->eFileLock==0 );
25831 assert( pInode->nShared>0 );
25832 pFile->eFileLock = SHARED_LOCK;
25833 pInode->nShared++;
25834 pInode->nLock++;
25835 goto afp_end_lock;
25838 /* A PENDING lock is needed before acquiring a SHARED lock and before
25839 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
25840 ** be released.
25842 if( eFileLock==SHARED_LOCK
25843 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25845 int failed;
25846 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
25847 if (failed) {
25848 rc = failed;
25849 goto afp_end_lock;
25853 /* If control gets to this point, then actually go ahead and make
25854 ** operating system calls for the specified lock.
25856 if( eFileLock==SHARED_LOCK ){
25857 int lrc1, lrc2, lrc1Errno = 0;
25858 long lk, mask;
25860 assert( pInode->nShared==0 );
25861 assert( pInode->eFileLock==0 );
25863 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
25864 /* Now get the read-lock SHARED_LOCK */
25865 /* note that the quality of the randomness doesn't matter that much */
25866 lk = random();
25867 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
25868 lrc1 = afpSetLock(context->dbPath, pFile,
25869 SHARED_FIRST+pInode->sharedByte, 1, 1);
25870 if( IS_LOCK_ERROR(lrc1) ){
25871 lrc1Errno = pFile->lastErrno;
25873 /* Drop the temporary PENDING lock */
25874 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25876 if( IS_LOCK_ERROR(lrc1) ) {
25877 pFile->lastErrno = lrc1Errno;
25878 rc = lrc1;
25879 goto afp_end_lock;
25880 } else if( IS_LOCK_ERROR(lrc2) ){
25881 rc = lrc2;
25882 goto afp_end_lock;
25883 } else if( lrc1 != SQLITE_OK ) {
25884 rc = lrc1;
25885 } else {
25886 pFile->eFileLock = SHARED_LOCK;
25887 pInode->nLock++;
25888 pInode->nShared = 1;
25890 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25891 /* We are trying for an exclusive lock but another thread in this
25892 ** same process is still holding a shared lock. */
25893 rc = SQLITE_BUSY;
25894 }else{
25895 /* The request was for a RESERVED or EXCLUSIVE lock. It is
25896 ** assumed that there is a SHARED or greater lock on the file
25897 ** already.
25899 int failed = 0;
25900 assert( 0!=pFile->eFileLock );
25901 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
25902 /* Acquire a RESERVED lock */
25903 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25904 if( !failed ){
25905 context->reserved = 1;
25908 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
25909 /* Acquire an EXCLUSIVE lock */
25911 /* Remove the shared lock before trying the range. we'll need to
25912 ** reestablish the shared lock if we can't get the afpUnlock
25914 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
25915 pInode->sharedByte, 1, 0)) ){
25916 int failed2 = SQLITE_OK;
25917 /* now attemmpt to get the exclusive lock range */
25918 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
25919 SHARED_SIZE, 1);
25920 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
25921 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25922 /* Can't reestablish the shared lock. Sqlite can't deal, this is
25923 ** a critical I/O error
25925 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
25926 SQLITE_IOERR_LOCK;
25927 goto afp_end_lock;
25929 }else{
25930 rc = failed;
25933 if( failed ){
25934 rc = failed;
25938 if( rc==SQLITE_OK ){
25939 pFile->eFileLock = eFileLock;
25940 pInode->eFileLock = eFileLock;
25941 }else if( eFileLock==EXCLUSIVE_LOCK ){
25942 pFile->eFileLock = PENDING_LOCK;
25943 pInode->eFileLock = PENDING_LOCK;
25946 afp_end_lock:
25947 unixLeaveMutex();
25948 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
25949 rc==SQLITE_OK ? "ok" : "failed"));
25950 return rc;
25954 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25955 ** must be either NO_LOCK or SHARED_LOCK.
25957 ** If the locking level of the file descriptor is already at or below
25958 ** the requested locking level, this routine is a no-op.
25960 static int afpUnlock(sqlite3_file *id, int eFileLock) {
25961 int rc = SQLITE_OK;
25962 unixFile *pFile = (unixFile*)id;
25963 unixInodeInfo *pInode;
25964 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25965 int skipShared = 0;
25966 #ifdef SQLITE_TEST
25967 int h = pFile->h;
25968 #endif
25970 assert( pFile );
25971 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
25972 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25973 getpid()));
25975 assert( eFileLock<=SHARED_LOCK );
25976 if( pFile->eFileLock<=eFileLock ){
25977 return SQLITE_OK;
25979 unixEnterMutex();
25980 pInode = pFile->pInode;
25981 assert( pInode->nShared!=0 );
25982 if( pFile->eFileLock>SHARED_LOCK ){
25983 assert( pInode->eFileLock==pFile->eFileLock );
25984 SimulateIOErrorBenign(1);
25985 SimulateIOError( h=(-1) )
25986 SimulateIOErrorBenign(0);
25988 #ifdef SQLITE_DEBUG
25989 /* When reducing a lock such that other processes can start
25990 ** reading the database file again, make sure that the
25991 ** transaction counter was updated if any part of the database
25992 ** file changed. If the transaction counter is not updated,
25993 ** other connections to the same file might not realize that
25994 ** the file has changed and hence might not know to flush their
25995 ** cache. The use of a stale cache can lead to database corruption.
25997 assert( pFile->inNormalWrite==0
25998 || pFile->dbUpdate==0
25999 || pFile->transCntrChng==1 );
26000 pFile->inNormalWrite = 0;
26001 #endif
26003 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26004 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26005 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26006 /* only re-establish the shared lock if necessary */
26007 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26008 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26009 } else {
26010 skipShared = 1;
26013 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26014 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26016 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26017 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26018 if( !rc ){
26019 context->reserved = 0;
26022 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26023 pInode->eFileLock = SHARED_LOCK;
26026 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26028 /* Decrement the shared lock counter. Release the lock using an
26029 ** OS call only when all threads in this same process have released
26030 ** the lock.
26032 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26033 pInode->nShared--;
26034 if( pInode->nShared==0 ){
26035 SimulateIOErrorBenign(1);
26036 SimulateIOError( h=(-1) )
26037 SimulateIOErrorBenign(0);
26038 if( !skipShared ){
26039 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26041 if( !rc ){
26042 pInode->eFileLock = NO_LOCK;
26043 pFile->eFileLock = NO_LOCK;
26046 if( rc==SQLITE_OK ){
26047 pInode->nLock--;
26048 assert( pInode->nLock>=0 );
26049 if( pInode->nLock==0 ){
26050 closePendingFds(pFile);
26055 unixLeaveMutex();
26056 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26057 return rc;
26061 ** Close a file & cleanup AFP specific locking context
26063 static int afpClose(sqlite3_file *id) {
26064 int rc = SQLITE_OK;
26065 if( id ){
26066 unixFile *pFile = (unixFile*)id;
26067 afpUnlock(id, NO_LOCK);
26068 unixEnterMutex();
26069 if( pFile->pInode && pFile->pInode->nLock ){
26070 /* If there are outstanding locks, do not actually close the file just
26071 ** yet because that would clear those locks. Instead, add the file
26072 ** descriptor to pInode->aPending. It will be automatically closed when
26073 ** the last lock is cleared.
26075 setPendingFd(pFile);
26077 releaseInodeInfo(pFile);
26078 sqlite3_free(pFile->lockingContext);
26079 rc = closeUnixFile(id);
26080 unixLeaveMutex();
26082 return rc;
26085 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26087 ** The code above is the AFP lock implementation. The code is specific
26088 ** to MacOSX and does not work on other unix platforms. No alternative
26089 ** is available. If you don't compile for a mac, then the "unix-afp"
26090 ** VFS is not available.
26092 ********************* End of the AFP lock implementation **********************
26093 ******************************************************************************/
26095 /******************************************************************************
26096 *************************** Begin NFS Locking ********************************/
26098 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26100 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26101 ** must be either NO_LOCK or SHARED_LOCK.
26103 ** If the locking level of the file descriptor is already at or below
26104 ** the requested locking level, this routine is a no-op.
26106 static int nfsUnlock(sqlite3_file *id, int eFileLock){
26107 return posixUnlock(id, eFileLock, 1);
26110 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26112 ** The code above is the NFS lock implementation. The code is specific
26113 ** to MacOSX and does not work on other unix platforms. No alternative
26114 ** is available.
26116 ********************* End of the NFS lock implementation **********************
26117 ******************************************************************************/
26119 /******************************************************************************
26120 **************** Non-locking sqlite3_file methods *****************************
26122 ** The next division contains implementations for all methods of the
26123 ** sqlite3_file object other than the locking methods. The locking
26124 ** methods were defined in divisions above (one locking method per
26125 ** division). Those methods that are common to all locking modes
26126 ** are gather together into this division.
26130 ** Seek to the offset passed as the second argument, then read cnt
26131 ** bytes into pBuf. Return the number of bytes actually read.
26133 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
26134 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
26135 ** one system to another. Since SQLite does not define USE_PREAD
26136 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
26137 ** See tickets #2741 and #2681.
26139 ** To avoid stomping the errno value on a failed read the lastErrno value
26140 ** is set before returning.
26142 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
26143 int got;
26144 int prior = 0;
26145 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
26146 i64 newOffset;
26147 #endif
26148 TIMER_START;
26149 assert( cnt==(cnt&0x1ffff) );
26150 cnt &= 0x1ffff;
26152 #if defined(USE_PREAD)
26153 got = osPread(id->h, pBuf, cnt, offset);
26154 SimulateIOError( got = -1 );
26155 #elif defined(USE_PREAD64)
26156 got = osPread64(id->h, pBuf, cnt, offset);
26157 SimulateIOError( got = -1 );
26158 #else
26159 newOffset = lseek(id->h, offset, SEEK_SET);
26160 SimulateIOError( newOffset-- );
26161 if( newOffset!=offset ){
26162 if( newOffset == -1 ){
26163 ((unixFile*)id)->lastErrno = errno;
26164 }else{
26165 ((unixFile*)id)->lastErrno = 0;
26167 return -1;
26169 got = osRead(id->h, pBuf, cnt);
26170 #endif
26171 if( got==cnt ) break;
26172 if( got<0 ){
26173 if( errno==EINTR ){ got = 1; continue; }
26174 prior = 0;
26175 ((unixFile*)id)->lastErrno = errno;
26176 break;
26177 }else if( got>0 ){
26178 cnt -= got;
26179 offset += got;
26180 prior += got;
26181 pBuf = (void*)(got + (char*)pBuf);
26183 }while( got>0 );
26184 TIMER_END;
26185 OSTRACE(("READ %-3d %5d %7lld %llu\n",
26186 id->h, got+prior, offset-prior, TIMER_ELAPSED));
26187 return got+prior;
26191 ** Read data from a file into a buffer. Return SQLITE_OK if all
26192 ** bytes were read successfully and SQLITE_IOERR if anything goes
26193 ** wrong.
26195 static int unixRead(
26196 sqlite3_file *id,
26197 void *pBuf,
26198 int amt,
26199 sqlite3_int64 offset
26201 unixFile *pFile = (unixFile *)id;
26202 int got;
26203 assert( id );
26204 assert( offset>=0 );
26205 assert( amt>0 );
26207 /* If this is a database file (not a journal, master-journal or temp
26208 ** file), the bytes in the locking range should never be read or written. */
26209 #if 0
26210 assert( pFile->pUnused==0
26211 || offset>=PENDING_BYTE+512
26212 || offset+amt<=PENDING_BYTE
26214 #endif
26216 #if SQLITE_MAX_MMAP_SIZE>0
26217 /* Deal with as much of this read request as possible by transfering
26218 ** data from the memory mapping using memcpy(). */
26219 if( offset<pFile->mmapSize ){
26220 if( offset+amt <= pFile->mmapSize ){
26221 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
26222 return SQLITE_OK;
26223 }else{
26224 int nCopy = pFile->mmapSize - offset;
26225 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
26226 pBuf = &((u8 *)pBuf)[nCopy];
26227 amt -= nCopy;
26228 offset += nCopy;
26231 #endif
26233 got = seekAndRead(pFile, offset, pBuf, amt);
26234 if( got==amt ){
26235 return SQLITE_OK;
26236 }else if( got<0 ){
26237 /* lastErrno set by seekAndRead */
26238 return SQLITE_IOERR_READ;
26239 }else{
26240 pFile->lastErrno = 0; /* not a system error */
26241 /* Unread parts of the buffer must be zero-filled */
26242 memset(&((char*)pBuf)[got], 0, amt-got);
26243 return SQLITE_IOERR_SHORT_READ;
26248 ** Attempt to seek the file-descriptor passed as the first argument to
26249 ** absolute offset iOff, then attempt to write nBuf bytes of data from
26250 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
26251 ** return the actual number of bytes written (which may be less than
26252 ** nBuf).
26254 static int seekAndWriteFd(
26255 int fd, /* File descriptor to write to */
26256 i64 iOff, /* File offset to begin writing at */
26257 const void *pBuf, /* Copy data from this buffer to the file */
26258 int nBuf, /* Size of buffer pBuf in bytes */
26259 int *piErrno /* OUT: Error number if error occurs */
26261 int rc = 0; /* Value returned by system call */
26263 assert( nBuf==(nBuf&0x1ffff) );
26264 nBuf &= 0x1ffff;
26265 TIMER_START;
26267 #if defined(USE_PREAD)
26268 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
26269 #elif defined(USE_PREAD64)
26270 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
26271 #else
26273 i64 iSeek = lseek(fd, iOff, SEEK_SET);
26274 SimulateIOError( iSeek-- );
26276 if( iSeek!=iOff ){
26277 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
26278 return -1;
26280 rc = osWrite(fd, pBuf, nBuf);
26281 }while( rc<0 && errno==EINTR );
26282 #endif
26284 TIMER_END;
26285 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
26287 if( rc<0 && piErrno ) *piErrno = errno;
26288 return rc;
26293 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
26294 ** Return the number of bytes actually read. Update the offset.
26296 ** To avoid stomping the errno value on a failed write the lastErrno value
26297 ** is set before returning.
26299 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
26300 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
26305 ** Write data from a buffer into a file. Return SQLITE_OK on success
26306 ** or some other error code on failure.
26308 static int unixWrite(
26309 sqlite3_file *id,
26310 const void *pBuf,
26311 int amt,
26312 sqlite3_int64 offset
26314 unixFile *pFile = (unixFile*)id;
26315 int wrote = 0;
26316 assert( id );
26317 assert( amt>0 );
26319 /* If this is a database file (not a journal, master-journal or temp
26320 ** file), the bytes in the locking range should never be read or written. */
26321 #if 0
26322 assert( pFile->pUnused==0
26323 || offset>=PENDING_BYTE+512
26324 || offset+amt<=PENDING_BYTE
26326 #endif
26328 #ifdef SQLITE_DEBUG
26329 /* If we are doing a normal write to a database file (as opposed to
26330 ** doing a hot-journal rollback or a write to some file other than a
26331 ** normal database file) then record the fact that the database
26332 ** has changed. If the transaction counter is modified, record that
26333 ** fact too.
26335 if( pFile->inNormalWrite ){
26336 pFile->dbUpdate = 1; /* The database has been modified */
26337 if( offset<=24 && offset+amt>=27 ){
26338 int rc;
26339 char oldCntr[4];
26340 SimulateIOErrorBenign(1);
26341 rc = seekAndRead(pFile, 24, oldCntr, 4);
26342 SimulateIOErrorBenign(0);
26343 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
26344 pFile->transCntrChng = 1; /* The transaction counter has changed */
26348 #endif
26350 #if SQLITE_MAX_MMAP_SIZE>0
26351 /* Deal with as much of this write request as possible by transfering
26352 ** data from the memory mapping using memcpy(). */
26353 if( offset<pFile->mmapSize ){
26354 if( offset+amt <= pFile->mmapSize ){
26355 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
26356 return SQLITE_OK;
26357 }else{
26358 int nCopy = pFile->mmapSize - offset;
26359 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
26360 pBuf = &((u8 *)pBuf)[nCopy];
26361 amt -= nCopy;
26362 offset += nCopy;
26365 #endif
26367 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
26368 amt -= wrote;
26369 offset += wrote;
26370 pBuf = &((char*)pBuf)[wrote];
26372 SimulateIOError(( wrote=(-1), amt=1 ));
26373 SimulateDiskfullError(( wrote=0, amt=1 ));
26375 if( amt>0 ){
26376 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
26377 /* lastErrno set by seekAndWrite */
26378 return SQLITE_IOERR_WRITE;
26379 }else{
26380 pFile->lastErrno = 0; /* not a system error */
26381 return SQLITE_FULL;
26385 return SQLITE_OK;
26388 #ifdef SQLITE_TEST
26390 ** Count the number of fullsyncs and normal syncs. This is used to test
26391 ** that syncs and fullsyncs are occurring at the right times.
26393 SQLITE_API int sqlite3_sync_count = 0;
26394 SQLITE_API int sqlite3_fullsync_count = 0;
26395 #endif
26398 ** We do not trust systems to provide a working fdatasync(). Some do.
26399 ** Others do no. To be safe, we will stick with the (slightly slower)
26400 ** fsync(). If you know that your system does support fdatasync() correctly,
26401 ** then simply compile with -Dfdatasync=fdatasync
26403 #if !defined(fdatasync)
26404 # define fdatasync fsync
26405 #endif
26408 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
26409 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
26410 ** only available on Mac OS X. But that could change.
26412 #ifdef F_FULLFSYNC
26413 # define HAVE_FULLFSYNC 1
26414 #else
26415 # define HAVE_FULLFSYNC 0
26416 #endif
26420 ** The fsync() system call does not work as advertised on many
26421 ** unix systems. The following procedure is an attempt to make
26422 ** it work better.
26424 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
26425 ** for testing when we want to run through the test suite quickly.
26426 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
26427 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
26428 ** or power failure will likely corrupt the database file.
26430 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
26431 ** The idea behind dataOnly is that it should only write the file content
26432 ** to disk, not the inode. We only set dataOnly if the file size is
26433 ** unchanged since the file size is part of the inode. However,
26434 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
26435 ** file size has changed. The only real difference between fdatasync()
26436 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
26437 ** inode if the mtime or owner or other inode attributes have changed.
26438 ** We only care about the file size, not the other file attributes, so
26439 ** as far as SQLite is concerned, an fdatasync() is always adequate.
26440 ** So, we always use fdatasync() if it is available, regardless of
26441 ** the value of the dataOnly flag.
26443 static int full_fsync(int fd, int fullSync, int dataOnly){
26444 int rc;
26446 /* The following "ifdef/elif/else/" block has the same structure as
26447 ** the one below. It is replicated here solely to avoid cluttering
26448 ** up the real code with the UNUSED_PARAMETER() macros.
26450 #ifdef SQLITE_NO_SYNC
26451 UNUSED_PARAMETER(fd);
26452 UNUSED_PARAMETER(fullSync);
26453 UNUSED_PARAMETER(dataOnly);
26454 #elif HAVE_FULLFSYNC
26455 UNUSED_PARAMETER(dataOnly);
26456 #else
26457 UNUSED_PARAMETER(fullSync);
26458 UNUSED_PARAMETER(dataOnly);
26459 #endif
26461 /* Record the number of times that we do a normal fsync() and
26462 ** FULLSYNC. This is used during testing to verify that this procedure
26463 ** gets called with the correct arguments.
26465 #ifdef SQLITE_TEST
26466 if( fullSync ) sqlite3_fullsync_count++;
26467 sqlite3_sync_count++;
26468 #endif
26470 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
26471 ** no-op
26473 #ifdef SQLITE_NO_SYNC
26474 rc = SQLITE_OK;
26475 #elif HAVE_FULLFSYNC
26476 if( fullSync ){
26477 rc = osFcntl(fd, F_FULLFSYNC, 0);
26478 }else{
26479 rc = 1;
26481 /* If the FULLFSYNC failed, fall back to attempting an fsync().
26482 ** It shouldn't be possible for fullfsync to fail on the local
26483 ** file system (on OSX), so failure indicates that FULLFSYNC
26484 ** isn't supported for this file system. So, attempt an fsync
26485 ** and (for now) ignore the overhead of a superfluous fcntl call.
26486 ** It'd be better to detect fullfsync support once and avoid
26487 ** the fcntl call every time sync is called.
26489 if( rc ) rc = fsync(fd);
26491 #elif defined(__APPLE__)
26492 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
26493 ** so currently we default to the macro that redefines fdatasync to fsync
26495 rc = fsync(fd);
26496 #else
26497 rc = fdatasync(fd);
26498 #if OS_VXWORKS
26499 if( rc==-1 && errno==ENOTSUP ){
26500 rc = fsync(fd);
26502 #endif /* OS_VXWORKS */
26503 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
26505 if( OS_VXWORKS && rc!= -1 ){
26506 rc = 0;
26508 return rc;
26512 ** Open a file descriptor to the directory containing file zFilename.
26513 ** If successful, *pFd is set to the opened file descriptor and
26514 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26515 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26516 ** value.
26518 ** The directory file descriptor is used for only one thing - to
26519 ** fsync() a directory to make sure file creation and deletion events
26520 ** are flushed to disk. Such fsyncs are not needed on newer
26521 ** journaling filesystems, but are required on older filesystems.
26523 ** This routine can be overridden using the xSetSysCall interface.
26524 ** The ability to override this routine was added in support of the
26525 ** chromium sandbox. Opening a directory is a security risk (we are
26526 ** told) so making it overrideable allows the chromium sandbox to
26527 ** replace this routine with a harmless no-op. To make this routine
26528 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
26529 ** *pFd set to a negative number.
26531 ** If SQLITE_OK is returned, the caller is responsible for closing
26532 ** the file descriptor *pFd using close().
26534 static int openDirectory(const char *zFilename, int *pFd){
26535 int ii;
26536 int fd = -1;
26537 char zDirname[MAX_PATHNAME+1];
26539 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26540 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26541 if( ii>0 ){
26542 zDirname[ii] = '\0';
26543 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
26544 if( fd>=0 ){
26545 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26548 *pFd = fd;
26549 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
26553 ** Make sure all writes to a particular file are committed to disk.
26555 ** If dataOnly==0 then both the file itself and its metadata (file
26556 ** size, access time, etc) are synced. If dataOnly!=0 then only the
26557 ** file data is synced.
26559 ** Under Unix, also make sure that the directory entry for the file
26560 ** has been created by fsync-ing the directory that contains the file.
26561 ** If we do not do this and we encounter a power failure, the directory
26562 ** entry for the journal might not exist after we reboot. The next
26563 ** SQLite to access the file will not know that the journal exists (because
26564 ** the directory entry for the journal was never created) and the transaction
26565 ** will not roll back - possibly leading to database corruption.
26567 static int unixSync(sqlite3_file *id, int flags){
26568 int rc;
26569 unixFile *pFile = (unixFile*)id;
26571 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
26572 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
26574 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
26575 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
26576 || (flags&0x0F)==SQLITE_SYNC_FULL
26579 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
26580 ** line is to test that doing so does not cause any problems.
26582 SimulateDiskfullError( return SQLITE_FULL );
26584 assert( pFile );
26585 OSTRACE(("SYNC %-3d\n", pFile->h));
26586 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
26587 SimulateIOError( rc=1 );
26588 if( rc ){
26589 pFile->lastErrno = errno;
26590 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
26593 /* Also fsync the directory containing the file if the DIRSYNC flag
26594 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
26595 ** are unable to fsync a directory, so ignore errors on the fsync.
26597 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
26598 int dirfd;
26599 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
26600 HAVE_FULLFSYNC, isFullsync));
26601 rc = osOpenDirectory(pFile->zPath, &dirfd);
26602 if( rc==SQLITE_OK && dirfd>=0 ){
26603 full_fsync(dirfd, 0, 0);
26604 robust_close(pFile, dirfd, __LINE__);
26605 }else if( rc==SQLITE_CANTOPEN ){
26606 rc = SQLITE_OK;
26608 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
26610 return rc;
26614 ** Truncate an open file to a specified size
26616 static int unixTruncate(sqlite3_file *id, i64 nByte){
26617 unixFile *pFile = (unixFile *)id;
26618 int rc;
26619 assert( pFile );
26620 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
26622 /* If the user has configured a chunk-size for this file, truncate the
26623 ** file so that it consists of an integer number of chunks (i.e. the
26624 ** actual file size after the operation may be larger than the requested
26625 ** size).
26627 if( pFile->szChunk>0 ){
26628 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
26631 rc = robust_ftruncate(pFile->h, (off_t)nByte);
26632 if( rc ){
26633 pFile->lastErrno = errno;
26634 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26635 }else{
26636 #ifdef SQLITE_DEBUG
26637 /* If we are doing a normal write to a database file (as opposed to
26638 ** doing a hot-journal rollback or a write to some file other than a
26639 ** normal database file) and we truncate the file to zero length,
26640 ** that effectively updates the change counter. This might happen
26641 ** when restoring a database using the backup API from a zero-length
26642 ** source.
26644 if( pFile->inNormalWrite && nByte==0 ){
26645 pFile->transCntrChng = 1;
26647 #endif
26649 /* If the file was just truncated to a size smaller than the currently
26650 ** mapped region, reduce the effective mapping size as well. SQLite will
26651 ** use read() and write() to access data beyond this point from now on.
26653 if( nByte<pFile->mmapSize ){
26654 pFile->mmapSize = nByte;
26657 return SQLITE_OK;
26662 ** Determine the current size of a file in bytes
26664 static int unixFileSize(sqlite3_file *id, i64 *pSize){
26665 int rc;
26666 struct stat buf;
26667 assert( id );
26668 rc = osFstat(((unixFile*)id)->h, &buf);
26669 SimulateIOError( rc=1 );
26670 if( rc!=0 ){
26671 ((unixFile*)id)->lastErrno = errno;
26672 return SQLITE_IOERR_FSTAT;
26674 *pSize = buf.st_size;
26676 /* When opening a zero-size database, the findInodeInfo() procedure
26677 ** writes a single byte into that file in order to work around a bug
26678 ** in the OS-X msdos filesystem. In order to avoid problems with upper
26679 ** layers, we need to report this file size as zero even though it is
26680 ** really 1. Ticket #3260.
26682 if( *pSize==1 ) *pSize = 0;
26685 return SQLITE_OK;
26688 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26690 ** Handler for proxy-locking file-control verbs. Defined below in the
26691 ** proxying locking division.
26693 static int proxyFileControl(sqlite3_file*,int,void*);
26694 #endif
26697 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
26698 ** file-control operation. Enlarge the database to nBytes in size
26699 ** (rounded up to the next chunk-size). If the database is already
26700 ** nBytes or larger, this routine is a no-op.
26702 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
26703 if( pFile->szChunk>0 ){
26704 i64 nSize; /* Required file size */
26705 struct stat buf; /* Used to hold return values of fstat() */
26707 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
26709 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
26710 if( nSize>(i64)buf.st_size ){
26712 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
26713 /* The code below is handling the return value of osFallocate()
26714 ** correctly. posix_fallocate() is defined to "returns zero on success,
26715 ** or an error number on failure". See the manpage for details. */
26716 int err;
26718 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
26719 }while( err==EINTR );
26720 if( err ) return SQLITE_IOERR_WRITE;
26721 #else
26722 /* If the OS does not have posix_fallocate(), fake it. First use
26723 ** ftruncate() to set the file size, then write a single byte to
26724 ** the last byte in each block within the extended region. This
26725 ** is the same technique used by glibc to implement posix_fallocate()
26726 ** on systems that do not have a real fallocate() system call.
26728 int nBlk = buf.st_blksize; /* File-system block size */
26729 i64 iWrite; /* Next offset to write to */
26731 if( robust_ftruncate(pFile->h, nSize) ){
26732 pFile->lastErrno = errno;
26733 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26735 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
26736 while( iWrite<nSize ){
26737 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
26738 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
26739 iWrite += nBlk;
26741 #endif
26745 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
26746 int rc;
26747 if( pFile->szChunk<=0 ){
26748 if( robust_ftruncate(pFile->h, nByte) ){
26749 pFile->lastErrno = errno;
26750 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26754 rc = unixMapfile(pFile, nByte);
26755 return rc;
26758 return SQLITE_OK;
26762 ** If *pArg is inititially negative then this is a query. Set *pArg to
26763 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
26765 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
26767 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
26768 if( *pArg<0 ){
26769 *pArg = (pFile->ctrlFlags & mask)!=0;
26770 }else if( (*pArg)==0 ){
26771 pFile->ctrlFlags &= ~mask;
26772 }else{
26773 pFile->ctrlFlags |= mask;
26777 /* Forward declaration */
26778 static int unixGetTempname(int nBuf, char *zBuf);
26781 ** Information and control of an open file handle.
26783 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
26784 unixFile *pFile = (unixFile*)id;
26785 switch( op ){
26786 case SQLITE_FCNTL_LOCKSTATE: {
26787 *(int*)pArg = pFile->eFileLock;
26788 return SQLITE_OK;
26790 case SQLITE_LAST_ERRNO: {
26791 *(int*)pArg = pFile->lastErrno;
26792 return SQLITE_OK;
26794 case SQLITE_FCNTL_CHUNK_SIZE: {
26795 pFile->szChunk = *(int *)pArg;
26796 return SQLITE_OK;
26798 case SQLITE_FCNTL_SIZE_HINT: {
26799 int rc;
26800 SimulateIOErrorBenign(1);
26801 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
26802 SimulateIOErrorBenign(0);
26803 return rc;
26805 case SQLITE_FCNTL_PERSIST_WAL: {
26806 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
26807 return SQLITE_OK;
26809 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
26810 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
26811 return SQLITE_OK;
26813 case SQLITE_FCNTL_VFSNAME: {
26814 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
26815 return SQLITE_OK;
26817 case SQLITE_FCNTL_TEMPFILENAME: {
26818 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
26819 if( zTFile ){
26820 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
26821 *(char**)pArg = zTFile;
26823 return SQLITE_OK;
26825 case SQLITE_FCNTL_MMAP_SIZE: {
26826 i64 newLimit = *(i64*)pArg;
26827 int rc = SQLITE_OK;
26828 if( newLimit>sqlite3GlobalConfig.mxMmap ){
26829 newLimit = sqlite3GlobalConfig.mxMmap;
26831 *(i64*)pArg = pFile->mmapSizeMax;
26832 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
26833 pFile->mmapSizeMax = newLimit;
26834 if( pFile->mmapSize>0 ){
26835 unixUnmapfile(pFile);
26836 rc = unixMapfile(pFile, -1);
26839 return rc;
26841 #ifdef SQLITE_DEBUG
26842 /* The pager calls this method to signal that it has done
26843 ** a rollback and that the database is therefore unchanged and
26844 ** it hence it is OK for the transaction change counter to be
26845 ** unchanged.
26847 case SQLITE_FCNTL_DB_UNCHANGED: {
26848 ((unixFile*)id)->dbUpdate = 0;
26849 return SQLITE_OK;
26851 #endif
26852 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26853 case SQLITE_SET_LOCKPROXYFILE:
26854 case SQLITE_GET_LOCKPROXYFILE: {
26855 return proxyFileControl(id,op,pArg);
26857 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
26859 return SQLITE_NOTFOUND;
26863 ** Return the sector size in bytes of the underlying block device for
26864 ** the specified file. This is almost always 512 bytes, but may be
26865 ** larger for some devices.
26867 ** SQLite code assumes this function cannot fail. It also assumes that
26868 ** if two files are created in the same file-system directory (i.e.
26869 ** a database and its journal file) that the sector size will be the
26870 ** same for both.
26872 #ifndef __QNXNTO__
26873 static int unixSectorSize(sqlite3_file *NotUsed){
26874 UNUSED_PARAMETER(NotUsed);
26875 return SQLITE_DEFAULT_SECTOR_SIZE;
26877 #endif
26880 ** The following version of unixSectorSize() is optimized for QNX.
26882 #ifdef __QNXNTO__
26883 #include <sys/dcmd_blk.h>
26884 #include <sys/statvfs.h>
26885 static int unixSectorSize(sqlite3_file *id){
26886 unixFile *pFile = (unixFile*)id;
26887 if( pFile->sectorSize == 0 ){
26888 struct statvfs fsInfo;
26890 /* Set defaults for non-supported filesystems */
26891 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26892 pFile->deviceCharacteristics = 0;
26893 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
26894 return pFile->sectorSize;
26897 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
26898 pFile->sectorSize = fsInfo.f_bsize;
26899 pFile->deviceCharacteristics =
26900 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
26901 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
26902 ** the write succeeds */
26903 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
26904 ** so it is ordered */
26906 }else if( strstr(fsInfo.f_basetype, "etfs") ){
26907 pFile->sectorSize = fsInfo.f_bsize;
26908 pFile->deviceCharacteristics =
26909 /* etfs cluster size writes are atomic */
26910 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
26911 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
26912 ** the write succeeds */
26913 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
26914 ** so it is ordered */
26916 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
26917 pFile->sectorSize = fsInfo.f_bsize;
26918 pFile->deviceCharacteristics =
26919 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
26920 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
26921 ** the write succeeds */
26922 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
26923 ** so it is ordered */
26925 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
26926 pFile->sectorSize = fsInfo.f_bsize;
26927 pFile->deviceCharacteristics =
26928 /* full bitset of atomics from max sector size and smaller */
26929 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26930 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
26931 ** so it is ordered */
26933 }else if( strstr(fsInfo.f_basetype, "dos") ){
26934 pFile->sectorSize = fsInfo.f_bsize;
26935 pFile->deviceCharacteristics =
26936 /* full bitset of atomics from max sector size and smaller */
26937 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26938 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
26939 ** so it is ordered */
26941 }else{
26942 pFile->deviceCharacteristics =
26943 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
26944 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
26945 ** the write succeeds */
26949 /* Last chance verification. If the sector size isn't a multiple of 512
26950 ** then it isn't valid.*/
26951 if( pFile->sectorSize % 512 != 0 ){
26952 pFile->deviceCharacteristics = 0;
26953 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26955 return pFile->sectorSize;
26957 #endif /* __QNXNTO__ */
26960 ** Return the device characteristics for the file.
26962 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
26963 ** However, that choice is contraversial since technically the underlying
26964 ** file system does not always provide powersafe overwrites. (In other
26965 ** words, after a power-loss event, parts of the file that were never
26966 ** written might end up being altered.) However, non-PSOW behavior is very,
26967 ** very rare. And asserting PSOW makes a large reduction in the amount
26968 ** of required I/O for journaling, since a lot of padding is eliminated.
26969 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
26970 ** available to turn it off and URI query parameter available to turn it off.
26972 static int unixDeviceCharacteristics(sqlite3_file *id){
26973 unixFile *p = (unixFile*)id;
26974 int rc = 0;
26975 #ifdef __QNXNTO__
26976 if( p->sectorSize==0 ) unixSectorSize(id);
26977 rc = p->deviceCharacteristics;
26978 #endif
26979 if( p->ctrlFlags & UNIXFILE_PSOW ){
26980 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
26982 return rc;
26985 #ifndef SQLITE_OMIT_WAL
26989 ** Object used to represent an shared memory buffer.
26991 ** When multiple threads all reference the same wal-index, each thread
26992 ** has its own unixShm object, but they all point to a single instance
26993 ** of this unixShmNode object. In other words, each wal-index is opened
26994 ** only once per process.
26996 ** Each unixShmNode object is connected to a single unixInodeInfo object.
26997 ** We could coalesce this object into unixInodeInfo, but that would mean
26998 ** every open file that does not use shared memory (in other words, most
26999 ** open files) would have to carry around this extra information. So
27000 ** the unixInodeInfo object contains a pointer to this unixShmNode object
27001 ** and the unixShmNode object is created only when needed.
27003 ** unixMutexHeld() must be true when creating or destroying
27004 ** this object or while reading or writing the following fields:
27006 ** nRef
27008 ** The following fields are read-only after the object is created:
27010 ** fid
27011 ** zFilename
27013 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27014 ** unixMutexHeld() is true when reading or writing any other field
27015 ** in this structure.
27017 struct unixShmNode {
27018 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
27019 sqlite3_mutex *mutex; /* Mutex to access this object */
27020 char *zFilename; /* Name of the mmapped file */
27021 int h; /* Open file descriptor */
27022 int szRegion; /* Size of shared-memory regions */
27023 u16 nRegion; /* Size of array apRegion */
27024 u8 isReadonly; /* True if read-only */
27025 char **apRegion; /* Array of mapped shared-memory regions */
27026 int nRef; /* Number of unixShm objects pointing to this */
27027 unixShm *pFirst; /* All unixShm objects pointing to this */
27028 #ifdef SQLITE_DEBUG
27029 u8 exclMask; /* Mask of exclusive locks held */
27030 u8 sharedMask; /* Mask of shared locks held */
27031 u8 nextShmId; /* Next available unixShm.id value */
27032 #endif
27036 ** Structure used internally by this VFS to record the state of an
27037 ** open shared memory connection.
27039 ** The following fields are initialized when this object is created and
27040 ** are read-only thereafter:
27042 ** unixShm.pFile
27043 ** unixShm.id
27045 ** All other fields are read/write. The unixShm.pFile->mutex must be held
27046 ** while accessing any read/write fields.
27048 struct unixShm {
27049 unixShmNode *pShmNode; /* The underlying unixShmNode object */
27050 unixShm *pNext; /* Next unixShm with the same unixShmNode */
27051 u8 hasMutex; /* True if holding the unixShmNode mutex */
27052 u8 id; /* Id of this connection within its unixShmNode */
27053 u16 sharedMask; /* Mask of shared locks held */
27054 u16 exclMask; /* Mask of exclusive locks held */
27058 ** Constants used for locking
27060 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
27061 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
27064 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27066 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27067 ** otherwise.
27069 static int unixShmSystemLock(
27070 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27071 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
27072 int ofst, /* First byte of the locking range */
27073 int n /* Number of bytes to lock */
27075 struct flock f; /* The posix advisory locking structure */
27076 int rc = SQLITE_OK; /* Result code form fcntl() */
27078 /* Access to the unixShmNode object is serialized by the caller */
27079 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27081 /* Shared locks never span more than one byte */
27082 assert( n==1 || lockType!=F_RDLCK );
27084 /* Locks are within range */
27085 assert( n>=1 && n<SQLITE_SHM_NLOCK );
27087 if( pShmNode->h>=0 ){
27088 /* Initialize the locking parameters */
27089 memset(&f, 0, sizeof(f));
27090 f.l_type = lockType;
27091 f.l_whence = SEEK_SET;
27092 f.l_start = ofst;
27093 f.l_len = n;
27095 rc = osFcntl(pShmNode->h, F_SETLK, &f);
27096 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
27099 /* Update the global lock state and do debug tracing */
27100 #ifdef SQLITE_DEBUG
27101 { u16 mask;
27102 OSTRACE(("SHM-LOCK "));
27103 mask = (1<<(ofst+n)) - (1<<ofst);
27104 if( rc==SQLITE_OK ){
27105 if( lockType==F_UNLCK ){
27106 OSTRACE(("unlock %d ok", ofst));
27107 pShmNode->exclMask &= ~mask;
27108 pShmNode->sharedMask &= ~mask;
27109 }else if( lockType==F_RDLCK ){
27110 OSTRACE(("read-lock %d ok", ofst));
27111 pShmNode->exclMask &= ~mask;
27112 pShmNode->sharedMask |= mask;
27113 }else{
27114 assert( lockType==F_WRLCK );
27115 OSTRACE(("write-lock %d ok", ofst));
27116 pShmNode->exclMask |= mask;
27117 pShmNode->sharedMask &= ~mask;
27119 }else{
27120 if( lockType==F_UNLCK ){
27121 OSTRACE(("unlock %d failed", ofst));
27122 }else if( lockType==F_RDLCK ){
27123 OSTRACE(("read-lock failed"));
27124 }else{
27125 assert( lockType==F_WRLCK );
27126 OSTRACE(("write-lock %d failed", ofst));
27129 OSTRACE((" - afterwards %03x,%03x\n",
27130 pShmNode->sharedMask, pShmNode->exclMask));
27132 #endif
27134 return rc;
27139 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
27141 ** This is not a VFS shared-memory method; it is a utility function called
27142 ** by VFS shared-memory methods.
27144 static void unixShmPurge(unixFile *pFd){
27145 unixShmNode *p = pFd->pInode->pShmNode;
27146 assert( unixMutexHeld() );
27147 if( p && p->nRef==0 ){
27148 int i;
27149 assert( p->pInode==pFd->pInode );
27150 sqlite3_mutex_free(p->mutex);
27151 for(i=0; i<p->nRegion; i++){
27152 if( p->h>=0 ){
27153 osMunmap(p->apRegion[i], p->szRegion);
27154 }else{
27155 sqlite3_free(p->apRegion[i]);
27158 sqlite3_free(p->apRegion);
27159 if( p->h>=0 ){
27160 robust_close(pFd, p->h, __LINE__);
27161 p->h = -1;
27163 p->pInode->pShmNode = 0;
27164 sqlite3_free(p);
27169 ** Open a shared-memory area associated with open database file pDbFd.
27170 ** This particular implementation uses mmapped files.
27172 ** The file used to implement shared-memory is in the same directory
27173 ** as the open database file and has the same name as the open database
27174 ** file with the "-shm" suffix added. For example, if the database file
27175 ** is "/home/user1/config.db" then the file that is created and mmapped
27176 ** for shared memory will be called "/home/user1/config.db-shm".
27178 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
27179 ** some other tmpfs mount. But if a file in a different directory
27180 ** from the database file is used, then differing access permissions
27181 ** or a chroot() might cause two different processes on the same
27182 ** database to end up using different files for shared memory -
27183 ** meaning that their memory would not really be shared - resulting
27184 ** in database corruption. Nevertheless, this tmpfs file usage
27185 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
27186 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
27187 ** option results in an incompatible build of SQLite; builds of SQLite
27188 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
27189 ** same database file at the same time, database corruption will likely
27190 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
27191 ** "unsupported" and may go away in a future SQLite release.
27193 ** When opening a new shared-memory file, if no other instances of that
27194 ** file are currently open, in this process or in other processes, then
27195 ** the file must be truncated to zero length or have its header cleared.
27197 ** If the original database file (pDbFd) is using the "unix-excl" VFS
27198 ** that means that an exclusive lock is held on the database file and
27199 ** that no other processes are able to read or write the database. In
27200 ** that case, we do not really need shared memory. No shared memory
27201 ** file is created. The shared memory will be simulated with heap memory.
27203 static int unixOpenSharedMemory(unixFile *pDbFd){
27204 struct unixShm *p = 0; /* The connection to be opened */
27205 struct unixShmNode *pShmNode; /* The underlying mmapped file */
27206 int rc; /* Result code */
27207 unixInodeInfo *pInode; /* The inode of fd */
27208 char *zShmFilename; /* Name of the file used for SHM */
27209 int nShmFilename; /* Size of the SHM filename in bytes */
27211 /* Allocate space for the new unixShm object. */
27212 p = sqlite3_malloc( sizeof(*p) );
27213 if( p==0 ) return SQLITE_NOMEM;
27214 memset(p, 0, sizeof(*p));
27215 assert( pDbFd->pShm==0 );
27217 /* Check to see if a unixShmNode object already exists. Reuse an existing
27218 ** one if present. Create a new one if necessary.
27220 unixEnterMutex();
27221 pInode = pDbFd->pInode;
27222 pShmNode = pInode->pShmNode;
27223 if( pShmNode==0 ){
27224 struct stat sStat; /* fstat() info for database file */
27226 /* Call fstat() to figure out the permissions on the database file. If
27227 ** a new *-shm file is created, an attempt will be made to create it
27228 ** with the same permissions.
27230 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
27231 rc = SQLITE_IOERR_FSTAT;
27232 goto shm_open_err;
27235 #ifdef SQLITE_SHM_DIRECTORY
27236 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
27237 #else
27238 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
27239 #endif
27240 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
27241 if( pShmNode==0 ){
27242 rc = SQLITE_NOMEM;
27243 goto shm_open_err;
27245 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
27246 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
27247 #ifdef SQLITE_SHM_DIRECTORY
27248 sqlite3_snprintf(nShmFilename, zShmFilename,
27249 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
27250 (u32)sStat.st_ino, (u32)sStat.st_dev);
27251 #else
27252 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
27253 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
27254 #endif
27255 pShmNode->h = -1;
27256 pDbFd->pInode->pShmNode = pShmNode;
27257 pShmNode->pInode = pDbFd->pInode;
27258 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27259 if( pShmNode->mutex==0 ){
27260 rc = SQLITE_NOMEM;
27261 goto shm_open_err;
27264 if( pInode->bProcessLock==0 ){
27265 int openFlags = O_RDWR | O_CREAT;
27266 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
27267 openFlags = O_RDONLY;
27268 pShmNode->isReadonly = 1;
27270 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
27271 if( pShmNode->h<0 ){
27272 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
27273 goto shm_open_err;
27276 /* If this process is running as root, make sure that the SHM file
27277 ** is owned by the same user that owns the original database. Otherwise,
27278 ** the original owner will not be able to connect.
27280 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
27282 /* Check to see if another process is holding the dead-man switch.
27283 ** If not, truncate the file to zero length.
27285 rc = SQLITE_OK;
27286 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27287 if( robust_ftruncate(pShmNode->h, 0) ){
27288 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27291 if( rc==SQLITE_OK ){
27292 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27294 if( rc ) goto shm_open_err;
27298 /* Make the new connection a child of the unixShmNode */
27299 p->pShmNode = pShmNode;
27300 #ifdef SQLITE_DEBUG
27301 p->id = pShmNode->nextShmId++;
27302 #endif
27303 pShmNode->nRef++;
27304 pDbFd->pShm = p;
27305 unixLeaveMutex();
27307 /* The reference count on pShmNode has already been incremented under
27308 ** the cover of the unixEnterMutex() mutex and the pointer from the
27309 ** new (struct unixShm) object to the pShmNode has been set. All that is
27310 ** left to do is to link the new object into the linked list starting
27311 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
27312 ** mutex.
27314 sqlite3_mutex_enter(pShmNode->mutex);
27315 p->pNext = pShmNode->pFirst;
27316 pShmNode->pFirst = p;
27317 sqlite3_mutex_leave(pShmNode->mutex);
27318 return SQLITE_OK;
27320 /* Jump here on any error */
27321 shm_open_err:
27322 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
27323 sqlite3_free(p);
27324 unixLeaveMutex();
27325 return rc;
27329 ** This function is called to obtain a pointer to region iRegion of the
27330 ** shared-memory associated with the database file fd. Shared-memory regions
27331 ** are numbered starting from zero. Each shared-memory region is szRegion
27332 ** bytes in size.
27334 ** If an error occurs, an error code is returned and *pp is set to NULL.
27336 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
27337 ** region has not been allocated (by any client, including one running in a
27338 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
27339 ** bExtend is non-zero and the requested shared-memory region has not yet
27340 ** been allocated, it is allocated by this function.
27342 ** If the shared-memory region has already been allocated or is allocated by
27343 ** this call as described above, then it is mapped into this processes
27344 ** address space (if it is not already), *pp is set to point to the mapped
27345 ** memory and SQLITE_OK returned.
27347 static int unixShmMap(
27348 sqlite3_file *fd, /* Handle open on database file */
27349 int iRegion, /* Region to retrieve */
27350 int szRegion, /* Size of regions */
27351 int bExtend, /* True to extend file if necessary */
27352 void volatile **pp /* OUT: Mapped memory */
27354 unixFile *pDbFd = (unixFile*)fd;
27355 unixShm *p;
27356 unixShmNode *pShmNode;
27357 int rc = SQLITE_OK;
27359 /* If the shared-memory file has not yet been opened, open it now. */
27360 if( pDbFd->pShm==0 ){
27361 rc = unixOpenSharedMemory(pDbFd);
27362 if( rc!=SQLITE_OK ) return rc;
27365 p = pDbFd->pShm;
27366 pShmNode = p->pShmNode;
27367 sqlite3_mutex_enter(pShmNode->mutex);
27368 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
27369 assert( pShmNode->pInode==pDbFd->pInode );
27370 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27371 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27373 if( pShmNode->nRegion<=iRegion ){
27374 char **apNew; /* New apRegion[] array */
27375 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
27376 struct stat sStat; /* Used by fstat() */
27378 pShmNode->szRegion = szRegion;
27380 if( pShmNode->h>=0 ){
27381 /* The requested region is not mapped into this processes address space.
27382 ** Check to see if it has been allocated (i.e. if the wal-index file is
27383 ** large enough to contain the requested region).
27385 if( osFstat(pShmNode->h, &sStat) ){
27386 rc = SQLITE_IOERR_SHMSIZE;
27387 goto shmpage_out;
27390 if( sStat.st_size<nByte ){
27391 /* The requested memory region does not exist. If bExtend is set to
27392 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
27394 if( !bExtend ){
27395 goto shmpage_out;
27398 /* Alternatively, if bExtend is true, extend the file. Do this by
27399 ** writing a single byte to the end of each (OS) page being
27400 ** allocated or extended. Technically, we need only write to the
27401 ** last page in order to extend the file. But writing to all new
27402 ** pages forces the OS to allocate them immediately, which reduces
27403 ** the chances of SIGBUS while accessing the mapped region later on.
27405 else{
27406 static const int pgsz = 4096;
27407 int iPg;
27409 /* Write to the last byte of each newly allocated or extended page */
27410 assert( (nByte % pgsz)==0 );
27411 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
27412 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
27413 const char *zFile = pShmNode->zFilename;
27414 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
27415 goto shmpage_out;
27422 /* Map the requested memory region into this processes address space. */
27423 apNew = (char **)sqlite3_realloc(
27424 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
27426 if( !apNew ){
27427 rc = SQLITE_IOERR_NOMEM;
27428 goto shmpage_out;
27430 pShmNode->apRegion = apNew;
27431 while(pShmNode->nRegion<=iRegion){
27432 void *pMem;
27433 if( pShmNode->h>=0 ){
27434 pMem = osMmap(0, szRegion,
27435 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
27436 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
27438 if( pMem==MAP_FAILED ){
27439 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
27440 goto shmpage_out;
27442 }else{
27443 pMem = sqlite3_malloc(szRegion);
27444 if( pMem==0 ){
27445 rc = SQLITE_NOMEM;
27446 goto shmpage_out;
27448 memset(pMem, 0, szRegion);
27450 pShmNode->apRegion[pShmNode->nRegion] = pMem;
27451 pShmNode->nRegion++;
27455 shmpage_out:
27456 if( pShmNode->nRegion>iRegion ){
27457 *pp = pShmNode->apRegion[iRegion];
27458 }else{
27459 *pp = 0;
27461 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
27462 sqlite3_mutex_leave(pShmNode->mutex);
27463 return rc;
27467 ** Change the lock state for a shared-memory segment.
27469 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
27470 ** different here than in posix. In xShmLock(), one can go from unlocked
27471 ** to shared and back or from unlocked to exclusive and back. But one may
27472 ** not go from shared to exclusive or from exclusive to shared.
27474 static int unixShmLock(
27475 sqlite3_file *fd, /* Database file holding the shared memory */
27476 int ofst, /* First lock to acquire or release */
27477 int n, /* Number of locks to acquire or release */
27478 int flags /* What to do with the lock */
27480 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
27481 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
27482 unixShm *pX; /* For looping over all siblings */
27483 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
27484 int rc = SQLITE_OK; /* Result code */
27485 u16 mask; /* Mask of locks to take or release */
27487 assert( pShmNode==pDbFd->pInode->pShmNode );
27488 assert( pShmNode->pInode==pDbFd->pInode );
27489 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
27490 assert( n>=1 );
27491 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
27492 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
27493 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
27494 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
27495 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
27496 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27497 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27499 mask = (1<<(ofst+n)) - (1<<ofst);
27500 assert( n>1 || mask==(1<<ofst) );
27501 sqlite3_mutex_enter(pShmNode->mutex);
27502 if( flags & SQLITE_SHM_UNLOCK ){
27503 u16 allMask = 0; /* Mask of locks held by siblings */
27505 /* See if any siblings hold this same lock */
27506 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27507 if( pX==p ) continue;
27508 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
27509 allMask |= pX->sharedMask;
27512 /* Unlock the system-level locks */
27513 if( (mask & allMask)==0 ){
27514 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
27515 }else{
27516 rc = SQLITE_OK;
27519 /* Undo the local locks */
27520 if( rc==SQLITE_OK ){
27521 p->exclMask &= ~mask;
27522 p->sharedMask &= ~mask;
27524 }else if( flags & SQLITE_SHM_SHARED ){
27525 u16 allShared = 0; /* Union of locks held by connections other than "p" */
27527 /* Find out which shared locks are already held by sibling connections.
27528 ** If any sibling already holds an exclusive lock, go ahead and return
27529 ** SQLITE_BUSY.
27531 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27532 if( (pX->exclMask & mask)!=0 ){
27533 rc = SQLITE_BUSY;
27534 break;
27536 allShared |= pX->sharedMask;
27539 /* Get shared locks at the system level, if necessary */
27540 if( rc==SQLITE_OK ){
27541 if( (allShared & mask)==0 ){
27542 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
27543 }else{
27544 rc = SQLITE_OK;
27548 /* Get the local shared locks */
27549 if( rc==SQLITE_OK ){
27550 p->sharedMask |= mask;
27552 }else{
27553 /* Make sure no sibling connections hold locks that will block this
27554 ** lock. If any do, return SQLITE_BUSY right away.
27556 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27557 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
27558 rc = SQLITE_BUSY;
27559 break;
27563 /* Get the exclusive locks at the system level. Then if successful
27564 ** also mark the local connection as being locked.
27566 if( rc==SQLITE_OK ){
27567 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
27568 if( rc==SQLITE_OK ){
27569 assert( (p->sharedMask & mask)==0 );
27570 p->exclMask |= mask;
27574 sqlite3_mutex_leave(pShmNode->mutex);
27575 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
27576 p->id, getpid(), p->sharedMask, p->exclMask));
27577 return rc;
27581 ** Implement a memory barrier or memory fence on shared memory.
27583 ** All loads and stores begun before the barrier must complete before
27584 ** any load or store begun after the barrier.
27586 static void unixShmBarrier(
27587 sqlite3_file *fd /* Database file holding the shared memory */
27589 UNUSED_PARAMETER(fd);
27590 unixEnterMutex();
27591 unixLeaveMutex();
27595 ** Close a connection to shared-memory. Delete the underlying
27596 ** storage if deleteFlag is true.
27598 ** If there is no shared memory associated with the connection then this
27599 ** routine is a harmless no-op.
27601 static int unixShmUnmap(
27602 sqlite3_file *fd, /* The underlying database file */
27603 int deleteFlag /* Delete shared-memory if true */
27605 unixShm *p; /* The connection to be closed */
27606 unixShmNode *pShmNode; /* The underlying shared-memory file */
27607 unixShm **pp; /* For looping over sibling connections */
27608 unixFile *pDbFd; /* The underlying database file */
27610 pDbFd = (unixFile*)fd;
27611 p = pDbFd->pShm;
27612 if( p==0 ) return SQLITE_OK;
27613 pShmNode = p->pShmNode;
27615 assert( pShmNode==pDbFd->pInode->pShmNode );
27616 assert( pShmNode->pInode==pDbFd->pInode );
27618 /* Remove connection p from the set of connections associated
27619 ** with pShmNode */
27620 sqlite3_mutex_enter(pShmNode->mutex);
27621 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
27622 *pp = p->pNext;
27624 /* Free the connection p */
27625 sqlite3_free(p);
27626 pDbFd->pShm = 0;
27627 sqlite3_mutex_leave(pShmNode->mutex);
27629 /* If pShmNode->nRef has reached 0, then close the underlying
27630 ** shared-memory file, too */
27631 unixEnterMutex();
27632 assert( pShmNode->nRef>0 );
27633 pShmNode->nRef--;
27634 if( pShmNode->nRef==0 ){
27635 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
27636 unixShmPurge(pDbFd);
27638 unixLeaveMutex();
27640 return SQLITE_OK;
27644 #else
27645 # define unixShmMap 0
27646 # define unixShmLock 0
27647 # define unixShmBarrier 0
27648 # define unixShmUnmap 0
27649 #endif /* #ifndef SQLITE_OMIT_WAL */
27652 ** If it is currently memory mapped, unmap file pFd.
27654 static void unixUnmapfile(unixFile *pFd){
27655 assert( pFd->nFetchOut==0 );
27656 #if SQLITE_MAX_MMAP_SIZE>0
27657 if( pFd->pMapRegion ){
27658 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
27659 pFd->pMapRegion = 0;
27660 pFd->mmapSize = 0;
27661 pFd->mmapSizeActual = 0;
27663 #endif
27666 #if SQLITE_MAX_MMAP_SIZE>0
27668 ** Return the system page size.
27670 static int unixGetPagesize(void){
27671 #if HAVE_MREMAP
27672 return 512;
27673 #elif defined(_BSD_SOURCE)
27674 return getpagesize();
27675 #else
27676 return (int)sysconf(_SC_PAGESIZE);
27677 #endif
27679 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
27681 #if SQLITE_MAX_MMAP_SIZE>0
27683 ** Attempt to set the size of the memory mapping maintained by file
27684 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
27686 ** If successful, this function sets the following variables:
27688 ** unixFile.pMapRegion
27689 ** unixFile.mmapSize
27690 ** unixFile.mmapSizeActual
27692 ** If unsuccessful, an error message is logged via sqlite3_log() and
27693 ** the three variables above are zeroed. In this case SQLite should
27694 ** continue accessing the database using the xRead() and xWrite()
27695 ** methods.
27697 static void unixRemapfile(
27698 unixFile *pFd, /* File descriptor object */
27699 i64 nNew /* Required mapping size */
27701 const char *zErr = "mmap";
27702 int h = pFd->h; /* File descriptor open on db file */
27703 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
27704 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
27705 u8 *pNew = 0; /* Location of new mapping */
27706 int flags = PROT_READ; /* Flags to pass to mmap() */
27708 assert( pFd->nFetchOut==0 );
27709 assert( nNew>pFd->mmapSize );
27710 assert( nNew<=pFd->mmapSizeMax );
27711 assert( nNew>0 );
27712 assert( pFd->mmapSizeActual>=pFd->mmapSize );
27713 assert( MAP_FAILED!=0 );
27715 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
27717 if( pOrig ){
27718 const int szSyspage = unixGetPagesize();
27719 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
27720 u8 *pReq = &pOrig[nReuse];
27722 /* Unmap any pages of the existing mapping that cannot be reused. */
27723 if( nReuse!=nOrig ){
27724 osMunmap(pReq, nOrig-nReuse);
27727 #if HAVE_MREMAP
27728 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
27729 zErr = "mremap";
27730 #else
27731 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
27732 if( pNew!=MAP_FAILED ){
27733 if( pNew!=pReq ){
27734 osMunmap(pNew, nNew - nReuse);
27735 pNew = 0;
27736 }else{
27737 pNew = pOrig;
27740 #endif
27742 /* The attempt to extend the existing mapping failed. Free it. */
27743 if( pNew==MAP_FAILED || pNew==0 ){
27744 osMunmap(pOrig, nReuse);
27748 /* If pNew is still NULL, try to create an entirely new mapping. */
27749 if( pNew==0 ){
27750 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
27753 if( pNew==MAP_FAILED ){
27754 pNew = 0;
27755 nNew = 0;
27756 unixLogError(SQLITE_OK, zErr, pFd->zPath);
27758 /* If the mmap() above failed, assume that all subsequent mmap() calls
27759 ** will probably fail too. Fall back to using xRead/xWrite exclusively
27760 ** in this case. */
27761 pFd->mmapSizeMax = 0;
27763 pFd->pMapRegion = (void *)pNew;
27764 pFd->mmapSize = pFd->mmapSizeActual = nNew;
27766 #endif
27769 ** Memory map or remap the file opened by file-descriptor pFd (if the file
27770 ** is already mapped, the existing mapping is replaced by the new). Or, if
27771 ** there already exists a mapping for this file, and there are still
27772 ** outstanding xFetch() references to it, this function is a no-op.
27774 ** If parameter nByte is non-negative, then it is the requested size of
27775 ** the mapping to create. Otherwise, if nByte is less than zero, then the
27776 ** requested size is the size of the file on disk. The actual size of the
27777 ** created mapping is either the requested size or the value configured
27778 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
27780 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
27781 ** recreated as a result of outstanding references) or an SQLite error
27782 ** code otherwise.
27784 static int unixMapfile(unixFile *pFd, i64 nByte){
27785 #if SQLITE_MAX_MMAP_SIZE>0
27786 i64 nMap = nByte;
27787 int rc;
27789 assert( nMap>=0 || pFd->nFetchOut==0 );
27790 if( pFd->nFetchOut>0 ) return SQLITE_OK;
27792 if( nMap<0 ){
27793 struct stat statbuf; /* Low-level file information */
27794 rc = osFstat(pFd->h, &statbuf);
27795 if( rc!=SQLITE_OK ){
27796 return SQLITE_IOERR_FSTAT;
27798 nMap = statbuf.st_size;
27800 if( nMap>pFd->mmapSizeMax ){
27801 nMap = pFd->mmapSizeMax;
27804 if( nMap!=pFd->mmapSize ){
27805 if( nMap>0 ){
27806 unixRemapfile(pFd, nMap);
27807 }else{
27808 unixUnmapfile(pFd);
27811 #endif
27813 return SQLITE_OK;
27817 ** If possible, return a pointer to a mapping of file fd starting at offset
27818 ** iOff. The mapping must be valid for at least nAmt bytes.
27820 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
27821 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
27822 ** Finally, if an error does occur, return an SQLite error code. The final
27823 ** value of *pp is undefined in this case.
27825 ** If this function does return a pointer, the caller must eventually
27826 ** release the reference by calling unixUnfetch().
27828 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
27829 #if SQLITE_MAX_MMAP_SIZE>0
27830 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
27831 #endif
27832 *pp = 0;
27834 #if SQLITE_MAX_MMAP_SIZE>0
27835 if( pFd->mmapSizeMax>0 ){
27836 if( pFd->pMapRegion==0 ){
27837 int rc = unixMapfile(pFd, -1);
27838 if( rc!=SQLITE_OK ) return rc;
27840 if( pFd->mmapSize >= iOff+nAmt ){
27841 *pp = &((u8 *)pFd->pMapRegion)[iOff];
27842 pFd->nFetchOut++;
27845 #endif
27846 return SQLITE_OK;
27850 ** If the third argument is non-NULL, then this function releases a
27851 ** reference obtained by an earlier call to unixFetch(). The second
27852 ** argument passed to this function must be the same as the corresponding
27853 ** argument that was passed to the unixFetch() invocation.
27855 ** Or, if the third argument is NULL, then this function is being called
27856 ** to inform the VFS layer that, according to POSIX, any existing mapping
27857 ** may now be invalid and should be unmapped.
27859 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
27860 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
27861 UNUSED_PARAMETER(iOff);
27863 /* If p==0 (unmap the entire file) then there must be no outstanding
27864 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
27865 ** then there must be at least one outstanding. */
27866 assert( (p==0)==(pFd->nFetchOut==0) );
27868 /* If p!=0, it must match the iOff value. */
27869 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
27871 if( p ){
27872 pFd->nFetchOut--;
27873 }else{
27874 unixUnmapfile(pFd);
27877 assert( pFd->nFetchOut>=0 );
27878 return SQLITE_OK;
27882 ** Here ends the implementation of all sqlite3_file methods.
27884 ********************** End sqlite3_file Methods *******************************
27885 ******************************************************************************/
27888 ** This division contains definitions of sqlite3_io_methods objects that
27889 ** implement various file locking strategies. It also contains definitions
27890 ** of "finder" functions. A finder-function is used to locate the appropriate
27891 ** sqlite3_io_methods object for a particular database file. The pAppData
27892 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
27893 ** the correct finder-function for that VFS.
27895 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
27896 ** object. The only interesting finder-function is autolockIoFinder, which
27897 ** looks at the filesystem type and tries to guess the best locking
27898 ** strategy from that.
27900 ** For finder-funtion F, two objects are created:
27902 ** (1) The real finder-function named "FImpt()".
27904 ** (2) A constant pointer to this function named just "F".
27907 ** A pointer to the F pointer is used as the pAppData value for VFS
27908 ** objects. We have to do this instead of letting pAppData point
27909 ** directly at the finder-function since C90 rules prevent a void*
27910 ** from be cast into a function pointer.
27913 ** Each instance of this macro generates two objects:
27915 ** * A constant sqlite3_io_methods object call METHOD that has locking
27916 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
27918 ** * An I/O method finder function called FINDER that returns a pointer
27919 ** to the METHOD object in the previous bullet.
27921 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
27922 static const sqlite3_io_methods METHOD = { \
27923 VERSION, /* iVersion */ \
27924 CLOSE, /* xClose */ \
27925 unixRead, /* xRead */ \
27926 unixWrite, /* xWrite */ \
27927 unixTruncate, /* xTruncate */ \
27928 unixSync, /* xSync */ \
27929 unixFileSize, /* xFileSize */ \
27930 LOCK, /* xLock */ \
27931 UNLOCK, /* xUnlock */ \
27932 CKLOCK, /* xCheckReservedLock */ \
27933 unixFileControl, /* xFileControl */ \
27934 unixSectorSize, /* xSectorSize */ \
27935 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
27936 unixShmMap, /* xShmMap */ \
27937 unixShmLock, /* xShmLock */ \
27938 unixShmBarrier, /* xShmBarrier */ \
27939 unixShmUnmap, /* xShmUnmap */ \
27940 unixFetch, /* xFetch */ \
27941 unixUnfetch, /* xUnfetch */ \
27942 }; \
27943 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
27944 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
27945 return &METHOD; \
27947 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
27948 = FINDER##Impl;
27951 ** Here are all of the sqlite3_io_methods objects for each of the
27952 ** locking strategies. Functions that return pointers to these methods
27953 ** are also created.
27955 IOMETHODS(
27956 posixIoFinder, /* Finder function name */
27957 posixIoMethods, /* sqlite3_io_methods object name */
27958 3, /* shared memory and mmap are enabled */
27959 unixClose, /* xClose method */
27960 unixLock, /* xLock method */
27961 unixUnlock, /* xUnlock method */
27962 unixCheckReservedLock /* xCheckReservedLock method */
27964 IOMETHODS(
27965 nolockIoFinder, /* Finder function name */
27966 nolockIoMethods, /* sqlite3_io_methods object name */
27967 1, /* shared memory is disabled */
27968 nolockClose, /* xClose method */
27969 nolockLock, /* xLock method */
27970 nolockUnlock, /* xUnlock method */
27971 nolockCheckReservedLock /* xCheckReservedLock method */
27973 IOMETHODS(
27974 dotlockIoFinder, /* Finder function name */
27975 dotlockIoMethods, /* sqlite3_io_methods object name */
27976 1, /* shared memory is disabled */
27977 dotlockClose, /* xClose method */
27978 dotlockLock, /* xLock method */
27979 dotlockUnlock, /* xUnlock method */
27980 dotlockCheckReservedLock /* xCheckReservedLock method */
27983 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27984 IOMETHODS(
27985 flockIoFinder, /* Finder function name */
27986 flockIoMethods, /* sqlite3_io_methods object name */
27987 1, /* shared memory is disabled */
27988 flockClose, /* xClose method */
27989 flockLock, /* xLock method */
27990 flockUnlock, /* xUnlock method */
27991 flockCheckReservedLock /* xCheckReservedLock method */
27993 #endif
27995 #if OS_VXWORKS
27996 IOMETHODS(
27997 semIoFinder, /* Finder function name */
27998 semIoMethods, /* sqlite3_io_methods object name */
27999 1, /* shared memory is disabled */
28000 semClose, /* xClose method */
28001 semLock, /* xLock method */
28002 semUnlock, /* xUnlock method */
28003 semCheckReservedLock /* xCheckReservedLock method */
28005 #endif
28007 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28008 IOMETHODS(
28009 afpIoFinder, /* Finder function name */
28010 afpIoMethods, /* sqlite3_io_methods object name */
28011 1, /* shared memory is disabled */
28012 afpClose, /* xClose method */
28013 afpLock, /* xLock method */
28014 afpUnlock, /* xUnlock method */
28015 afpCheckReservedLock /* xCheckReservedLock method */
28017 #endif
28020 ** The proxy locking method is a "super-method" in the sense that it
28021 ** opens secondary file descriptors for the conch and lock files and
28022 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28023 ** secondary files. For this reason, the division that implements
28024 ** proxy locking is located much further down in the file. But we need
28025 ** to go ahead and define the sqlite3_io_methods and finder function
28026 ** for proxy locking here. So we forward declare the I/O methods.
28028 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28029 static int proxyClose(sqlite3_file*);
28030 static int proxyLock(sqlite3_file*, int);
28031 static int proxyUnlock(sqlite3_file*, int);
28032 static int proxyCheckReservedLock(sqlite3_file*, int*);
28033 IOMETHODS(
28034 proxyIoFinder, /* Finder function name */
28035 proxyIoMethods, /* sqlite3_io_methods object name */
28036 1, /* shared memory is disabled */
28037 proxyClose, /* xClose method */
28038 proxyLock, /* xLock method */
28039 proxyUnlock, /* xUnlock method */
28040 proxyCheckReservedLock /* xCheckReservedLock method */
28042 #endif
28044 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28045 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28046 IOMETHODS(
28047 nfsIoFinder, /* Finder function name */
28048 nfsIoMethods, /* sqlite3_io_methods object name */
28049 1, /* shared memory is disabled */
28050 unixClose, /* xClose method */
28051 unixLock, /* xLock method */
28052 nfsUnlock, /* xUnlock method */
28053 unixCheckReservedLock /* xCheckReservedLock method */
28055 #endif
28057 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28059 ** This "finder" function attempts to determine the best locking strategy
28060 ** for the database file "filePath". It then returns the sqlite3_io_methods
28061 ** object that implements that strategy.
28063 ** This is for MacOSX only.
28065 static const sqlite3_io_methods *autolockIoFinderImpl(
28066 const char *filePath, /* name of the database file */
28067 unixFile *pNew /* open file object for the database file */
28069 static const struct Mapping {
28070 const char *zFilesystem; /* Filesystem type name */
28071 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
28072 } aMap[] = {
28073 { "hfs", &posixIoMethods },
28074 { "ufs", &posixIoMethods },
28075 { "afpfs", &afpIoMethods },
28076 { "smbfs", &afpIoMethods },
28077 { "webdav", &nolockIoMethods },
28078 { 0, 0 }
28080 int i;
28081 struct statfs fsInfo;
28082 struct flock lockInfo;
28084 if( !filePath ){
28085 /* If filePath==NULL that means we are dealing with a transient file
28086 ** that does not need to be locked. */
28087 return &nolockIoMethods;
28089 if( statfs(filePath, &fsInfo) != -1 ){
28090 if( fsInfo.f_flags & MNT_RDONLY ){
28091 return &nolockIoMethods;
28093 for(i=0; aMap[i].zFilesystem; i++){
28094 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28095 return aMap[i].pMethods;
28100 /* Default case. Handles, amongst others, "nfs".
28101 ** Test byte-range lock using fcntl(). If the call succeeds,
28102 ** assume that the file-system supports POSIX style locks.
28104 lockInfo.l_len = 1;
28105 lockInfo.l_start = 0;
28106 lockInfo.l_whence = SEEK_SET;
28107 lockInfo.l_type = F_RDLCK;
28108 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28109 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28110 return &nfsIoMethods;
28111 } else {
28112 return &posixIoMethods;
28114 }else{
28115 return &dotlockIoMethods;
28118 static const sqlite3_io_methods
28119 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28121 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28123 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28125 ** This "finder" function attempts to determine the best locking strategy
28126 ** for the database file "filePath". It then returns the sqlite3_io_methods
28127 ** object that implements that strategy.
28129 ** This is for VXWorks only.
28131 static const sqlite3_io_methods *autolockIoFinderImpl(
28132 const char *filePath, /* name of the database file */
28133 unixFile *pNew /* the open file object */
28135 struct flock lockInfo;
28137 if( !filePath ){
28138 /* If filePath==NULL that means we are dealing with a transient file
28139 ** that does not need to be locked. */
28140 return &nolockIoMethods;
28143 /* Test if fcntl() is supported and use POSIX style locks.
28144 ** Otherwise fall back to the named semaphore method.
28146 lockInfo.l_len = 1;
28147 lockInfo.l_start = 0;
28148 lockInfo.l_whence = SEEK_SET;
28149 lockInfo.l_type = F_RDLCK;
28150 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28151 return &posixIoMethods;
28152 }else{
28153 return &semIoMethods;
28156 static const sqlite3_io_methods
28157 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28159 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28162 ** An abstract type for a pointer to a IO method finder function:
28164 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28167 /****************************************************************************
28168 **************************** sqlite3_vfs methods ****************************
28170 ** This division contains the implementation of methods on the
28171 ** sqlite3_vfs object.
28175 ** Initialize the contents of the unixFile structure pointed to by pId.
28177 static int fillInUnixFile(
28178 sqlite3_vfs *pVfs, /* Pointer to vfs object */
28179 int h, /* Open file descriptor of file being opened */
28180 sqlite3_file *pId, /* Write to the unixFile structure here */
28181 const char *zFilename, /* Name of the file being opened */
28182 int ctrlFlags /* Zero or more UNIXFILE_* values */
28184 const sqlite3_io_methods *pLockingStyle;
28185 unixFile *pNew = (unixFile *)pId;
28186 int rc = SQLITE_OK;
28188 assert( pNew->pInode==NULL );
28190 /* Usually the path zFilename should not be a relative pathname. The
28191 ** exception is when opening the proxy "conch" file in builds that
28192 ** include the special Apple locking styles.
28194 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28195 assert( zFilename==0 || zFilename[0]=='/'
28196 || pVfs->pAppData==(void*)&autolockIoFinder );
28197 #else
28198 assert( zFilename==0 || zFilename[0]=='/' );
28199 #endif
28201 /* No locking occurs in temporary files */
28202 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
28204 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
28205 pNew->h = h;
28206 pNew->pVfs = pVfs;
28207 pNew->zPath = zFilename;
28208 pNew->ctrlFlags = (u8)ctrlFlags;
28209 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
28210 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
28211 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
28212 pNew->ctrlFlags |= UNIXFILE_PSOW;
28214 if( strcmp(pVfs->zName,"unix-excl")==0 ){
28215 pNew->ctrlFlags |= UNIXFILE_EXCL;
28218 #if OS_VXWORKS
28219 pNew->pId = vxworksFindFileId(zFilename);
28220 if( pNew->pId==0 ){
28221 ctrlFlags |= UNIXFILE_NOLOCK;
28222 rc = SQLITE_NOMEM;
28224 #endif
28226 if( ctrlFlags & UNIXFILE_NOLOCK ){
28227 pLockingStyle = &nolockIoMethods;
28228 }else{
28229 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28230 #if SQLITE_ENABLE_LOCKING_STYLE
28231 /* Cache zFilename in the locking context (AFP and dotlock override) for
28232 ** proxyLock activation is possible (remote proxy is based on db name)
28233 ** zFilename remains valid until file is closed, to support */
28234 pNew->lockingContext = (void*)zFilename;
28235 #endif
28238 if( pLockingStyle == &posixIoMethods
28239 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28240 || pLockingStyle == &nfsIoMethods
28241 #endif
28243 unixEnterMutex();
28244 rc = findInodeInfo(pNew, &pNew->pInode);
28245 if( rc!=SQLITE_OK ){
28246 /* If an error occurred in findInodeInfo(), close the file descriptor
28247 ** immediately, before releasing the mutex. findInodeInfo() may fail
28248 ** in two scenarios:
28250 ** (a) A call to fstat() failed.
28251 ** (b) A malloc failed.
28253 ** Scenario (b) may only occur if the process is holding no other
28254 ** file descriptors open on the same file. If there were other file
28255 ** descriptors on this file, then no malloc would be required by
28256 ** findInodeInfo(). If this is the case, it is quite safe to close
28257 ** handle h - as it is guaranteed that no posix locks will be released
28258 ** by doing so.
28260 ** If scenario (a) caused the error then things are not so safe. The
28261 ** implicit assumption here is that if fstat() fails, things are in
28262 ** such bad shape that dropping a lock or two doesn't matter much.
28264 robust_close(pNew, h, __LINE__);
28265 h = -1;
28267 unixLeaveMutex();
28270 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28271 else if( pLockingStyle == &afpIoMethods ){
28272 /* AFP locking uses the file path so it needs to be included in
28273 ** the afpLockingContext.
28275 afpLockingContext *pCtx;
28276 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
28277 if( pCtx==0 ){
28278 rc = SQLITE_NOMEM;
28279 }else{
28280 /* NB: zFilename exists and remains valid until the file is closed
28281 ** according to requirement F11141. So we do not need to make a
28282 ** copy of the filename. */
28283 pCtx->dbPath = zFilename;
28284 pCtx->reserved = 0;
28285 srandomdev();
28286 unixEnterMutex();
28287 rc = findInodeInfo(pNew, &pNew->pInode);
28288 if( rc!=SQLITE_OK ){
28289 sqlite3_free(pNew->lockingContext);
28290 robust_close(pNew, h, __LINE__);
28291 h = -1;
28293 unixLeaveMutex();
28296 #endif
28298 else if( pLockingStyle == &dotlockIoMethods ){
28299 /* Dotfile locking uses the file path so it needs to be included in
28300 ** the dotlockLockingContext
28302 char *zLockFile;
28303 int nFilename;
28304 assert( zFilename!=0 );
28305 nFilename = (int)strlen(zFilename) + 6;
28306 zLockFile = (char *)sqlite3_malloc(nFilename);
28307 if( zLockFile==0 ){
28308 rc = SQLITE_NOMEM;
28309 }else{
28310 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
28312 pNew->lockingContext = zLockFile;
28315 #if OS_VXWORKS
28316 else if( pLockingStyle == &semIoMethods ){
28317 /* Named semaphore locking uses the file path so it needs to be
28318 ** included in the semLockingContext
28320 unixEnterMutex();
28321 rc = findInodeInfo(pNew, &pNew->pInode);
28322 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
28323 char *zSemName = pNew->pInode->aSemName;
28324 int n;
28325 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
28326 pNew->pId->zCanonicalName);
28327 for( n=1; zSemName[n]; n++ )
28328 if( zSemName[n]=='/' ) zSemName[n] = '_';
28329 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
28330 if( pNew->pInode->pSem == SEM_FAILED ){
28331 rc = SQLITE_NOMEM;
28332 pNew->pInode->aSemName[0] = '\0';
28335 unixLeaveMutex();
28337 #endif
28339 pNew->lastErrno = 0;
28340 #if OS_VXWORKS
28341 if( rc!=SQLITE_OK ){
28342 if( h>=0 ) robust_close(pNew, h, __LINE__);
28343 h = -1;
28344 osUnlink(zFilename);
28345 pNew->ctrlFlags |= UNIXFILE_DELETE;
28347 #endif
28348 if( rc!=SQLITE_OK ){
28349 if( h>=0 ) robust_close(pNew, h, __LINE__);
28350 }else{
28351 pNew->pMethod = pLockingStyle;
28352 OpenCounter(+1);
28353 verifyDbFile(pNew);
28355 return rc;
28359 ** Return the name of a directory in which to put temporary files.
28360 ** If no suitable temporary file directory can be found, return NULL.
28362 static const char *unixTempFileDir(void){
28363 static const char *azDirs[] = {
28366 "/var/tmp",
28367 "/usr/tmp",
28368 "/tmp",
28369 0 /* List terminator */
28371 unsigned int i;
28372 struct stat buf;
28373 const char *zDir = 0;
28375 azDirs[0] = sqlite3_temp_directory;
28376 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
28377 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
28378 if( zDir==0 ) continue;
28379 if( osStat(zDir, &buf) ) continue;
28380 if( !S_ISDIR(buf.st_mode) ) continue;
28381 if( osAccess(zDir, 07) ) continue;
28382 break;
28384 return zDir;
28388 ** Create a temporary file name in zBuf. zBuf must be allocated
28389 ** by the calling process and must be big enough to hold at least
28390 ** pVfs->mxPathname bytes.
28392 static int unixGetTempname(int nBuf, char *zBuf){
28393 static const unsigned char zChars[] =
28394 "abcdefghijklmnopqrstuvwxyz"
28395 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28396 "0123456789";
28397 unsigned int i, j;
28398 const char *zDir;
28400 /* It's odd to simulate an io-error here, but really this is just
28401 ** using the io-error infrastructure to test that SQLite handles this
28402 ** function failing.
28404 SimulateIOError( return SQLITE_IOERR );
28406 zDir = unixTempFileDir();
28407 if( zDir==0 ) zDir = ".";
28409 /* Check that the output buffer is large enough for the temporary file
28410 ** name. If it is not, return SQLITE_ERROR.
28412 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
28413 return SQLITE_ERROR;
28417 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
28418 j = (int)strlen(zBuf);
28419 sqlite3_randomness(15, &zBuf[j]);
28420 for(i=0; i<15; i++, j++){
28421 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28423 zBuf[j] = 0;
28424 zBuf[j+1] = 0;
28425 }while( osAccess(zBuf,0)==0 );
28426 return SQLITE_OK;
28429 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28431 ** Routine to transform a unixFile into a proxy-locking unixFile.
28432 ** Implementation in the proxy-lock division, but used by unixOpen()
28433 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
28435 static int proxyTransformUnixFile(unixFile*, const char*);
28436 #endif
28439 ** Search for an unused file descriptor that was opened on the database
28440 ** file (not a journal or master-journal file) identified by pathname
28441 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
28442 ** argument to this function.
28444 ** Such a file descriptor may exist if a database connection was closed
28445 ** but the associated file descriptor could not be closed because some
28446 ** other file descriptor open on the same file is holding a file-lock.
28447 ** Refer to comments in the unixClose() function and the lengthy comment
28448 ** describing "Posix Advisory Locking" at the start of this file for
28449 ** further details. Also, ticket #4018.
28451 ** If a suitable file descriptor is found, then it is returned. If no
28452 ** such file descriptor is located, -1 is returned.
28454 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
28455 UnixUnusedFd *pUnused = 0;
28457 /* Do not search for an unused file descriptor on vxworks. Not because
28458 ** vxworks would not benefit from the change (it might, we're not sure),
28459 ** but because no way to test it is currently available. It is better
28460 ** not to risk breaking vxworks support for the sake of such an obscure
28461 ** feature. */
28462 #if !OS_VXWORKS
28463 struct stat sStat; /* Results of stat() call */
28465 /* A stat() call may fail for various reasons. If this happens, it is
28466 ** almost certain that an open() call on the same path will also fail.
28467 ** For this reason, if an error occurs in the stat() call here, it is
28468 ** ignored and -1 is returned. The caller will try to open a new file
28469 ** descriptor on the same path, fail, and return an error to SQLite.
28471 ** Even if a subsequent open() call does succeed, the consequences of
28472 ** not searching for a resusable file descriptor are not dire. */
28473 if( 0==osStat(zPath, &sStat) ){
28474 unixInodeInfo *pInode;
28476 unixEnterMutex();
28477 pInode = inodeList;
28478 while( pInode && (pInode->fileId.dev!=sStat.st_dev
28479 || pInode->fileId.ino!=sStat.st_ino) ){
28480 pInode = pInode->pNext;
28482 if( pInode ){
28483 UnixUnusedFd **pp;
28484 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
28485 pUnused = *pp;
28486 if( pUnused ){
28487 *pp = pUnused->pNext;
28490 unixLeaveMutex();
28492 #endif /* if !OS_VXWORKS */
28493 return pUnused;
28497 ** This function is called by unixOpen() to determine the unix permissions
28498 ** to create new files with. If no error occurs, then SQLITE_OK is returned
28499 ** and a value suitable for passing as the third argument to open(2) is
28500 ** written to *pMode. If an IO error occurs, an SQLite error code is
28501 ** returned and the value of *pMode is not modified.
28503 ** In most cases cases, this routine sets *pMode to 0, which will become
28504 ** an indication to robust_open() to create the file using
28505 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
28506 ** But if the file being opened is a WAL or regular journal file, then
28507 ** this function queries the file-system for the permissions on the
28508 ** corresponding database file and sets *pMode to this value. Whenever
28509 ** possible, WAL and journal files are created using the same permissions
28510 ** as the associated database file.
28512 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
28513 ** original filename is unavailable. But 8_3_NAMES is only used for
28514 ** FAT filesystems and permissions do not matter there, so just use
28515 ** the default permissions.
28517 static int findCreateFileMode(
28518 const char *zPath, /* Path of file (possibly) being created */
28519 int flags, /* Flags passed as 4th argument to xOpen() */
28520 mode_t *pMode, /* OUT: Permissions to open file with */
28521 uid_t *pUid, /* OUT: uid to set on the file */
28522 gid_t *pGid /* OUT: gid to set on the file */
28524 int rc = SQLITE_OK; /* Return Code */
28525 *pMode = 0;
28526 *pUid = 0;
28527 *pGid = 0;
28528 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28529 char zDb[MAX_PATHNAME+1]; /* Database file path */
28530 int nDb; /* Number of valid bytes in zDb */
28531 struct stat sStat; /* Output of stat() on database file */
28533 /* zPath is a path to a WAL or journal file. The following block derives
28534 ** the path to the associated database file from zPath. This block handles
28535 ** the following naming conventions:
28537 ** "<path to db>-journal"
28538 ** "<path to db>-wal"
28539 ** "<path to db>-journalNN"
28540 ** "<path to db>-walNN"
28542 ** where NN is a decimal number. The NN naming schemes are
28543 ** used by the test_multiplex.c module.
28545 nDb = sqlite3Strlen30(zPath) - 1;
28546 #ifdef SQLITE_ENABLE_8_3_NAMES
28547 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
28548 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
28549 #else
28550 while( zPath[nDb]!='-' ){
28551 assert( nDb>0 );
28552 assert( zPath[nDb]!='\n' );
28553 nDb--;
28555 #endif
28556 memcpy(zDb, zPath, nDb);
28557 zDb[nDb] = '\0';
28559 if( 0==osStat(zDb, &sStat) ){
28560 *pMode = sStat.st_mode & 0777;
28561 *pUid = sStat.st_uid;
28562 *pGid = sStat.st_gid;
28563 }else{
28564 rc = SQLITE_IOERR_FSTAT;
28566 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28567 *pMode = 0600;
28569 return rc;
28573 ** Open the file zPath.
28575 ** Previously, the SQLite OS layer used three functions in place of this
28576 ** one:
28578 ** sqlite3OsOpenReadWrite();
28579 ** sqlite3OsOpenReadOnly();
28580 ** sqlite3OsOpenExclusive();
28582 ** These calls correspond to the following combinations of flags:
28584 ** ReadWrite() -> (READWRITE | CREATE)
28585 ** ReadOnly() -> (READONLY)
28586 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
28588 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
28589 ** true, the file was configured to be automatically deleted when the
28590 ** file handle closed. To achieve the same effect using this new
28591 ** interface, add the DELETEONCLOSE flag to those specified above for
28592 ** OpenExclusive().
28594 static int unixOpen(
28595 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
28596 const char *zPath, /* Pathname of file to be opened */
28597 sqlite3_file *pFile, /* The file descriptor to be filled in */
28598 int flags, /* Input flags to control the opening */
28599 int *pOutFlags /* Output flags returned to SQLite core */
28601 unixFile *p = (unixFile *)pFile;
28602 int fd = -1; /* File descriptor returned by open() */
28603 int openFlags = 0; /* Flags to pass to open() */
28604 int eType = flags&0xFFFFFF00; /* Type of file to open */
28605 int noLock; /* True to omit locking primitives */
28606 int rc = SQLITE_OK; /* Function Return Code */
28607 int ctrlFlags = 0; /* UNIXFILE_* flags */
28609 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
28610 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
28611 int isCreate = (flags & SQLITE_OPEN_CREATE);
28612 int isReadonly = (flags & SQLITE_OPEN_READONLY);
28613 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
28614 #if SQLITE_ENABLE_LOCKING_STYLE
28615 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
28616 #endif
28617 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28618 struct statfs fsInfo;
28619 #endif
28621 /* If creating a master or main-file journal, this function will open
28622 ** a file-descriptor on the directory too. The first time unixSync()
28623 ** is called the directory file descriptor will be fsync()ed and close()d.
28625 int syncDir = (isCreate && (
28626 eType==SQLITE_OPEN_MASTER_JOURNAL
28627 || eType==SQLITE_OPEN_MAIN_JOURNAL
28628 || eType==SQLITE_OPEN_WAL
28631 /* If argument zPath is a NULL pointer, this function is required to open
28632 ** a temporary file. Use this buffer to store the file name in.
28634 char zTmpname[MAX_PATHNAME+2];
28635 const char *zName = zPath;
28637 /* Check the following statements are true:
28639 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
28640 ** (b) if CREATE is set, then READWRITE must also be set, and
28641 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
28642 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
28644 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
28645 assert(isCreate==0 || isReadWrite);
28646 assert(isExclusive==0 || isCreate);
28647 assert(isDelete==0 || isCreate);
28649 /* The main DB, main journal, WAL file and master journal are never
28650 ** automatically deleted. Nor are they ever temporary files. */
28651 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
28652 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
28653 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
28654 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
28656 /* Assert that the upper layer has set one of the "file-type" flags. */
28657 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
28658 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
28659 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
28660 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
28663 memset(p, 0, sizeof(unixFile));
28665 if( eType==SQLITE_OPEN_MAIN_DB ){
28666 UnixUnusedFd *pUnused;
28667 pUnused = findReusableFd(zName, flags);
28668 if( pUnused ){
28669 fd = pUnused->fd;
28670 }else{
28671 pUnused = sqlite3_malloc(sizeof(*pUnused));
28672 if( !pUnused ){
28673 return SQLITE_NOMEM;
28676 p->pUnused = pUnused;
28678 /* Database filenames are double-zero terminated if they are not
28679 ** URIs with parameters. Hence, they can always be passed into
28680 ** sqlite3_uri_parameter(). */
28681 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
28683 }else if( !zName ){
28684 /* If zName is NULL, the upper layer is requesting a temp file. */
28685 assert(isDelete && !syncDir);
28686 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
28687 if( rc!=SQLITE_OK ){
28688 return rc;
28690 zName = zTmpname;
28692 /* Generated temporary filenames are always double-zero terminated
28693 ** for use by sqlite3_uri_parameter(). */
28694 assert( zName[strlen(zName)+1]==0 );
28697 /* Determine the value of the flags parameter passed to POSIX function
28698 ** open(). These must be calculated even if open() is not called, as
28699 ** they may be stored as part of the file handle and used by the
28700 ** 'conch file' locking functions later on. */
28701 if( isReadonly ) openFlags |= O_RDONLY;
28702 if( isReadWrite ) openFlags |= O_RDWR;
28703 if( isCreate ) openFlags |= O_CREAT;
28704 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
28705 openFlags |= (O_LARGEFILE|O_BINARY);
28707 if( fd<0 ){
28708 mode_t openMode; /* Permissions to create file with */
28709 uid_t uid; /* Userid for the file */
28710 gid_t gid; /* Groupid for the file */
28711 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
28712 if( rc!=SQLITE_OK ){
28713 assert( !p->pUnused );
28714 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
28715 return rc;
28717 fd = robust_open(zName, openFlags, openMode);
28718 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
28719 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
28720 /* Failed to open the file for read/write access. Try read-only. */
28721 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
28722 openFlags &= ~(O_RDWR|O_CREAT);
28723 flags |= SQLITE_OPEN_READONLY;
28724 openFlags |= O_RDONLY;
28725 isReadonly = 1;
28726 fd = robust_open(zName, openFlags, openMode);
28728 if( fd<0 ){
28729 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
28730 goto open_finished;
28733 /* If this process is running as root and if creating a new rollback
28734 ** journal or WAL file, set the ownership of the journal or WAL to be
28735 ** the same as the original database.
28737 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28738 osFchown(fd, uid, gid);
28741 assert( fd>=0 );
28742 if( pOutFlags ){
28743 *pOutFlags = flags;
28746 if( p->pUnused ){
28747 p->pUnused->fd = fd;
28748 p->pUnused->flags = flags;
28751 if( isDelete ){
28752 #if OS_VXWORKS
28753 zPath = zName;
28754 #else
28755 osUnlink(zName);
28756 #endif
28758 #if SQLITE_ENABLE_LOCKING_STYLE
28759 else{
28760 p->openFlags = openFlags;
28762 #endif
28764 noLock = eType!=SQLITE_OPEN_MAIN_DB;
28767 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28768 if( fstatfs(fd, &fsInfo) == -1 ){
28769 ((unixFile*)pFile)->lastErrno = errno;
28770 robust_close(p, fd, __LINE__);
28771 return SQLITE_IOERR_ACCESS;
28773 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
28774 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
28776 #endif
28778 /* Set up appropriate ctrlFlags */
28779 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
28780 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
28781 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
28782 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
28783 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
28785 #if SQLITE_ENABLE_LOCKING_STYLE
28786 #if SQLITE_PREFER_PROXY_LOCKING
28787 isAutoProxy = 1;
28788 #endif
28789 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
28790 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
28791 int useProxy = 0;
28793 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
28794 ** never use proxy, NULL means use proxy for non-local files only. */
28795 if( envforce!=NULL ){
28796 useProxy = atoi(envforce)>0;
28797 }else{
28798 if( statfs(zPath, &fsInfo) == -1 ){
28799 /* In theory, the close(fd) call is sub-optimal. If the file opened
28800 ** with fd is a database file, and there are other connections open
28801 ** on that file that are currently holding advisory locks on it,
28802 ** then the call to close() will cancel those locks. In practice,
28803 ** we're assuming that statfs() doesn't fail very often. At least
28804 ** not while other file descriptors opened by the same process on
28805 ** the same file are working. */
28806 p->lastErrno = errno;
28807 robust_close(p, fd, __LINE__);
28808 rc = SQLITE_IOERR_ACCESS;
28809 goto open_finished;
28811 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
28813 if( useProxy ){
28814 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28815 if( rc==SQLITE_OK ){
28816 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
28817 if( rc!=SQLITE_OK ){
28818 /* Use unixClose to clean up the resources added in fillInUnixFile
28819 ** and clear all the structure's references. Specifically,
28820 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
28822 unixClose(pFile);
28823 return rc;
28826 goto open_finished;
28829 #endif
28831 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28833 open_finished:
28834 if( rc!=SQLITE_OK ){
28835 sqlite3_free(p->pUnused);
28837 return rc;
28842 ** Delete the file at zPath. If the dirSync argument is true, fsync()
28843 ** the directory after deleting the file.
28845 static int unixDelete(
28846 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
28847 const char *zPath, /* Name of file to be deleted */
28848 int dirSync /* If true, fsync() directory after deleting file */
28850 int rc = SQLITE_OK;
28851 UNUSED_PARAMETER(NotUsed);
28852 SimulateIOError(return SQLITE_IOERR_DELETE);
28853 if( osUnlink(zPath)==(-1) ){
28854 if( errno==ENOENT ){
28855 rc = SQLITE_IOERR_DELETE_NOENT;
28856 }else{
28857 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
28859 return rc;
28861 #ifndef SQLITE_DISABLE_DIRSYNC
28862 if( (dirSync & 1)!=0 ){
28863 int fd;
28864 rc = osOpenDirectory(zPath, &fd);
28865 if( rc==SQLITE_OK ){
28866 #if OS_VXWORKS
28867 if( fsync(fd)==-1 )
28868 #else
28869 if( fsync(fd) )
28870 #endif
28872 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
28874 robust_close(0, fd, __LINE__);
28875 }else if( rc==SQLITE_CANTOPEN ){
28876 rc = SQLITE_OK;
28879 #endif
28880 return rc;
28884 ** Test the existence of or access permissions of file zPath. The
28885 ** test performed depends on the value of flags:
28887 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
28888 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
28889 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
28891 ** Otherwise return 0.
28893 static int unixAccess(
28894 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
28895 const char *zPath, /* Path of the file to examine */
28896 int flags, /* What do we want to learn about the zPath file? */
28897 int *pResOut /* Write result boolean here */
28899 int amode = 0;
28900 UNUSED_PARAMETER(NotUsed);
28901 SimulateIOError( return SQLITE_IOERR_ACCESS; );
28902 switch( flags ){
28903 case SQLITE_ACCESS_EXISTS:
28904 amode = F_OK;
28905 break;
28906 case SQLITE_ACCESS_READWRITE:
28907 amode = W_OK|R_OK;
28908 break;
28909 case SQLITE_ACCESS_READ:
28910 amode = R_OK;
28911 break;
28913 default:
28914 assert(!"Invalid flags argument");
28916 *pResOut = (osAccess(zPath, amode)==0);
28917 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
28918 struct stat buf;
28919 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
28920 *pResOut = 0;
28923 return SQLITE_OK;
28928 ** Turn a relative pathname into a full pathname. The relative path
28929 ** is stored as a nul-terminated string in the buffer pointed to by
28930 ** zPath.
28932 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
28933 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
28934 ** this buffer before returning.
28936 static int unixFullPathname(
28937 sqlite3_vfs *pVfs, /* Pointer to vfs object */
28938 const char *zPath, /* Possibly relative input path */
28939 int nOut, /* Size of output buffer in bytes */
28940 char *zOut /* Output buffer */
28943 /* It's odd to simulate an io-error here, but really this is just
28944 ** using the io-error infrastructure to test that SQLite handles this
28945 ** function failing. This function could fail if, for example, the
28946 ** current working directory has been unlinked.
28948 SimulateIOError( return SQLITE_ERROR );
28950 assert( pVfs->mxPathname==MAX_PATHNAME );
28951 UNUSED_PARAMETER(pVfs);
28953 zOut[nOut-1] = '\0';
28954 if( zPath[0]=='/' ){
28955 sqlite3_snprintf(nOut, zOut, "%s", zPath);
28956 }else{
28957 int nCwd;
28958 if( osGetcwd(zOut, nOut-1)==0 ){
28959 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
28961 nCwd = (int)strlen(zOut);
28962 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
28964 return SQLITE_OK;
28968 #ifndef SQLITE_OMIT_LOAD_EXTENSION
28970 ** Interfaces for opening a shared library, finding entry points
28971 ** within the shared library, and closing the shared library.
28973 #include <dlfcn.h>
28974 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
28975 UNUSED_PARAMETER(NotUsed);
28976 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
28980 ** SQLite calls this function immediately after a call to unixDlSym() or
28981 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
28982 ** message is available, it is written to zBufOut. If no error message
28983 ** is available, zBufOut is left unmodified and SQLite uses a default
28984 ** error message.
28986 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
28987 const char *zErr;
28988 UNUSED_PARAMETER(NotUsed);
28989 unixEnterMutex();
28990 zErr = dlerror();
28991 if( zErr ){
28992 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
28994 unixLeaveMutex();
28996 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
28998 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
28999 ** cast into a pointer to a function. And yet the library dlsym() routine
29000 ** returns a void* which is really a pointer to a function. So how do we
29001 ** use dlsym() with -pedantic-errors?
29003 ** Variable x below is defined to be a pointer to a function taking
29004 ** parameters void* and const char* and returning a pointer to a function.
29005 ** We initialize x by assigning it a pointer to the dlsym() function.
29006 ** (That assignment requires a cast.) Then we call the function that
29007 ** x points to.
29009 ** This work-around is unlikely to work correctly on any system where
29010 ** you really cannot cast a function pointer into void*. But then, on the
29011 ** other hand, dlsym() will not work on such a system either, so we have
29012 ** not really lost anything.
29014 void (*(*x)(void*,const char*))(void);
29015 UNUSED_PARAMETER(NotUsed);
29016 x = (void(*(*)(void*,const char*))(void))dlsym;
29017 return (*x)(p, zSym);
29019 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29020 UNUSED_PARAMETER(NotUsed);
29021 dlclose(pHandle);
29023 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29024 #define unixDlOpen 0
29025 #define unixDlError 0
29026 #define unixDlSym 0
29027 #define unixDlClose 0
29028 #endif
29031 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29033 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29034 UNUSED_PARAMETER(NotUsed);
29035 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29037 /* We have to initialize zBuf to prevent valgrind from reporting
29038 ** errors. The reports issued by valgrind are incorrect - we would
29039 ** prefer that the randomness be increased by making use of the
29040 ** uninitialized space in zBuf - but valgrind errors tend to worry
29041 ** some users. Rather than argue, it seems easier just to initialize
29042 ** the whole array and silence valgrind, even if that means less randomness
29043 ** in the random seed.
29045 ** When testing, initializing zBuf[] to zero is all we do. That means
29046 ** that we always use the same random number sequence. This makes the
29047 ** tests repeatable.
29049 memset(zBuf, 0, nBuf);
29050 #if !defined(SQLITE_TEST)
29052 int pid, fd, got;
29053 fd = robust_open("/dev/urandom", O_RDONLY, 0);
29054 if( fd<0 ){
29055 time_t t;
29056 time(&t);
29057 memcpy(zBuf, &t, sizeof(t));
29058 pid = getpid();
29059 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29060 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29061 nBuf = sizeof(t) + sizeof(pid);
29062 }else{
29063 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
29064 robust_close(0, fd, __LINE__);
29067 #endif
29068 return nBuf;
29073 ** Sleep for a little while. Return the amount of time slept.
29074 ** The argument is the number of microseconds we want to sleep.
29075 ** The return value is the number of microseconds of sleep actually
29076 ** requested from the underlying operating system, a number which
29077 ** might be greater than or equal to the argument, but not less
29078 ** than the argument.
29080 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29081 #if OS_VXWORKS
29082 struct timespec sp;
29084 sp.tv_sec = microseconds / 1000000;
29085 sp.tv_nsec = (microseconds % 1000000) * 1000;
29086 nanosleep(&sp, NULL);
29087 UNUSED_PARAMETER(NotUsed);
29088 return microseconds;
29089 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29090 usleep(microseconds);
29091 UNUSED_PARAMETER(NotUsed);
29092 return microseconds;
29093 #else
29094 int seconds = (microseconds+999999)/1000000;
29095 sleep(seconds);
29096 UNUSED_PARAMETER(NotUsed);
29097 return seconds*1000000;
29098 #endif
29102 ** The following variable, if set to a non-zero value, is interpreted as
29103 ** the number of seconds since 1970 and is used to set the result of
29104 ** sqlite3OsCurrentTime() during testing.
29106 #ifdef SQLITE_TEST
29107 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
29108 #endif
29111 ** Find the current time (in Universal Coordinated Time). Write into *piNow
29112 ** the current time and date as a Julian Day number times 86_400_000. In
29113 ** other words, write into *piNow the number of milliseconds since the Julian
29114 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29115 ** proleptic Gregorian calendar.
29117 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
29118 ** cannot be found.
29120 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29121 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29122 int rc = SQLITE_OK;
29123 #if defined(NO_GETTOD)
29124 time_t t;
29125 time(&t);
29126 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29127 #elif OS_VXWORKS
29128 struct timespec sNow;
29129 clock_gettime(CLOCK_REALTIME, &sNow);
29130 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29131 #else
29132 struct timeval sNow;
29133 if( gettimeofday(&sNow, 0)==0 ){
29134 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29135 }else{
29136 rc = SQLITE_ERROR;
29138 #endif
29140 #ifdef SQLITE_TEST
29141 if( sqlite3_current_time ){
29142 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29144 #endif
29145 UNUSED_PARAMETER(NotUsed);
29146 return rc;
29150 ** Find the current time (in Universal Coordinated Time). Write the
29151 ** current time and date as a Julian Day number into *prNow and
29152 ** return 0. Return 1 if the time and date cannot be found.
29154 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29155 sqlite3_int64 i = 0;
29156 int rc;
29157 UNUSED_PARAMETER(NotUsed);
29158 rc = unixCurrentTimeInt64(0, &i);
29159 *prNow = i/86400000.0;
29160 return rc;
29164 ** We added the xGetLastError() method with the intention of providing
29165 ** better low-level error messages when operating-system problems come up
29166 ** during SQLite operation. But so far, none of that has been implemented
29167 ** in the core. So this routine is never called. For now, it is merely
29168 ** a place-holder.
29170 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29171 UNUSED_PARAMETER(NotUsed);
29172 UNUSED_PARAMETER(NotUsed2);
29173 UNUSED_PARAMETER(NotUsed3);
29174 return 0;
29179 ************************ End of sqlite3_vfs methods ***************************
29180 ******************************************************************************/
29182 /******************************************************************************
29183 ************************** Begin Proxy Locking ********************************
29185 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
29186 ** other locking methods on secondary lock files. Proxy locking is a
29187 ** meta-layer over top of the primitive locking implemented above. For
29188 ** this reason, the division that implements of proxy locking is deferred
29189 ** until late in the file (here) after all of the other I/O methods have
29190 ** been defined - so that the primitive locking methods are available
29191 ** as services to help with the implementation of proxy locking.
29193 ****
29195 ** The default locking schemes in SQLite use byte-range locks on the
29196 ** database file to coordinate safe, concurrent access by multiple readers
29197 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
29198 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29199 ** as POSIX read & write locks over fixed set of locations (via fsctl),
29200 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
29201 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29202 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29203 ** address in the shared range is taken for a SHARED lock, the entire
29204 ** shared range is taken for an EXCLUSIVE lock):
29206 ** PENDING_BYTE 0x40000000
29207 ** RESERVED_BYTE 0x40000001
29208 ** SHARED_RANGE 0x40000002 -> 0x40000200
29210 ** This works well on the local file system, but shows a nearly 100x
29211 ** slowdown in read performance on AFP because the AFP client disables
29212 ** the read cache when byte-range locks are present. Enabling the read
29213 ** cache exposes a cache coherency problem that is present on all OS X
29214 ** supported network file systems. NFS and AFP both observe the
29215 ** close-to-open semantics for ensuring cache coherency
29216 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29217 ** address the requirements for concurrent database access by multiple
29218 ** readers and writers
29219 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29221 ** To address the performance and cache coherency issues, proxy file locking
29222 ** changes the way database access is controlled by limiting access to a
29223 ** single host at a time and moving file locks off of the database file
29224 ** and onto a proxy file on the local file system.
29227 ** Using proxy locks
29228 ** -----------------
29230 ** C APIs
29232 ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29233 ** <proxy_path> | ":auto:");
29234 ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29237 ** SQL pragmas
29239 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29240 ** PRAGMA [database.]lock_proxy_file
29242 ** Specifying ":auto:" means that if there is a conch file with a matching
29243 ** host ID in it, the proxy path in the conch file will be used, otherwise
29244 ** a proxy path based on the user's temp dir
29245 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29246 ** actual proxy file name is generated from the name and path of the
29247 ** database file. For example:
29249 ** For database path "/Users/me/foo.db"
29250 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29252 ** Once a lock proxy is configured for a database connection, it can not
29253 ** be removed, however it may be switched to a different proxy path via
29254 ** the above APIs (assuming the conch file is not being held by another
29255 ** connection or process).
29258 ** How proxy locking works
29259 ** -----------------------
29261 ** Proxy file locking relies primarily on two new supporting files:
29263 ** * conch file to limit access to the database file to a single host
29264 ** at a time
29266 ** * proxy file to act as a proxy for the advisory locks normally
29267 ** taken on the database
29269 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
29270 ** by taking an sqlite-style shared lock on the conch file, reading the
29271 ** contents and comparing the host's unique host ID (see below) and lock
29272 ** proxy path against the values stored in the conch. The conch file is
29273 ** stored in the same directory as the database file and the file name
29274 ** is patterned after the database file name as ".<databasename>-conch".
29275 ** If the conch file does not exist, or it's contents do not match the
29276 ** host ID and/or proxy path, then the lock is escalated to an exclusive
29277 ** lock and the conch file contents is updated with the host ID and proxy
29278 ** path and the lock is downgraded to a shared lock again. If the conch
29279 ** is held by another process (with a shared lock), the exclusive lock
29280 ** will fail and SQLITE_BUSY is returned.
29282 ** The proxy file - a single-byte file used for all advisory file locks
29283 ** normally taken on the database file. This allows for safe sharing
29284 ** of the database file for multiple readers and writers on the same
29285 ** host (the conch ensures that they all use the same local lock file).
29287 ** Requesting the lock proxy does not immediately take the conch, it is
29288 ** only taken when the first request to lock database file is made.
29289 ** This matches the semantics of the traditional locking behavior, where
29290 ** opening a connection to a database file does not take a lock on it.
29291 ** The shared lock and an open file descriptor are maintained until
29292 ** the connection to the database is closed.
29294 ** The proxy file and the lock file are never deleted so they only need
29295 ** to be created the first time they are used.
29297 ** Configuration options
29298 ** ---------------------
29300 ** SQLITE_PREFER_PROXY_LOCKING
29302 ** Database files accessed on non-local file systems are
29303 ** automatically configured for proxy locking, lock files are
29304 ** named automatically using the same logic as
29305 ** PRAGMA lock_proxy_file=":auto:"
29307 ** SQLITE_PROXY_DEBUG
29309 ** Enables the logging of error messages during host id file
29310 ** retrieval and creation
29312 ** LOCKPROXYDIR
29314 ** Overrides the default directory used for lock proxy files that
29315 ** are named automatically via the ":auto:" setting
29317 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29319 ** Permissions to use when creating a directory for storing the
29320 ** lock proxy files, only used when LOCKPROXYDIR is not set.
29323 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
29324 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
29325 ** force proxy locking to be used for every database file opened, and 0
29326 ** will force automatic proxy locking to be disabled for all database
29327 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
29328 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
29332 ** Proxy locking is only available on MacOSX
29334 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29337 ** The proxyLockingContext has the path and file structures for the remote
29338 ** and local proxy files in it
29340 typedef struct proxyLockingContext proxyLockingContext;
29341 struct proxyLockingContext {
29342 unixFile *conchFile; /* Open conch file */
29343 char *conchFilePath; /* Name of the conch file */
29344 unixFile *lockProxy; /* Open proxy lock file */
29345 char *lockProxyPath; /* Name of the proxy lock file */
29346 char *dbPath; /* Name of the open file */
29347 int conchHeld; /* 1 if the conch is held, -1 if lockless */
29348 void *oldLockingContext; /* Original lockingcontext to restore on close */
29349 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
29353 ** The proxy lock file path for the database at dbPath is written into lPath,
29354 ** which must point to valid, writable memory large enough for a maxLen length
29355 ** file path.
29357 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
29358 int len;
29359 int dbLen;
29360 int i;
29362 #ifdef LOCKPROXYDIR
29363 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
29364 #else
29365 # ifdef _CS_DARWIN_USER_TEMP_DIR
29367 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
29368 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
29369 lPath, errno, getpid()));
29370 return SQLITE_IOERR_LOCK;
29372 len = strlcat(lPath, "sqliteplocks", maxLen);
29374 # else
29375 len = strlcpy(lPath, "/tmp/", maxLen);
29376 # endif
29377 #endif
29379 if( lPath[len-1]!='/' ){
29380 len = strlcat(lPath, "/", maxLen);
29383 /* transform the db path to a unique cache name */
29384 dbLen = (int)strlen(dbPath);
29385 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
29386 char c = dbPath[i];
29387 lPath[i+len] = (c=='/')?'_':c;
29389 lPath[i+len]='\0';
29390 strlcat(lPath, ":auto:", maxLen);
29391 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
29392 return SQLITE_OK;
29396 ** Creates the lock file and any missing directories in lockPath
29398 static int proxyCreateLockPath(const char *lockPath){
29399 int i, len;
29400 char buf[MAXPATHLEN];
29401 int start = 0;
29403 assert(lockPath!=NULL);
29404 /* try to create all the intermediate directories */
29405 len = (int)strlen(lockPath);
29406 buf[0] = lockPath[0];
29407 for( i=1; i<len; i++ ){
29408 if( lockPath[i] == '/' && (i - start > 0) ){
29409 /* only mkdir if leaf dir != "." or "/" or ".." */
29410 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
29411 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
29412 buf[i]='\0';
29413 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
29414 int err=errno;
29415 if( err!=EEXIST ) {
29416 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
29417 "'%s' proxy lock path=%s pid=%d\n",
29418 buf, strerror(err), lockPath, getpid()));
29419 return err;
29423 start=i+1;
29425 buf[i] = lockPath[i];
29427 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
29428 return 0;
29432 ** Create a new VFS file descriptor (stored in memory obtained from
29433 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
29435 ** The caller is responsible not only for closing the file descriptor
29436 ** but also for freeing the memory associated with the file descriptor.
29438 static int proxyCreateUnixFile(
29439 const char *path, /* path for the new unixFile */
29440 unixFile **ppFile, /* unixFile created and returned by ref */
29441 int islockfile /* if non zero missing dirs will be created */
29443 int fd = -1;
29444 unixFile *pNew;
29445 int rc = SQLITE_OK;
29446 int openFlags = O_RDWR | O_CREAT;
29447 sqlite3_vfs dummyVfs;
29448 int terrno = 0;
29449 UnixUnusedFd *pUnused = NULL;
29451 /* 1. first try to open/create the file
29452 ** 2. if that fails, and this is a lock file (not-conch), try creating
29453 ** the parent directories and then try again.
29454 ** 3. if that fails, try to open the file read-only
29455 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
29457 pUnused = findReusableFd(path, openFlags);
29458 if( pUnused ){
29459 fd = pUnused->fd;
29460 }else{
29461 pUnused = sqlite3_malloc(sizeof(*pUnused));
29462 if( !pUnused ){
29463 return SQLITE_NOMEM;
29466 if( fd<0 ){
29467 fd = robust_open(path, openFlags, 0);
29468 terrno = errno;
29469 if( fd<0 && errno==ENOENT && islockfile ){
29470 if( proxyCreateLockPath(path) == SQLITE_OK ){
29471 fd = robust_open(path, openFlags, 0);
29475 if( fd<0 ){
29476 openFlags = O_RDONLY;
29477 fd = robust_open(path, openFlags, 0);
29478 terrno = errno;
29480 if( fd<0 ){
29481 if( islockfile ){
29482 return SQLITE_BUSY;
29484 switch (terrno) {
29485 case EACCES:
29486 return SQLITE_PERM;
29487 case EIO:
29488 return SQLITE_IOERR_LOCK; /* even though it is the conch */
29489 default:
29490 return SQLITE_CANTOPEN_BKPT;
29494 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
29495 if( pNew==NULL ){
29496 rc = SQLITE_NOMEM;
29497 goto end_create_proxy;
29499 memset(pNew, 0, sizeof(unixFile));
29500 pNew->openFlags = openFlags;
29501 memset(&dummyVfs, 0, sizeof(dummyVfs));
29502 dummyVfs.pAppData = (void*)&autolockIoFinder;
29503 dummyVfs.zName = "dummy";
29504 pUnused->fd = fd;
29505 pUnused->flags = openFlags;
29506 pNew->pUnused = pUnused;
29508 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
29509 if( rc==SQLITE_OK ){
29510 *ppFile = pNew;
29511 return SQLITE_OK;
29513 end_create_proxy:
29514 robust_close(pNew, fd, __LINE__);
29515 sqlite3_free(pNew);
29516 sqlite3_free(pUnused);
29517 return rc;
29520 #ifdef SQLITE_TEST
29521 /* simulate multiple hosts by creating unique hostid file paths */
29522 SQLITE_API int sqlite3_hostid_num = 0;
29523 #endif
29525 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
29527 /* Not always defined in the headers as it ought to be */
29528 extern int gethostuuid(uuid_t id, const struct timespec *wait);
29530 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
29531 ** bytes of writable memory.
29533 static int proxyGetHostID(unsigned char *pHostID, int *pError){
29534 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29535 memset(pHostID, 0, PROXY_HOSTIDLEN);
29536 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
29537 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
29539 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
29540 if( gethostuuid(pHostID, &timeout) ){
29541 int err = errno;
29542 if( pError ){
29543 *pError = err;
29545 return SQLITE_IOERR;
29548 #else
29549 UNUSED_PARAMETER(pError);
29550 #endif
29551 #ifdef SQLITE_TEST
29552 /* simulate multiple hosts by creating unique hostid file paths */
29553 if( sqlite3_hostid_num != 0){
29554 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
29556 #endif
29558 return SQLITE_OK;
29561 /* The conch file contains the header, host id and lock file path
29563 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
29564 #define PROXY_HEADERLEN 1 /* conch file header length */
29565 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
29566 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
29569 ** Takes an open conch file, copies the contents to a new path and then moves
29570 ** it back. The newly created file's file descriptor is assigned to the
29571 ** conch file structure and finally the original conch file descriptor is
29572 ** closed. Returns zero if successful.
29574 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
29575 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29576 unixFile *conchFile = pCtx->conchFile;
29577 char tPath[MAXPATHLEN];
29578 char buf[PROXY_MAXCONCHLEN];
29579 char *cPath = pCtx->conchFilePath;
29580 size_t readLen = 0;
29581 size_t pathLen = 0;
29582 char errmsg[64] = "";
29583 int fd = -1;
29584 int rc = -1;
29585 UNUSED_PARAMETER(myHostID);
29587 /* create a new path by replace the trailing '-conch' with '-break' */
29588 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
29589 if( pathLen>MAXPATHLEN || pathLen<6 ||
29590 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
29591 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
29592 goto end_breaklock;
29594 /* read the conch content */
29595 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
29596 if( readLen<PROXY_PATHINDEX ){
29597 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
29598 goto end_breaklock;
29600 /* write it out to the temporary break file */
29601 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
29602 if( fd<0 ){
29603 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
29604 goto end_breaklock;
29606 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
29607 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
29608 goto end_breaklock;
29610 if( rename(tPath, cPath) ){
29611 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
29612 goto end_breaklock;
29614 rc = 0;
29615 fprintf(stderr, "broke stale lock on %s\n", cPath);
29616 robust_close(pFile, conchFile->h, __LINE__);
29617 conchFile->h = fd;
29618 conchFile->openFlags = O_RDWR | O_CREAT;
29620 end_breaklock:
29621 if( rc ){
29622 if( fd>=0 ){
29623 osUnlink(tPath);
29624 robust_close(pFile, fd, __LINE__);
29626 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
29628 return rc;
29631 /* Take the requested lock on the conch file and break a stale lock if the
29632 ** host id matches.
29634 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
29635 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29636 unixFile *conchFile = pCtx->conchFile;
29637 int rc = SQLITE_OK;
29638 int nTries = 0;
29639 struct timespec conchModTime;
29641 memset(&conchModTime, 0, sizeof(conchModTime));
29642 do {
29643 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29644 nTries ++;
29645 if( rc==SQLITE_BUSY ){
29646 /* If the lock failed (busy):
29647 * 1st try: get the mod time of the conch, wait 0.5s and try again.
29648 * 2nd try: fail if the mod time changed or host id is different, wait
29649 * 10 sec and try again
29650 * 3rd try: break the lock unless the mod time has changed.
29652 struct stat buf;
29653 if( osFstat(conchFile->h, &buf) ){
29654 pFile->lastErrno = errno;
29655 return SQLITE_IOERR_LOCK;
29658 if( nTries==1 ){
29659 conchModTime = buf.st_mtimespec;
29660 usleep(500000); /* wait 0.5 sec and try the lock again*/
29661 continue;
29664 assert( nTries>1 );
29665 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
29666 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
29667 return SQLITE_BUSY;
29670 if( nTries==2 ){
29671 char tBuf[PROXY_MAXCONCHLEN];
29672 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
29673 if( len<0 ){
29674 pFile->lastErrno = errno;
29675 return SQLITE_IOERR_LOCK;
29677 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
29678 /* don't break the lock if the host id doesn't match */
29679 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
29680 return SQLITE_BUSY;
29682 }else{
29683 /* don't break the lock on short read or a version mismatch */
29684 return SQLITE_BUSY;
29686 usleep(10000000); /* wait 10 sec and try the lock again */
29687 continue;
29690 assert( nTries==3 );
29691 if( 0==proxyBreakConchLock(pFile, myHostID) ){
29692 rc = SQLITE_OK;
29693 if( lockType==EXCLUSIVE_LOCK ){
29694 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
29696 if( !rc ){
29697 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29701 } while( rc==SQLITE_BUSY && nTries<3 );
29703 return rc;
29706 /* Takes the conch by taking a shared lock and read the contents conch, if
29707 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
29708 ** lockPath means that the lockPath in the conch file will be used if the
29709 ** host IDs match, or a new lock path will be generated automatically
29710 ** and written to the conch file.
29712 static int proxyTakeConch(unixFile *pFile){
29713 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29715 if( pCtx->conchHeld!=0 ){
29716 return SQLITE_OK;
29717 }else{
29718 unixFile *conchFile = pCtx->conchFile;
29719 uuid_t myHostID;
29720 int pError = 0;
29721 char readBuf[PROXY_MAXCONCHLEN];
29722 char lockPath[MAXPATHLEN];
29723 char *tempLockPath = NULL;
29724 int rc = SQLITE_OK;
29725 int createConch = 0;
29726 int hostIdMatch = 0;
29727 int readLen = 0;
29728 int tryOldLockPath = 0;
29729 int forceNewLockPath = 0;
29731 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
29732 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
29734 rc = proxyGetHostID(myHostID, &pError);
29735 if( (rc&0xff)==SQLITE_IOERR ){
29736 pFile->lastErrno = pError;
29737 goto end_takeconch;
29739 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
29740 if( rc!=SQLITE_OK ){
29741 goto end_takeconch;
29743 /* read the existing conch file */
29744 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
29745 if( readLen<0 ){
29746 /* I/O error: lastErrno set by seekAndRead */
29747 pFile->lastErrno = conchFile->lastErrno;
29748 rc = SQLITE_IOERR_READ;
29749 goto end_takeconch;
29750 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
29751 readBuf[0]!=(char)PROXY_CONCHVERSION ){
29752 /* a short read or version format mismatch means we need to create a new
29753 ** conch file.
29755 createConch = 1;
29757 /* if the host id matches and the lock path already exists in the conch
29758 ** we'll try to use the path there, if we can't open that path, we'll
29759 ** retry with a new auto-generated path
29761 do { /* in case we need to try again for an :auto: named lock file */
29763 if( !createConch && !forceNewLockPath ){
29764 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
29765 PROXY_HOSTIDLEN);
29766 /* if the conch has data compare the contents */
29767 if( !pCtx->lockProxyPath ){
29768 /* for auto-named local lock file, just check the host ID and we'll
29769 ** use the local lock file path that's already in there
29771 if( hostIdMatch ){
29772 size_t pathLen = (readLen - PROXY_PATHINDEX);
29774 if( pathLen>=MAXPATHLEN ){
29775 pathLen=MAXPATHLEN-1;
29777 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
29778 lockPath[pathLen] = 0;
29779 tempLockPath = lockPath;
29780 tryOldLockPath = 1;
29781 /* create a copy of the lock path if the conch is taken */
29782 goto end_takeconch;
29784 }else if( hostIdMatch
29785 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
29786 readLen-PROXY_PATHINDEX)
29788 /* conch host and lock path match */
29789 goto end_takeconch;
29793 /* if the conch isn't writable and doesn't match, we can't take it */
29794 if( (conchFile->openFlags&O_RDWR) == 0 ){
29795 rc = SQLITE_BUSY;
29796 goto end_takeconch;
29799 /* either the conch didn't match or we need to create a new one */
29800 if( !pCtx->lockProxyPath ){
29801 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
29802 tempLockPath = lockPath;
29803 /* create a copy of the lock path _only_ if the conch is taken */
29806 /* update conch with host and path (this will fail if other process
29807 ** has a shared lock already), if the host id matches, use the big
29808 ** stick.
29810 futimes(conchFile->h, NULL);
29811 if( hostIdMatch && !createConch ){
29812 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
29813 /* We are trying for an exclusive lock but another thread in this
29814 ** same process is still holding a shared lock. */
29815 rc = SQLITE_BUSY;
29816 } else {
29817 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
29819 }else{
29820 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
29822 if( rc==SQLITE_OK ){
29823 char writeBuffer[PROXY_MAXCONCHLEN];
29824 int writeSize = 0;
29826 writeBuffer[0] = (char)PROXY_CONCHVERSION;
29827 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
29828 if( pCtx->lockProxyPath!=NULL ){
29829 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
29830 }else{
29831 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
29833 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
29834 robust_ftruncate(conchFile->h, writeSize);
29835 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
29836 fsync(conchFile->h);
29837 /* If we created a new conch file (not just updated the contents of a
29838 ** valid conch file), try to match the permissions of the database
29840 if( rc==SQLITE_OK && createConch ){
29841 struct stat buf;
29842 int err = osFstat(pFile->h, &buf);
29843 if( err==0 ){
29844 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
29845 S_IROTH|S_IWOTH);
29846 /* try to match the database file R/W permissions, ignore failure */
29847 #ifndef SQLITE_PROXY_DEBUG
29848 osFchmod(conchFile->h, cmode);
29849 #else
29851 rc = osFchmod(conchFile->h, cmode);
29852 }while( rc==(-1) && errno==EINTR );
29853 if( rc!=0 ){
29854 int code = errno;
29855 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
29856 cmode, code, strerror(code));
29857 } else {
29858 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
29860 }else{
29861 int code = errno;
29862 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
29863 err, code, strerror(code));
29864 #endif
29868 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
29870 end_takeconch:
29871 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
29872 if( rc==SQLITE_OK && pFile->openFlags ){
29873 int fd;
29874 if( pFile->h>=0 ){
29875 robust_close(pFile, pFile->h, __LINE__);
29877 pFile->h = -1;
29878 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
29879 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
29880 if( fd>=0 ){
29881 pFile->h = fd;
29882 }else{
29883 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
29884 during locking */
29887 if( rc==SQLITE_OK && !pCtx->lockProxy ){
29888 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
29889 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
29890 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
29891 /* we couldn't create the proxy lock file with the old lock file path
29892 ** so try again via auto-naming
29894 forceNewLockPath = 1;
29895 tryOldLockPath = 0;
29896 continue; /* go back to the do {} while start point, try again */
29899 if( rc==SQLITE_OK ){
29900 /* Need to make a copy of path if we extracted the value
29901 ** from the conch file or the path was allocated on the stack
29903 if( tempLockPath ){
29904 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
29905 if( !pCtx->lockProxyPath ){
29906 rc = SQLITE_NOMEM;
29910 if( rc==SQLITE_OK ){
29911 pCtx->conchHeld = 1;
29913 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
29914 afpLockingContext *afpCtx;
29915 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
29916 afpCtx->dbPath = pCtx->lockProxyPath;
29918 } else {
29919 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29921 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
29922 rc==SQLITE_OK?"ok":"failed"));
29923 return rc;
29924 } while (1); /* in case we need to retry the :auto: lock file -
29925 ** we should never get here except via the 'continue' call. */
29930 ** If pFile holds a lock on a conch file, then release that lock.
29932 static int proxyReleaseConch(unixFile *pFile){
29933 int rc = SQLITE_OK; /* Subroutine return code */
29934 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
29935 unixFile *conchFile; /* Name of the conch file */
29937 pCtx = (proxyLockingContext *)pFile->lockingContext;
29938 conchFile = pCtx->conchFile;
29939 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
29940 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
29941 getpid()));
29942 if( pCtx->conchHeld>0 ){
29943 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29945 pCtx->conchHeld = 0;
29946 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
29947 (rc==SQLITE_OK ? "ok" : "failed")));
29948 return rc;
29952 ** Given the name of a database file, compute the name of its conch file.
29953 ** Store the conch filename in memory obtained from sqlite3_malloc().
29954 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
29955 ** or SQLITE_NOMEM if unable to obtain memory.
29957 ** The caller is responsible for ensuring that the allocated memory
29958 ** space is eventually freed.
29960 ** *pConchPath is set to NULL if a memory allocation error occurs.
29962 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
29963 int i; /* Loop counter */
29964 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
29965 char *conchPath; /* buffer in which to construct conch name */
29967 /* Allocate space for the conch filename and initialize the name to
29968 ** the name of the original database file. */
29969 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
29970 if( conchPath==0 ){
29971 return SQLITE_NOMEM;
29973 memcpy(conchPath, dbPath, len+1);
29975 /* now insert a "." before the last / character */
29976 for( i=(len-1); i>=0; i-- ){
29977 if( conchPath[i]=='/' ){
29978 i++;
29979 break;
29982 conchPath[i]='.';
29983 while ( i<len ){
29984 conchPath[i+1]=dbPath[i];
29985 i++;
29988 /* append the "-conch" suffix to the file */
29989 memcpy(&conchPath[i+1], "-conch", 7);
29990 assert( (int)strlen(conchPath) == len+7 );
29992 return SQLITE_OK;
29996 /* Takes a fully configured proxy locking-style unix file and switches
29997 ** the local lock file path
29999 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30000 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30001 char *oldPath = pCtx->lockProxyPath;
30002 int rc = SQLITE_OK;
30004 if( pFile->eFileLock!=NO_LOCK ){
30005 return SQLITE_BUSY;
30008 /* nothing to do if the path is NULL, :auto: or matches the existing path */
30009 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30010 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30011 return SQLITE_OK;
30012 }else{
30013 unixFile *lockProxy = pCtx->lockProxy;
30014 pCtx->lockProxy=NULL;
30015 pCtx->conchHeld = 0;
30016 if( lockProxy!=NULL ){
30017 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30018 if( rc ) return rc;
30019 sqlite3_free(lockProxy);
30021 sqlite3_free(oldPath);
30022 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30025 return rc;
30029 ** pFile is a file that has been opened by a prior xOpen call. dbPath
30030 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30032 ** This routine find the filename associated with pFile and writes it
30033 ** int dbPath.
30035 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30036 #if defined(__APPLE__)
30037 if( pFile->pMethod == &afpIoMethods ){
30038 /* afp style keeps a reference to the db path in the filePath field
30039 ** of the struct */
30040 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30041 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30042 } else
30043 #endif
30044 if( pFile->pMethod == &dotlockIoMethods ){
30045 /* dot lock style uses the locking context to store the dot lock
30046 ** file path */
30047 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30048 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30049 }else{
30050 /* all other styles use the locking context to store the db file path */
30051 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30052 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30054 return SQLITE_OK;
30058 ** Takes an already filled in unix file and alters it so all file locking
30059 ** will be performed on the local proxy lock file. The following fields
30060 ** are preserved in the locking context so that they can be restored and
30061 ** the unix structure properly cleaned up at close time:
30062 ** ->lockingContext
30063 ** ->pMethod
30065 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30066 proxyLockingContext *pCtx;
30067 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
30068 char *lockPath=NULL;
30069 int rc = SQLITE_OK;
30071 if( pFile->eFileLock!=NO_LOCK ){
30072 return SQLITE_BUSY;
30074 proxyGetDbPathForUnixFile(pFile, dbPath);
30075 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30076 lockPath=NULL;
30077 }else{
30078 lockPath=(char *)path;
30081 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
30082 (lockPath ? lockPath : ":auto:"), getpid()));
30084 pCtx = sqlite3_malloc( sizeof(*pCtx) );
30085 if( pCtx==0 ){
30086 return SQLITE_NOMEM;
30088 memset(pCtx, 0, sizeof(*pCtx));
30090 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30091 if( rc==SQLITE_OK ){
30092 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30093 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30094 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30095 ** (c) the file system is read-only, then enable no-locking access.
30096 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30097 ** that openFlags will have only one of O_RDONLY or O_RDWR.
30099 struct statfs fsInfo;
30100 struct stat conchInfo;
30101 int goLockless = 0;
30103 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30104 int err = errno;
30105 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30106 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30109 if( goLockless ){
30110 pCtx->conchHeld = -1; /* read only FS/ lockless */
30111 rc = SQLITE_OK;
30115 if( rc==SQLITE_OK && lockPath ){
30116 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30119 if( rc==SQLITE_OK ){
30120 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30121 if( pCtx->dbPath==NULL ){
30122 rc = SQLITE_NOMEM;
30125 if( rc==SQLITE_OK ){
30126 /* all memory is allocated, proxys are created and assigned,
30127 ** switch the locking context and pMethod then return.
30129 pCtx->oldLockingContext = pFile->lockingContext;
30130 pFile->lockingContext = pCtx;
30131 pCtx->pOldMethod = pFile->pMethod;
30132 pFile->pMethod = &proxyIoMethods;
30133 }else{
30134 if( pCtx->conchFile ){
30135 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30136 sqlite3_free(pCtx->conchFile);
30138 sqlite3DbFree(0, pCtx->lockProxyPath);
30139 sqlite3_free(pCtx->conchFilePath);
30140 sqlite3_free(pCtx);
30142 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
30143 (rc==SQLITE_OK ? "ok" : "failed")));
30144 return rc;
30149 ** This routine handles sqlite3_file_control() calls that are specific
30150 ** to proxy locking.
30152 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30153 switch( op ){
30154 case SQLITE_GET_LOCKPROXYFILE: {
30155 unixFile *pFile = (unixFile*)id;
30156 if( pFile->pMethod == &proxyIoMethods ){
30157 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30158 proxyTakeConch(pFile);
30159 if( pCtx->lockProxyPath ){
30160 *(const char **)pArg = pCtx->lockProxyPath;
30161 }else{
30162 *(const char **)pArg = ":auto: (not held)";
30164 } else {
30165 *(const char **)pArg = NULL;
30167 return SQLITE_OK;
30169 case SQLITE_SET_LOCKPROXYFILE: {
30170 unixFile *pFile = (unixFile*)id;
30171 int rc = SQLITE_OK;
30172 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30173 if( pArg==NULL || (const char *)pArg==0 ){
30174 if( isProxyStyle ){
30175 /* turn off proxy locking - not supported */
30176 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30177 }else{
30178 /* turn off proxy locking - already off - NOOP */
30179 rc = SQLITE_OK;
30181 }else{
30182 const char *proxyPath = (const char *)pArg;
30183 if( isProxyStyle ){
30184 proxyLockingContext *pCtx =
30185 (proxyLockingContext*)pFile->lockingContext;
30186 if( !strcmp(pArg, ":auto:")
30187 || (pCtx->lockProxyPath &&
30188 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30190 rc = SQLITE_OK;
30191 }else{
30192 rc = switchLockProxyPath(pFile, proxyPath);
30194 }else{
30195 /* turn on proxy file locking */
30196 rc = proxyTransformUnixFile(pFile, proxyPath);
30199 return rc;
30201 default: {
30202 assert( 0 ); /* The call assures that only valid opcodes are sent */
30205 /*NOTREACHED*/
30206 return SQLITE_ERROR;
30210 ** Within this division (the proxying locking implementation) the procedures
30211 ** above this point are all utilities. The lock-related methods of the
30212 ** proxy-locking sqlite3_io_method object follow.
30217 ** This routine checks if there is a RESERVED lock held on the specified
30218 ** file by this or any other process. If such a lock is held, set *pResOut
30219 ** to a non-zero value otherwise *pResOut is set to zero. The return value
30220 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30222 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30223 unixFile *pFile = (unixFile*)id;
30224 int rc = proxyTakeConch(pFile);
30225 if( rc==SQLITE_OK ){
30226 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30227 if( pCtx->conchHeld>0 ){
30228 unixFile *proxy = pCtx->lockProxy;
30229 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30230 }else{ /* conchHeld < 0 is lockless */
30231 pResOut=0;
30234 return rc;
30238 ** Lock the file with the lock specified by parameter eFileLock - one
30239 ** of the following:
30241 ** (1) SHARED_LOCK
30242 ** (2) RESERVED_LOCK
30243 ** (3) PENDING_LOCK
30244 ** (4) EXCLUSIVE_LOCK
30246 ** Sometimes when requesting one lock state, additional lock states
30247 ** are inserted in between. The locking might fail on one of the later
30248 ** transitions leaving the lock state different from what it started but
30249 ** still short of its goal. The following chart shows the allowed
30250 ** transitions and the inserted intermediate states:
30252 ** UNLOCKED -> SHARED
30253 ** SHARED -> RESERVED
30254 ** SHARED -> (PENDING) -> EXCLUSIVE
30255 ** RESERVED -> (PENDING) -> EXCLUSIVE
30256 ** PENDING -> EXCLUSIVE
30258 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
30259 ** routine to lower a locking level.
30261 static int proxyLock(sqlite3_file *id, int eFileLock) {
30262 unixFile *pFile = (unixFile*)id;
30263 int rc = proxyTakeConch(pFile);
30264 if( rc==SQLITE_OK ){
30265 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30266 if( pCtx->conchHeld>0 ){
30267 unixFile *proxy = pCtx->lockProxy;
30268 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
30269 pFile->eFileLock = proxy->eFileLock;
30270 }else{
30271 /* conchHeld < 0 is lockless */
30274 return rc;
30279 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
30280 ** must be either NO_LOCK or SHARED_LOCK.
30282 ** If the locking level of the file descriptor is already at or below
30283 ** the requested locking level, this routine is a no-op.
30285 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
30286 unixFile *pFile = (unixFile*)id;
30287 int rc = proxyTakeConch(pFile);
30288 if( rc==SQLITE_OK ){
30289 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30290 if( pCtx->conchHeld>0 ){
30291 unixFile *proxy = pCtx->lockProxy;
30292 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
30293 pFile->eFileLock = proxy->eFileLock;
30294 }else{
30295 /* conchHeld < 0 is lockless */
30298 return rc;
30302 ** Close a file that uses proxy locks.
30304 static int proxyClose(sqlite3_file *id) {
30305 if( id ){
30306 unixFile *pFile = (unixFile*)id;
30307 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30308 unixFile *lockProxy = pCtx->lockProxy;
30309 unixFile *conchFile = pCtx->conchFile;
30310 int rc = SQLITE_OK;
30312 if( lockProxy ){
30313 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
30314 if( rc ) return rc;
30315 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
30316 if( rc ) return rc;
30317 sqlite3_free(lockProxy);
30318 pCtx->lockProxy = 0;
30320 if( conchFile ){
30321 if( pCtx->conchHeld ){
30322 rc = proxyReleaseConch(pFile);
30323 if( rc ) return rc;
30325 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
30326 if( rc ) return rc;
30327 sqlite3_free(conchFile);
30329 sqlite3DbFree(0, pCtx->lockProxyPath);
30330 sqlite3_free(pCtx->conchFilePath);
30331 sqlite3DbFree(0, pCtx->dbPath);
30332 /* restore the original locking context and pMethod then close it */
30333 pFile->lockingContext = pCtx->oldLockingContext;
30334 pFile->pMethod = pCtx->pOldMethod;
30335 sqlite3_free(pCtx);
30336 return pFile->pMethod->xClose(id);
30338 return SQLITE_OK;
30343 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30345 ** The proxy locking style is intended for use with AFP filesystems.
30346 ** And since AFP is only supported on MacOSX, the proxy locking is also
30347 ** restricted to MacOSX.
30350 ******************* End of the proxy lock implementation **********************
30351 ******************************************************************************/
30354 ** Initialize the operating system interface.
30356 ** This routine registers all VFS implementations for unix-like operating
30357 ** systems. This routine, and the sqlite3_os_end() routine that follows,
30358 ** should be the only routines in this file that are visible from other
30359 ** files.
30361 ** This routine is called once during SQLite initialization and by a
30362 ** single thread. The memory allocation and mutex subsystems have not
30363 ** necessarily been initialized when this routine is called, and so they
30364 ** should not be used.
30366 SQLITE_API int sqlite3_os_init(void){
30368 ** The following macro defines an initializer for an sqlite3_vfs object.
30369 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
30370 ** to the "finder" function. (pAppData is a pointer to a pointer because
30371 ** silly C90 rules prohibit a void* from being cast to a function pointer
30372 ** and so we have to go through the intermediate pointer to avoid problems
30373 ** when compiling with -pedantic-errors on GCC.)
30375 ** The FINDER parameter to this macro is the name of the pointer to the
30376 ** finder-function. The finder-function returns a pointer to the
30377 ** sqlite_io_methods object that implements the desired locking
30378 ** behaviors. See the division above that contains the IOMETHODS
30379 ** macro for addition information on finder-functions.
30381 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
30382 ** object. But the "autolockIoFinder" available on MacOSX does a little
30383 ** more than that; it looks at the filesystem type that hosts the
30384 ** database file and tries to choose an locking method appropriate for
30385 ** that filesystem time.
30387 #define UNIXVFS(VFSNAME, FINDER) { \
30388 3, /* iVersion */ \
30389 sizeof(unixFile), /* szOsFile */ \
30390 MAX_PATHNAME, /* mxPathname */ \
30391 0, /* pNext */ \
30392 VFSNAME, /* zName */ \
30393 (void*)&FINDER, /* pAppData */ \
30394 unixOpen, /* xOpen */ \
30395 unixDelete, /* xDelete */ \
30396 unixAccess, /* xAccess */ \
30397 unixFullPathname, /* xFullPathname */ \
30398 unixDlOpen, /* xDlOpen */ \
30399 unixDlError, /* xDlError */ \
30400 unixDlSym, /* xDlSym */ \
30401 unixDlClose, /* xDlClose */ \
30402 unixRandomness, /* xRandomness */ \
30403 unixSleep, /* xSleep */ \
30404 unixCurrentTime, /* xCurrentTime */ \
30405 unixGetLastError, /* xGetLastError */ \
30406 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
30407 unixSetSystemCall, /* xSetSystemCall */ \
30408 unixGetSystemCall, /* xGetSystemCall */ \
30409 unixNextSystemCall, /* xNextSystemCall */ \
30413 ** All default VFSes for unix are contained in the following array.
30415 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
30416 ** by the SQLite core when the VFS is registered. So the following
30417 ** array cannot be const.
30419 static sqlite3_vfs aVfs[] = {
30420 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
30421 UNIXVFS("unix", autolockIoFinder ),
30422 #else
30423 UNIXVFS("unix", posixIoFinder ),
30424 #endif
30425 UNIXVFS("unix-none", nolockIoFinder ),
30426 UNIXVFS("unix-dotfile", dotlockIoFinder ),
30427 UNIXVFS("unix-excl", posixIoFinder ),
30428 #if OS_VXWORKS
30429 UNIXVFS("unix-namedsem", semIoFinder ),
30430 #endif
30431 #if SQLITE_ENABLE_LOCKING_STYLE
30432 UNIXVFS("unix-posix", posixIoFinder ),
30433 #if !OS_VXWORKS
30434 UNIXVFS("unix-flock", flockIoFinder ),
30435 #endif
30436 #endif
30437 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30438 UNIXVFS("unix-afp", afpIoFinder ),
30439 UNIXVFS("unix-nfs", nfsIoFinder ),
30440 UNIXVFS("unix-proxy", proxyIoFinder ),
30441 #endif
30443 unsigned int i; /* Loop counter */
30445 /* Double-check that the aSyscall[] array has been constructed
30446 ** correctly. See ticket [bb3a86e890c8e96ab] */
30447 assert( ArraySize(aSyscall)==24 );
30449 /* Register all VFSes defined in the aVfs[] array */
30450 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
30451 sqlite3_vfs_register(&aVfs[i], i==0);
30453 return SQLITE_OK;
30457 ** Shutdown the operating system interface.
30459 ** Some operating systems might need to do some cleanup in this routine,
30460 ** to release dynamically allocated objects. But not on unix.
30461 ** This routine is a no-op for unix.
30463 SQLITE_API int sqlite3_os_end(void){
30464 return SQLITE_OK;
30467 #endif /* SQLITE_OS_UNIX */
30469 /************** End of os_unix.c *********************************************/
30470 /************** Begin file os_win.c ******************************************/
30472 ** 2004 May 22
30474 ** The author disclaims copyright to this source code. In place of
30475 ** a legal notice, here is a blessing:
30477 ** May you do good and not evil.
30478 ** May you find forgiveness for yourself and forgive others.
30479 ** May you share freely, never taking more than you give.
30481 ******************************************************************************
30483 ** This file contains code that is specific to Windows.
30485 #if SQLITE_OS_WIN /* This file is used for Windows only */
30487 #ifdef __CYGWIN__
30488 # include <sys/cygwin.h>
30489 /* # include <errno.h> */
30490 #endif
30493 ** Include code that is common to all os_*.c files
30495 /************** Include os_common.h in the middle of os_win.c ****************/
30496 /************** Begin file os_common.h ***************************************/
30498 ** 2004 May 22
30500 ** The author disclaims copyright to this source code. In place of
30501 ** a legal notice, here is a blessing:
30503 ** May you do good and not evil.
30504 ** May you find forgiveness for yourself and forgive others.
30505 ** May you share freely, never taking more than you give.
30507 ******************************************************************************
30509 ** This file contains macros and a little bit of code that is common to
30510 ** all of the platform-specific files (os_*.c) and is #included into those
30511 ** files.
30513 ** This file should be #included by the os_*.c files only. It is not a
30514 ** general purpose header file.
30516 #ifndef _OS_COMMON_H_
30517 #define _OS_COMMON_H_
30520 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
30521 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
30522 ** switch. The following code should catch this problem at compile-time.
30524 #ifdef MEMORY_DEBUG
30525 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
30526 #endif
30528 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
30529 # ifndef SQLITE_DEBUG_OS_TRACE
30530 # define SQLITE_DEBUG_OS_TRACE 0
30531 # endif
30532 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
30533 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
30534 #else
30535 # define OSTRACE(X)
30536 #endif
30539 ** Macros for performance tracing. Normally turned off. Only works
30540 ** on i486 hardware.
30542 #ifdef SQLITE_PERFORMANCE_TRACE
30545 ** hwtime.h contains inline assembler code for implementing
30546 ** high-performance timing routines.
30548 /************** Include hwtime.h in the middle of os_common.h ****************/
30549 /************** Begin file hwtime.h ******************************************/
30551 ** 2008 May 27
30553 ** The author disclaims copyright to this source code. In place of
30554 ** a legal notice, here is a blessing:
30556 ** May you do good and not evil.
30557 ** May you find forgiveness for yourself and forgive others.
30558 ** May you share freely, never taking more than you give.
30560 ******************************************************************************
30562 ** This file contains inline asm code for retrieving "high-performance"
30563 ** counters for x86 class CPUs.
30565 #ifndef _HWTIME_H_
30566 #define _HWTIME_H_
30569 ** The following routine only works on pentium-class (or newer) processors.
30570 ** It uses the RDTSC opcode to read the cycle count value out of the
30571 ** processor and returns that value. This can be used for high-res
30572 ** profiling.
30574 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
30575 (defined(i386) || defined(__i386__) || defined(_M_IX86))
30577 #if defined(__GNUC__)
30579 __inline__ sqlite_uint64 sqlite3Hwtime(void){
30580 unsigned int lo, hi;
30581 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30582 return (sqlite_uint64)hi << 32 | lo;
30585 #elif defined(_MSC_VER)
30587 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30588 __asm {
30589 rdtsc
30590 ret ; return value at EDX:EAX
30594 #endif
30596 #elif (defined(__GNUC__) && defined(__x86_64__))
30598 __inline__ sqlite_uint64 sqlite3Hwtime(void){
30599 unsigned long val;
30600 __asm__ __volatile__ ("rdtsc" : "=A" (val));
30601 return val;
30604 #elif (defined(__GNUC__) && defined(__ppc__))
30606 __inline__ sqlite_uint64 sqlite3Hwtime(void){
30607 unsigned long long retval;
30608 unsigned long junk;
30609 __asm__ __volatile__ ("\n\
30610 1: mftbu %1\n\
30611 mftb %L0\n\
30612 mftbu %0\n\
30613 cmpw %0,%1\n\
30614 bne 1b"
30615 : "=r" (retval), "=r" (junk));
30616 return retval;
30619 #else
30621 #error Need implementation of sqlite3Hwtime() for your platform.
30624 ** To compile without implementing sqlite3Hwtime() for your platform,
30625 ** you can remove the above #error and use the following
30626 ** stub function. You will lose timing support for many
30627 ** of the debugging and testing utilities, but it should at
30628 ** least compile and run.
30630 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
30632 #endif
30634 #endif /* !defined(_HWTIME_H_) */
30636 /************** End of hwtime.h **********************************************/
30637 /************** Continuing where we left off in os_common.h ******************/
30639 static sqlite_uint64 g_start;
30640 static sqlite_uint64 g_elapsed;
30641 #define TIMER_START g_start=sqlite3Hwtime()
30642 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
30643 #define TIMER_ELAPSED g_elapsed
30644 #else
30645 #define TIMER_START
30646 #define TIMER_END
30647 #define TIMER_ELAPSED ((sqlite_uint64)0)
30648 #endif
30651 ** If we compile with the SQLITE_TEST macro set, then the following block
30652 ** of code will give us the ability to simulate a disk I/O error. This
30653 ** is used for testing the I/O recovery logic.
30655 #ifdef SQLITE_TEST
30656 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
30657 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
30658 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
30659 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
30660 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
30661 SQLITE_API int sqlite3_diskfull_pending = 0;
30662 SQLITE_API int sqlite3_diskfull = 0;
30663 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
30664 #define SimulateIOError(CODE) \
30665 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
30666 || sqlite3_io_error_pending-- == 1 ) \
30667 { local_ioerr(); CODE; }
30668 static void local_ioerr(){
30669 IOTRACE(("IOERR\n"));
30670 sqlite3_io_error_hit++;
30671 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
30673 #define SimulateDiskfullError(CODE) \
30674 if( sqlite3_diskfull_pending ){ \
30675 if( sqlite3_diskfull_pending == 1 ){ \
30676 local_ioerr(); \
30677 sqlite3_diskfull = 1; \
30678 sqlite3_io_error_hit = 1; \
30679 CODE; \
30680 }else{ \
30681 sqlite3_diskfull_pending--; \
30684 #else
30685 #define SimulateIOErrorBenign(X)
30686 #define SimulateIOError(A)
30687 #define SimulateDiskfullError(A)
30688 #endif
30691 ** When testing, keep a count of the number of open files.
30693 #ifdef SQLITE_TEST
30694 SQLITE_API int sqlite3_open_file_count = 0;
30695 #define OpenCounter(X) sqlite3_open_file_count+=(X)
30696 #else
30697 #define OpenCounter(X)
30698 #endif
30700 #endif /* !defined(_OS_COMMON_H_) */
30702 /************** End of os_common.h *******************************************/
30703 /************** Continuing where we left off in os_win.c *********************/
30706 ** Compiling and using WAL mode requires several APIs that are only
30707 ** available in Windows platforms based on the NT kernel.
30709 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
30710 # error "WAL mode requires support from the Windows NT kernel, compile\
30711 with SQLITE_OMIT_WAL."
30712 #endif
30715 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
30716 ** based on the sub-platform)?
30718 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30719 # define SQLITE_WIN32_HAS_ANSI
30720 #endif
30723 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
30724 ** based on the sub-platform)?
30726 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
30727 # define SQLITE_WIN32_HAS_WIDE
30728 #endif
30731 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
30732 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
30733 ** are not present in the header file)?
30735 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
30737 ** Two of the file mapping APIs are different under WinRT. Figure out which
30738 ** set we need.
30740 #if SQLITE_OS_WINRT
30741 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
30742 LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
30744 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
30745 #else
30746 #if defined(SQLITE_WIN32_HAS_ANSI)
30747 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
30748 DWORD, DWORD, DWORD, LPCSTR);
30749 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
30751 #if defined(SQLITE_WIN32_HAS_WIDE)
30752 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
30753 DWORD, DWORD, DWORD, LPCWSTR);
30754 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
30756 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
30757 #endif /* SQLITE_OS_WINRT */
30760 ** This file mapping API is common to both Win32 and WinRT.
30762 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
30763 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
30766 ** Some Microsoft compilers lack this definition.
30768 #ifndef INVALID_FILE_ATTRIBUTES
30769 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
30770 #endif
30772 #ifndef FILE_FLAG_MASK
30773 # define FILE_FLAG_MASK (0xFF3C0000)
30774 #endif
30776 #ifndef FILE_ATTRIBUTE_MASK
30777 # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
30778 #endif
30780 #ifndef SQLITE_OMIT_WAL
30781 /* Forward references */
30782 typedef struct winShm winShm; /* A connection to shared-memory */
30783 typedef struct winShmNode winShmNode; /* A region of shared-memory */
30784 #endif
30787 ** WinCE lacks native support for file locking so we have to fake it
30788 ** with some code of our own.
30790 #if SQLITE_OS_WINCE
30791 typedef struct winceLock {
30792 int nReaders; /* Number of reader locks obtained */
30793 BOOL bPending; /* Indicates a pending lock has been obtained */
30794 BOOL bReserved; /* Indicates a reserved lock has been obtained */
30795 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
30796 } winceLock;
30797 #endif
30800 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
30801 ** portability layer.
30803 typedef struct winFile winFile;
30804 struct winFile {
30805 const sqlite3_io_methods *pMethod; /*** Must be first ***/
30806 sqlite3_vfs *pVfs; /* The VFS used to open this file */
30807 HANDLE h; /* Handle for accessing the file */
30808 u8 locktype; /* Type of lock currently held on this file */
30809 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
30810 u8 ctrlFlags; /* Flags. See WINFILE_* below */
30811 DWORD lastErrno; /* The Windows errno from the last I/O error */
30812 #ifndef SQLITE_OMIT_WAL
30813 winShm *pShm; /* Instance of shared memory on this file */
30814 #endif
30815 const char *zPath; /* Full pathname of this file */
30816 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
30817 #if SQLITE_OS_WINCE
30818 LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
30819 HANDLE hMutex; /* Mutex used to control access to shared lock */
30820 HANDLE hShared; /* Shared memory segment used for locking */
30821 winceLock local; /* Locks obtained by this instance of winFile */
30822 winceLock *shared; /* Global shared lock memory for the file */
30823 #endif
30824 #if SQLITE_MAX_MMAP_SIZE>0
30825 int nFetchOut; /* Number of outstanding xFetch references */
30826 HANDLE hMap; /* Handle for accessing memory mapping */
30827 void *pMapRegion; /* Area memory mapped */
30828 sqlite3_int64 mmapSize; /* Usable size of mapped region */
30829 sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
30830 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
30831 #endif
30835 ** Allowed values for winFile.ctrlFlags
30837 #define WINFILE_RDONLY 0x02 /* Connection is read only */
30838 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
30839 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
30842 * The size of the buffer used by sqlite3_win32_write_debug().
30844 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
30845 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
30846 #endif
30849 * The value used with sqlite3_win32_set_directory() to specify that
30850 * the data directory should be changed.
30852 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
30853 # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
30854 #endif
30857 * The value used with sqlite3_win32_set_directory() to specify that
30858 * the temporary directory should be changed.
30860 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
30861 # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
30862 #endif
30865 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
30866 * various Win32 API heap functions instead of our own.
30868 #ifdef SQLITE_WIN32_MALLOC
30871 * If this is non-zero, an isolated heap will be created by the native Win32
30872 * allocator subsystem; otherwise, the default process heap will be used. This
30873 * setting has no effect when compiling for WinRT. By default, this is enabled
30874 * and an isolated heap will be created to store all allocated data.
30876 ******************************************************************************
30877 * WARNING: It is important to note that when this setting is non-zero and the
30878 * winMemShutdown function is called (e.g. by the sqlite3_shutdown
30879 * function), all data that was allocated using the isolated heap will
30880 * be freed immediately and any attempt to access any of that freed
30881 * data will almost certainly result in an immediate access violation.
30882 ******************************************************************************
30884 #ifndef SQLITE_WIN32_HEAP_CREATE
30885 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
30886 #endif
30889 * The initial size of the Win32-specific heap. This value may be zero.
30891 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
30892 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
30893 (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
30894 #endif
30897 * The maximum size of the Win32-specific heap. This value may be zero.
30899 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
30900 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
30901 #endif
30904 * The extra flags to use in calls to the Win32 heap APIs. This value may be
30905 * zero for the default behavior.
30907 #ifndef SQLITE_WIN32_HEAP_FLAGS
30908 # define SQLITE_WIN32_HEAP_FLAGS (0)
30909 #endif
30913 ** The winMemData structure stores information required by the Win32-specific
30914 ** sqlite3_mem_methods implementation.
30916 typedef struct winMemData winMemData;
30917 struct winMemData {
30918 #ifndef NDEBUG
30919 u32 magic; /* Magic number to detect structure corruption. */
30920 #endif
30921 HANDLE hHeap; /* The handle to our heap. */
30922 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
30925 #ifndef NDEBUG
30926 #define WINMEM_MAGIC 0x42b2830b
30927 #endif
30929 static struct winMemData win_mem_data = {
30930 #ifndef NDEBUG
30931 WINMEM_MAGIC,
30932 #endif
30933 NULL, FALSE
30936 #ifndef NDEBUG
30937 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
30938 #else
30939 #define winMemAssertMagic()
30940 #endif
30942 #define winMemGetHeap() win_mem_data.hHeap
30944 static void *winMemMalloc(int nBytes);
30945 static void winMemFree(void *pPrior);
30946 static void *winMemRealloc(void *pPrior, int nBytes);
30947 static int winMemSize(void *p);
30948 static int winMemRoundup(int n);
30949 static int winMemInit(void *pAppData);
30950 static void winMemShutdown(void *pAppData);
30952 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
30953 #endif /* SQLITE_WIN32_MALLOC */
30956 ** The following variable is (normally) set once and never changes
30957 ** thereafter. It records whether the operating system is Win9x
30958 ** or WinNT.
30960 ** 0: Operating system unknown.
30961 ** 1: Operating system is Win9x.
30962 ** 2: Operating system is WinNT.
30964 ** In order to facilitate testing on a WinNT system, the test fixture
30965 ** can manually set this value to 1 to emulate Win98 behavior.
30967 #ifdef SQLITE_TEST
30968 SQLITE_API int sqlite3_os_type = 0;
30969 #else
30970 static int sqlite3_os_type = 0;
30971 #endif
30973 #ifndef SYSCALL
30974 # define SYSCALL sqlite3_syscall_ptr
30975 #endif
30978 ** This function is not available on Windows CE or WinRT.
30981 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
30982 # define osAreFileApisANSI() 1
30983 #endif
30986 ** Many system calls are accessed through pointer-to-functions so that
30987 ** they may be overridden at runtime to facilitate fault injection during
30988 ** testing and sandboxing. The following array holds the names and pointers
30989 ** to all overrideable system calls.
30991 static struct win_syscall {
30992 const char *zName; /* Name of the system call */
30993 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
30994 sqlite3_syscall_ptr pDefault; /* Default value */
30995 } aSyscall[] = {
30996 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30997 { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
30998 #else
30999 { "AreFileApisANSI", (SYSCALL)0, 0 },
31000 #endif
31002 #ifndef osAreFileApisANSI
31003 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
31004 #endif
31006 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
31007 { "CharLowerW", (SYSCALL)CharLowerW, 0 },
31008 #else
31009 { "CharLowerW", (SYSCALL)0, 0 },
31010 #endif
31012 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
31014 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
31015 { "CharUpperW", (SYSCALL)CharUpperW, 0 },
31016 #else
31017 { "CharUpperW", (SYSCALL)0, 0 },
31018 #endif
31020 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
31022 { "CloseHandle", (SYSCALL)CloseHandle, 0 },
31024 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
31026 #if defined(SQLITE_WIN32_HAS_ANSI)
31027 { "CreateFileA", (SYSCALL)CreateFileA, 0 },
31028 #else
31029 { "CreateFileA", (SYSCALL)0, 0 },
31030 #endif
31032 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
31033 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
31035 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31036 { "CreateFileW", (SYSCALL)CreateFileW, 0 },
31037 #else
31038 { "CreateFileW", (SYSCALL)0, 0 },
31039 #endif
31041 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
31042 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
31044 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
31045 !defined(SQLITE_OMIT_WAL))
31046 { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
31047 #else
31048 { "CreateFileMappingA", (SYSCALL)0, 0 },
31049 #endif
31051 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
31052 DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
31054 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
31055 !defined(SQLITE_OMIT_WAL))
31056 { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
31057 #else
31058 { "CreateFileMappingW", (SYSCALL)0, 0 },
31059 #endif
31061 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
31062 DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
31064 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31065 { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
31066 #else
31067 { "CreateMutexW", (SYSCALL)0, 0 },
31068 #endif
31070 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
31071 LPCWSTR))aSyscall[8].pCurrent)
31073 #if defined(SQLITE_WIN32_HAS_ANSI)
31074 { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
31075 #else
31076 { "DeleteFileA", (SYSCALL)0, 0 },
31077 #endif
31079 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
31081 #if defined(SQLITE_WIN32_HAS_WIDE)
31082 { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
31083 #else
31084 { "DeleteFileW", (SYSCALL)0, 0 },
31085 #endif
31087 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
31089 #if SQLITE_OS_WINCE
31090 { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
31091 #else
31092 { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
31093 #endif
31095 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
31096 LPFILETIME))aSyscall[11].pCurrent)
31098 #if SQLITE_OS_WINCE
31099 { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
31100 #else
31101 { "FileTimeToSystemTime", (SYSCALL)0, 0 },
31102 #endif
31104 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
31105 LPSYSTEMTIME))aSyscall[12].pCurrent)
31107 { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
31109 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
31111 #if defined(SQLITE_WIN32_HAS_ANSI)
31112 { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
31113 #else
31114 { "FormatMessageA", (SYSCALL)0, 0 },
31115 #endif
31117 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
31118 DWORD,va_list*))aSyscall[14].pCurrent)
31120 #if defined(SQLITE_WIN32_HAS_WIDE)
31121 { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
31122 #else
31123 { "FormatMessageW", (SYSCALL)0, 0 },
31124 #endif
31126 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
31127 DWORD,va_list*))aSyscall[15].pCurrent)
31129 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
31130 { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
31131 #else
31132 { "FreeLibrary", (SYSCALL)0, 0 },
31133 #endif
31135 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
31137 { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
31139 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
31141 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
31142 { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
31143 #else
31144 { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
31145 #endif
31147 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
31148 LPDWORD))aSyscall[18].pCurrent)
31150 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31151 { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
31152 #else
31153 { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
31154 #endif
31156 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
31157 LPDWORD))aSyscall[19].pCurrent)
31159 #if defined(SQLITE_WIN32_HAS_ANSI)
31160 { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
31161 #else
31162 { "GetFileAttributesA", (SYSCALL)0, 0 },
31163 #endif
31165 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
31167 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31168 { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
31169 #else
31170 { "GetFileAttributesW", (SYSCALL)0, 0 },
31171 #endif
31173 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
31175 #if defined(SQLITE_WIN32_HAS_WIDE)
31176 { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
31177 #else
31178 { "GetFileAttributesExW", (SYSCALL)0, 0 },
31179 #endif
31181 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
31182 LPVOID))aSyscall[22].pCurrent)
31184 #if !SQLITE_OS_WINRT
31185 { "GetFileSize", (SYSCALL)GetFileSize, 0 },
31186 #else
31187 { "GetFileSize", (SYSCALL)0, 0 },
31188 #endif
31190 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
31192 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
31193 { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
31194 #else
31195 { "GetFullPathNameA", (SYSCALL)0, 0 },
31196 #endif
31198 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
31199 LPSTR*))aSyscall[24].pCurrent)
31201 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31202 { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
31203 #else
31204 { "GetFullPathNameW", (SYSCALL)0, 0 },
31205 #endif
31207 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
31208 LPWSTR*))aSyscall[25].pCurrent)
31210 { "GetLastError", (SYSCALL)GetLastError, 0 },
31212 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
31214 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
31215 #if SQLITE_OS_WINCE
31216 /* The GetProcAddressA() routine is only available on Windows CE. */
31217 { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
31218 #else
31219 /* All other Windows platforms expect GetProcAddress() to take
31220 ** an ANSI string regardless of the _UNICODE setting */
31221 { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
31222 #endif
31223 #else
31224 { "GetProcAddressA", (SYSCALL)0, 0 },
31225 #endif
31227 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
31228 LPCSTR))aSyscall[27].pCurrent)
31230 #if !SQLITE_OS_WINRT
31231 { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
31232 #else
31233 { "GetSystemInfo", (SYSCALL)0, 0 },
31234 #endif
31236 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
31238 { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
31240 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
31242 #if !SQLITE_OS_WINCE
31243 { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
31244 #else
31245 { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
31246 #endif
31248 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
31249 LPFILETIME))aSyscall[30].pCurrent)
31251 #if defined(SQLITE_WIN32_HAS_ANSI)
31252 { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
31253 #else
31254 { "GetTempPathA", (SYSCALL)0, 0 },
31255 #endif
31257 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
31259 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31260 { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
31261 #else
31262 { "GetTempPathW", (SYSCALL)0, 0 },
31263 #endif
31265 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
31267 #if !SQLITE_OS_WINRT
31268 { "GetTickCount", (SYSCALL)GetTickCount, 0 },
31269 #else
31270 { "GetTickCount", (SYSCALL)0, 0 },
31271 #endif
31273 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
31275 #if defined(SQLITE_WIN32_HAS_ANSI)
31276 { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
31277 #else
31278 { "GetVersionExA", (SYSCALL)0, 0 },
31279 #endif
31281 #define osGetVersionExA ((BOOL(WINAPI*)( \
31282 LPOSVERSIONINFOA))aSyscall[34].pCurrent)
31284 { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
31286 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
31287 SIZE_T))aSyscall[35].pCurrent)
31289 #if !SQLITE_OS_WINRT
31290 { "HeapCreate", (SYSCALL)HeapCreate, 0 },
31291 #else
31292 { "HeapCreate", (SYSCALL)0, 0 },
31293 #endif
31295 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
31296 SIZE_T))aSyscall[36].pCurrent)
31298 #if !SQLITE_OS_WINRT
31299 { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
31300 #else
31301 { "HeapDestroy", (SYSCALL)0, 0 },
31302 #endif
31304 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
31306 { "HeapFree", (SYSCALL)HeapFree, 0 },
31308 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
31310 { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
31312 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
31313 SIZE_T))aSyscall[39].pCurrent)
31315 { "HeapSize", (SYSCALL)HeapSize, 0 },
31317 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
31318 LPCVOID))aSyscall[40].pCurrent)
31320 #if !SQLITE_OS_WINRT
31321 { "HeapValidate", (SYSCALL)HeapValidate, 0 },
31322 #else
31323 { "HeapValidate", (SYSCALL)0, 0 },
31324 #endif
31326 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
31327 LPCVOID))aSyscall[41].pCurrent)
31329 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
31330 { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
31331 #else
31332 { "LoadLibraryA", (SYSCALL)0, 0 },
31333 #endif
31335 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
31337 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
31338 !defined(SQLITE_OMIT_LOAD_EXTENSION)
31339 { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
31340 #else
31341 { "LoadLibraryW", (SYSCALL)0, 0 },
31342 #endif
31344 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
31346 #if !SQLITE_OS_WINRT
31347 { "LocalFree", (SYSCALL)LocalFree, 0 },
31348 #else
31349 { "LocalFree", (SYSCALL)0, 0 },
31350 #endif
31352 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
31354 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31355 { "LockFile", (SYSCALL)LockFile, 0 },
31356 #else
31357 { "LockFile", (SYSCALL)0, 0 },
31358 #endif
31360 #ifndef osLockFile
31361 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31362 DWORD))aSyscall[45].pCurrent)
31363 #endif
31365 #if !SQLITE_OS_WINCE
31366 { "LockFileEx", (SYSCALL)LockFileEx, 0 },
31367 #else
31368 { "LockFileEx", (SYSCALL)0, 0 },
31369 #endif
31371 #ifndef osLockFileEx
31372 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
31373 LPOVERLAPPED))aSyscall[46].pCurrent)
31374 #endif
31376 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
31377 { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
31378 #else
31379 { "MapViewOfFile", (SYSCALL)0, 0 },
31380 #endif
31382 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31383 SIZE_T))aSyscall[47].pCurrent)
31385 { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
31387 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
31388 int))aSyscall[48].pCurrent)
31390 { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
31392 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
31393 LARGE_INTEGER*))aSyscall[49].pCurrent)
31395 { "ReadFile", (SYSCALL)ReadFile, 0 },
31397 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
31398 LPOVERLAPPED))aSyscall[50].pCurrent)
31400 { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
31402 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
31404 #if !SQLITE_OS_WINRT
31405 { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
31406 #else
31407 { "SetFilePointer", (SYSCALL)0, 0 },
31408 #endif
31410 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
31411 DWORD))aSyscall[52].pCurrent)
31413 #if !SQLITE_OS_WINRT
31414 { "Sleep", (SYSCALL)Sleep, 0 },
31415 #else
31416 { "Sleep", (SYSCALL)0, 0 },
31417 #endif
31419 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
31421 { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
31423 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
31424 LPFILETIME))aSyscall[54].pCurrent)
31426 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31427 { "UnlockFile", (SYSCALL)UnlockFile, 0 },
31428 #else
31429 { "UnlockFile", (SYSCALL)0, 0 },
31430 #endif
31432 #ifndef osUnlockFile
31433 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31434 DWORD))aSyscall[55].pCurrent)
31435 #endif
31437 #if !SQLITE_OS_WINCE
31438 { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
31439 #else
31440 { "UnlockFileEx", (SYSCALL)0, 0 },
31441 #endif
31443 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31444 LPOVERLAPPED))aSyscall[56].pCurrent)
31446 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
31447 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
31448 #else
31449 { "UnmapViewOfFile", (SYSCALL)0, 0 },
31450 #endif
31452 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
31454 { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
31456 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
31457 LPCSTR,LPBOOL))aSyscall[58].pCurrent)
31459 { "WriteFile", (SYSCALL)WriteFile, 0 },
31461 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
31462 LPOVERLAPPED))aSyscall[59].pCurrent)
31464 #if SQLITE_OS_WINRT
31465 { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
31466 #else
31467 { "CreateEventExW", (SYSCALL)0, 0 },
31468 #endif
31470 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
31471 DWORD,DWORD))aSyscall[60].pCurrent)
31473 #if !SQLITE_OS_WINRT
31474 { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
31475 #else
31476 { "WaitForSingleObject", (SYSCALL)0, 0 },
31477 #endif
31479 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
31480 DWORD))aSyscall[61].pCurrent)
31482 #if SQLITE_OS_WINRT
31483 { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
31484 #else
31485 { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
31486 #endif
31488 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
31489 BOOL))aSyscall[62].pCurrent)
31491 #if SQLITE_OS_WINRT
31492 { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
31493 #else
31494 { "SetFilePointerEx", (SYSCALL)0, 0 },
31495 #endif
31497 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
31498 PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
31500 #if SQLITE_OS_WINRT
31501 { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
31502 #else
31503 { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
31504 #endif
31506 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
31507 FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
31509 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
31510 { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
31511 #else
31512 { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
31513 #endif
31515 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
31516 SIZE_T))aSyscall[65].pCurrent)
31518 #if SQLITE_OS_WINRT
31519 { "CreateFile2", (SYSCALL)CreateFile2, 0 },
31520 #else
31521 { "CreateFile2", (SYSCALL)0, 0 },
31522 #endif
31524 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
31525 LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
31527 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
31528 { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
31529 #else
31530 { "LoadPackagedLibrary", (SYSCALL)0, 0 },
31531 #endif
31533 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
31534 DWORD))aSyscall[67].pCurrent)
31536 #if SQLITE_OS_WINRT
31537 { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
31538 #else
31539 { "GetTickCount64", (SYSCALL)0, 0 },
31540 #endif
31542 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
31544 #if SQLITE_OS_WINRT
31545 { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
31546 #else
31547 { "GetNativeSystemInfo", (SYSCALL)0, 0 },
31548 #endif
31550 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
31551 LPSYSTEM_INFO))aSyscall[69].pCurrent)
31553 #if defined(SQLITE_WIN32_HAS_ANSI)
31554 { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
31555 #else
31556 { "OutputDebugStringA", (SYSCALL)0, 0 },
31557 #endif
31559 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
31561 #if defined(SQLITE_WIN32_HAS_WIDE)
31562 { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
31563 #else
31564 { "OutputDebugStringW", (SYSCALL)0, 0 },
31565 #endif
31567 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
31569 { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
31571 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
31573 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
31574 { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
31575 #else
31576 { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
31577 #endif
31579 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
31580 LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
31582 }; /* End of the overrideable system calls */
31585 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
31586 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
31587 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
31588 ** system call named zName.
31590 static int winSetSystemCall(
31591 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
31592 const char *zName, /* Name of system call to override */
31593 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
31595 unsigned int i;
31596 int rc = SQLITE_NOTFOUND;
31598 UNUSED_PARAMETER(pNotUsed);
31599 if( zName==0 ){
31600 /* If no zName is given, restore all system calls to their default
31601 ** settings and return NULL
31603 rc = SQLITE_OK;
31604 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31605 if( aSyscall[i].pDefault ){
31606 aSyscall[i].pCurrent = aSyscall[i].pDefault;
31609 }else{
31610 /* If zName is specified, operate on only the one system call
31611 ** specified.
31613 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31614 if( strcmp(zName, aSyscall[i].zName)==0 ){
31615 if( aSyscall[i].pDefault==0 ){
31616 aSyscall[i].pDefault = aSyscall[i].pCurrent;
31618 rc = SQLITE_OK;
31619 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
31620 aSyscall[i].pCurrent = pNewFunc;
31621 break;
31625 return rc;
31629 ** Return the value of a system call. Return NULL if zName is not a
31630 ** recognized system call name. NULL is also returned if the system call
31631 ** is currently undefined.
31633 static sqlite3_syscall_ptr winGetSystemCall(
31634 sqlite3_vfs *pNotUsed,
31635 const char *zName
31637 unsigned int i;
31639 UNUSED_PARAMETER(pNotUsed);
31640 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31641 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
31643 return 0;
31647 ** Return the name of the first system call after zName. If zName==NULL
31648 ** then return the name of the first system call. Return NULL if zName
31649 ** is the last system call or if zName is not the name of a valid
31650 ** system call.
31652 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
31653 int i = -1;
31655 UNUSED_PARAMETER(p);
31656 if( zName ){
31657 for(i=0; i<ArraySize(aSyscall)-1; i++){
31658 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
31661 for(i++; i<ArraySize(aSyscall); i++){
31662 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
31664 return 0;
31668 ** This function outputs the specified (ANSI) string to the Win32 debugger
31669 ** (if available).
31672 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
31673 char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
31674 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
31675 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
31676 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
31677 #if defined(SQLITE_WIN32_HAS_ANSI)
31678 if( nMin>0 ){
31679 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31680 memcpy(zDbgBuf, zBuf, nMin);
31681 osOutputDebugStringA(zDbgBuf);
31682 }else{
31683 osOutputDebugStringA(zBuf);
31685 #elif defined(SQLITE_WIN32_HAS_WIDE)
31686 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31687 if ( osMultiByteToWideChar(
31688 osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
31689 nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
31690 return;
31692 osOutputDebugStringW((LPCWSTR)zDbgBuf);
31693 #else
31694 if( nMin>0 ){
31695 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31696 memcpy(zDbgBuf, zBuf, nMin);
31697 fprintf(stderr, "%s", zDbgBuf);
31698 }else{
31699 fprintf(stderr, "%s", zBuf);
31701 #endif
31705 ** The following routine suspends the current thread for at least ms
31706 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
31708 #if SQLITE_OS_WINRT
31709 static HANDLE sleepObj = NULL;
31710 #endif
31712 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
31713 #if SQLITE_OS_WINRT
31714 if ( sleepObj==NULL ){
31715 sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
31716 SYNCHRONIZE);
31718 assert( sleepObj!=NULL );
31719 osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
31720 #else
31721 osSleep(milliseconds);
31722 #endif
31726 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31727 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
31729 ** Here is an interesting observation: Win95, Win98, and WinME lack
31730 ** the LockFileEx() API. But we can still statically link against that
31731 ** API as long as we don't call it when running Win95/98/ME. A call to
31732 ** this routine is used to determine if the host is Win95/98/ME or
31733 ** WinNT/2K/XP so that we will know whether or not we can safely call
31734 ** the LockFileEx() API.
31736 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
31737 # define isNT() (1)
31738 #elif !defined(SQLITE_WIN32_HAS_WIDE)
31739 # define isNT() (0)
31740 #else
31741 static int isNT(void){
31742 if( sqlite3_os_type==0 ){
31743 OSVERSIONINFOA sInfo;
31744 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31745 osGetVersionExA(&sInfo);
31746 sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31748 return sqlite3_os_type==2;
31750 #endif
31752 #ifdef SQLITE_WIN32_MALLOC
31754 ** Allocate nBytes of memory.
31756 static void *winMemMalloc(int nBytes){
31757 HANDLE hHeap;
31758 void *p;
31760 winMemAssertMagic();
31761 hHeap = winMemGetHeap();
31762 assert( hHeap!=0 );
31763 assert( hHeap!=INVALID_HANDLE_VALUE );
31764 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31765 assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31766 #endif
31767 assert( nBytes>=0 );
31768 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31769 if( !p ){
31770 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
31771 nBytes, osGetLastError(), (void*)hHeap);
31773 return p;
31777 ** Free memory.
31779 static void winMemFree(void *pPrior){
31780 HANDLE hHeap;
31782 winMemAssertMagic();
31783 hHeap = winMemGetHeap();
31784 assert( hHeap!=0 );
31785 assert( hHeap!=INVALID_HANDLE_VALUE );
31786 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31787 assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31788 #endif
31789 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
31790 if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
31791 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
31792 pPrior, osGetLastError(), (void*)hHeap);
31797 ** Change the size of an existing memory allocation
31799 static void *winMemRealloc(void *pPrior, int nBytes){
31800 HANDLE hHeap;
31801 void *p;
31803 winMemAssertMagic();
31804 hHeap = winMemGetHeap();
31805 assert( hHeap!=0 );
31806 assert( hHeap!=INVALID_HANDLE_VALUE );
31807 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31808 assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31809 #endif
31810 assert( nBytes>=0 );
31811 if( !pPrior ){
31812 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31813 }else{
31814 p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
31816 if( !p ){
31817 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
31818 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
31819 (void*)hHeap);
31821 return p;
31825 ** Return the size of an outstanding allocation, in bytes.
31827 static int winMemSize(void *p){
31828 HANDLE hHeap;
31829 SIZE_T n;
31831 winMemAssertMagic();
31832 hHeap = winMemGetHeap();
31833 assert( hHeap!=0 );
31834 assert( hHeap!=INVALID_HANDLE_VALUE );
31835 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31836 assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31837 #endif
31838 if( !p ) return 0;
31839 n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
31840 if( n==(SIZE_T)-1 ){
31841 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
31842 p, osGetLastError(), (void*)hHeap);
31843 return 0;
31845 return (int)n;
31849 ** Round up a request size to the next valid allocation size.
31851 static int winMemRoundup(int n){
31852 return n;
31856 ** Initialize this module.
31858 static int winMemInit(void *pAppData){
31859 winMemData *pWinMemData = (winMemData *)pAppData;
31861 if( !pWinMemData ) return SQLITE_ERROR;
31862 assert( pWinMemData->magic==WINMEM_MAGIC );
31864 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
31865 if( !pWinMemData->hHeap ){
31866 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
31867 SQLITE_WIN32_HEAP_INIT_SIZE,
31868 SQLITE_WIN32_HEAP_MAX_SIZE);
31869 if( !pWinMemData->hHeap ){
31870 sqlite3_log(SQLITE_NOMEM,
31871 "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
31872 osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
31873 SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
31874 return SQLITE_NOMEM;
31876 pWinMemData->bOwned = TRUE;
31877 assert( pWinMemData->bOwned );
31879 #else
31880 pWinMemData->hHeap = osGetProcessHeap();
31881 if( !pWinMemData->hHeap ){
31882 sqlite3_log(SQLITE_NOMEM,
31883 "failed to GetProcessHeap (%d)", osGetLastError());
31884 return SQLITE_NOMEM;
31886 pWinMemData->bOwned = FALSE;
31887 assert( !pWinMemData->bOwned );
31888 #endif
31889 assert( pWinMemData->hHeap!=0 );
31890 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31891 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31892 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31893 #endif
31894 return SQLITE_OK;
31898 ** Deinitialize this module.
31900 static void winMemShutdown(void *pAppData){
31901 winMemData *pWinMemData = (winMemData *)pAppData;
31903 if( !pWinMemData ) return;
31904 if( pWinMemData->hHeap ){
31905 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31906 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31907 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31908 #endif
31909 if( pWinMemData->bOwned ){
31910 if( !osHeapDestroy(pWinMemData->hHeap) ){
31911 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
31912 osGetLastError(), (void*)pWinMemData->hHeap);
31914 pWinMemData->bOwned = FALSE;
31916 pWinMemData->hHeap = NULL;
31921 ** Populate the low-level memory allocation function pointers in
31922 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
31923 ** arguments specify the block of memory to manage.
31925 ** This routine is only called by sqlite3_config(), and therefore
31926 ** is not required to be threadsafe (it is not).
31928 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
31929 static const sqlite3_mem_methods winMemMethods = {
31930 winMemMalloc,
31931 winMemFree,
31932 winMemRealloc,
31933 winMemSize,
31934 winMemRoundup,
31935 winMemInit,
31936 winMemShutdown,
31937 &win_mem_data
31939 return &winMemMethods;
31942 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
31943 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
31945 #endif /* SQLITE_WIN32_MALLOC */
31948 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
31950 ** Space to hold the returned string is obtained from malloc.
31952 static LPWSTR utf8ToUnicode(const char *zFilename){
31953 int nChar;
31954 LPWSTR zWideFilename;
31956 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31957 if( nChar==0 ){
31958 return 0;
31960 zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
31961 if( zWideFilename==0 ){
31962 return 0;
31964 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
31965 nChar);
31966 if( nChar==0 ){
31967 sqlite3_free(zWideFilename);
31968 zWideFilename = 0;
31970 return zWideFilename;
31974 ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
31975 ** obtained from sqlite3_malloc().
31977 static char *unicodeToUtf8(LPCWSTR zWideFilename){
31978 int nByte;
31979 char *zFilename;
31981 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31982 if( nByte == 0 ){
31983 return 0;
31985 zFilename = sqlite3MallocZero( nByte );
31986 if( zFilename==0 ){
31987 return 0;
31989 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31990 0, 0);
31991 if( nByte == 0 ){
31992 sqlite3_free(zFilename);
31993 zFilename = 0;
31995 return zFilename;
31999 ** Convert an ANSI string to Microsoft Unicode, based on the
32000 ** current codepage settings for file apis.
32002 ** Space to hold the returned string is obtained
32003 ** from sqlite3_malloc.
32005 static LPWSTR mbcsToUnicode(const char *zFilename){
32006 int nByte;
32007 LPWSTR zMbcsFilename;
32008 int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
32010 nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
32011 0)*sizeof(WCHAR);
32012 if( nByte==0 ){
32013 return 0;
32015 zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
32016 if( zMbcsFilename==0 ){
32017 return 0;
32019 nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
32020 nByte);
32021 if( nByte==0 ){
32022 sqlite3_free(zMbcsFilename);
32023 zMbcsFilename = 0;
32025 return zMbcsFilename;
32029 ** Convert Microsoft Unicode to multi-byte character string, based on the
32030 ** user's ANSI codepage.
32032 ** Space to hold the returned string is obtained from
32033 ** sqlite3_malloc().
32035 static char *unicodeToMbcs(LPCWSTR zWideFilename){
32036 int nByte;
32037 char *zFilename;
32038 int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
32040 nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
32041 if( nByte == 0 ){
32042 return 0;
32044 zFilename = sqlite3MallocZero( nByte );
32045 if( zFilename==0 ){
32046 return 0;
32048 nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
32049 nByte, 0, 0);
32050 if( nByte == 0 ){
32051 sqlite3_free(zFilename);
32052 zFilename = 0;
32054 return zFilename;
32058 ** Convert multibyte character string to UTF-8. Space to hold the
32059 ** returned string is obtained from sqlite3_malloc().
32061 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
32062 char *zFilenameUtf8;
32063 LPWSTR zTmpWide;
32065 zTmpWide = mbcsToUnicode(zFilename);
32066 if( zTmpWide==0 ){
32067 return 0;
32069 zFilenameUtf8 = unicodeToUtf8(zTmpWide);
32070 sqlite3_free(zTmpWide);
32071 return zFilenameUtf8;
32075 ** Convert UTF-8 to multibyte character string. Space to hold the
32076 ** returned string is obtained from sqlite3_malloc().
32078 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
32079 char *zFilenameMbcs;
32080 LPWSTR zTmpWide;
32082 zTmpWide = utf8ToUnicode(zFilename);
32083 if( zTmpWide==0 ){
32084 return 0;
32086 zFilenameMbcs = unicodeToMbcs(zTmpWide);
32087 sqlite3_free(zTmpWide);
32088 return zFilenameMbcs;
32092 ** This function sets the data directory or the temporary directory based on
32093 ** the provided arguments. The type argument must be 1 in order to set the
32094 ** data directory or 2 in order to set the temporary directory. The zValue
32095 ** argument is the name of the directory to use. The return value will be
32096 ** SQLITE_OK if successful.
32098 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
32099 char **ppDirectory = 0;
32100 #ifndef SQLITE_OMIT_AUTOINIT
32101 int rc = sqlite3_initialize();
32102 if( rc ) return rc;
32103 #endif
32104 if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
32105 ppDirectory = &sqlite3_data_directory;
32106 }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
32107 ppDirectory = &sqlite3_temp_directory;
32109 assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
32110 || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
32112 assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
32113 if( ppDirectory ){
32114 char *zValueUtf8 = 0;
32115 if( zValue && zValue[0] ){
32116 zValueUtf8 = unicodeToUtf8(zValue);
32117 if ( zValueUtf8==0 ){
32118 return SQLITE_NOMEM;
32121 sqlite3_free(*ppDirectory);
32122 *ppDirectory = zValueUtf8;
32123 return SQLITE_OK;
32125 return SQLITE_ERROR;
32129 ** The return value of getLastErrorMsg
32130 ** is zero if the error message fits in the buffer, or non-zero
32131 ** otherwise (if the message was truncated).
32133 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
32134 /* FormatMessage returns 0 on failure. Otherwise it
32135 ** returns the number of TCHARs written to the output
32136 ** buffer, excluding the terminating null char.
32138 DWORD dwLen = 0;
32139 char *zOut = 0;
32141 if( isNT() ){
32142 #if SQLITE_OS_WINRT
32143 WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
32144 dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
32145 FORMAT_MESSAGE_IGNORE_INSERTS,
32146 NULL,
32147 lastErrno,
32149 zTempWide,
32150 MAX_PATH,
32152 #else
32153 LPWSTR zTempWide = NULL;
32154 dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
32155 FORMAT_MESSAGE_FROM_SYSTEM |
32156 FORMAT_MESSAGE_IGNORE_INSERTS,
32157 NULL,
32158 lastErrno,
32160 (LPWSTR) &zTempWide,
32163 #endif
32164 if( dwLen > 0 ){
32165 /* allocate a buffer and convert to UTF8 */
32166 sqlite3BeginBenignMalloc();
32167 zOut = unicodeToUtf8(zTempWide);
32168 sqlite3EndBenignMalloc();
32169 #if !SQLITE_OS_WINRT
32170 /* free the system buffer allocated by FormatMessage */
32171 osLocalFree(zTempWide);
32172 #endif
32175 #ifdef SQLITE_WIN32_HAS_ANSI
32176 else{
32177 char *zTemp = NULL;
32178 dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
32179 FORMAT_MESSAGE_FROM_SYSTEM |
32180 FORMAT_MESSAGE_IGNORE_INSERTS,
32181 NULL,
32182 lastErrno,
32184 (LPSTR) &zTemp,
32187 if( dwLen > 0 ){
32188 /* allocate a buffer and convert to UTF8 */
32189 sqlite3BeginBenignMalloc();
32190 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
32191 sqlite3EndBenignMalloc();
32192 /* free the system buffer allocated by FormatMessage */
32193 osLocalFree(zTemp);
32196 #endif
32197 if( 0 == dwLen ){
32198 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
32199 }else{
32200 /* copy a maximum of nBuf chars to output buffer */
32201 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
32202 /* free the UTF8 buffer */
32203 sqlite3_free(zOut);
32205 return 0;
32210 ** This function - winLogErrorAtLine() - is only ever called via the macro
32211 ** winLogError().
32213 ** This routine is invoked after an error occurs in an OS function.
32214 ** It logs a message using sqlite3_log() containing the current value of
32215 ** error code and, if possible, the human-readable equivalent from
32216 ** FormatMessage.
32218 ** The first argument passed to the macro should be the error code that
32219 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
32220 ** The two subsequent arguments should be the name of the OS function that
32221 ** failed and the associated file-system path, if any.
32223 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
32224 static int winLogErrorAtLine(
32225 int errcode, /* SQLite error code */
32226 DWORD lastErrno, /* Win32 last error */
32227 const char *zFunc, /* Name of OS function that failed */
32228 const char *zPath, /* File path associated with error */
32229 int iLine /* Source line number where error occurred */
32231 char zMsg[500]; /* Human readable error text */
32232 int i; /* Loop counter */
32234 zMsg[0] = 0;
32235 getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
32236 assert( errcode!=SQLITE_OK );
32237 if( zPath==0 ) zPath = "";
32238 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
32239 zMsg[i] = 0;
32240 sqlite3_log(errcode,
32241 "os_win.c:%d: (%lu) %s(%s) - %s",
32242 iLine, lastErrno, zFunc, zPath, zMsg
32245 return errcode;
32249 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
32250 ** will be retried following a locking error - probably caused by
32251 ** antivirus software. Also the initial delay before the first retry.
32252 ** The delay increases linearly with each retry.
32254 #ifndef SQLITE_WIN32_IOERR_RETRY
32255 # define SQLITE_WIN32_IOERR_RETRY 10
32256 #endif
32257 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
32258 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
32259 #endif
32260 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
32261 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
32264 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
32265 ** to see if it should be retried. Return TRUE to retry. Return FALSE
32266 ** to give up with an error.
32268 static int retryIoerr(int *pnRetry, DWORD *pError){
32269 DWORD e = osGetLastError();
32270 if( *pnRetry>=win32IoerrRetry ){
32271 if( pError ){
32272 *pError = e;
32274 return 0;
32276 if( e==ERROR_ACCESS_DENIED ||
32277 e==ERROR_LOCK_VIOLATION ||
32278 e==ERROR_SHARING_VIOLATION ){
32279 sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
32280 ++*pnRetry;
32281 return 1;
32283 if( pError ){
32284 *pError = e;
32286 return 0;
32290 ** Log a I/O error retry episode.
32292 static void logIoerr(int nRetry){
32293 if( nRetry ){
32294 sqlite3_log(SQLITE_IOERR,
32295 "delayed %dms for lock/sharing conflict",
32296 win32IoerrRetryDelay*nRetry*(nRetry+1)/2
32301 #if SQLITE_OS_WINCE
32302 /*************************************************************************
32303 ** This section contains code for WinCE only.
32305 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
32307 ** The MSVC CRT on Windows CE may not have a localtime() function. So
32308 ** create a substitute.
32310 /* #include <time.h> */
32311 struct tm *__cdecl localtime(const time_t *t)
32313 static struct tm y;
32314 FILETIME uTm, lTm;
32315 SYSTEMTIME pTm;
32316 sqlite3_int64 t64;
32317 t64 = *t;
32318 t64 = (t64 + 11644473600)*10000000;
32319 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
32320 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
32321 osFileTimeToLocalFileTime(&uTm,&lTm);
32322 osFileTimeToSystemTime(&lTm,&pTm);
32323 y.tm_year = pTm.wYear - 1900;
32324 y.tm_mon = pTm.wMonth - 1;
32325 y.tm_wday = pTm.wDayOfWeek;
32326 y.tm_mday = pTm.wDay;
32327 y.tm_hour = pTm.wHour;
32328 y.tm_min = pTm.wMinute;
32329 y.tm_sec = pTm.wSecond;
32330 return &y;
32332 #endif
32334 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
32337 ** Acquire a lock on the handle h
32339 static void winceMutexAcquire(HANDLE h){
32340 DWORD dwErr;
32341 do {
32342 dwErr = osWaitForSingleObject(h, INFINITE);
32343 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
32346 ** Release a lock acquired by winceMutexAcquire()
32348 #define winceMutexRelease(h) ReleaseMutex(h)
32351 ** Create the mutex and shared memory used for locking in the file
32352 ** descriptor pFile
32354 static int winceCreateLock(const char *zFilename, winFile *pFile){
32355 LPWSTR zTok;
32356 LPWSTR zName;
32357 DWORD lastErrno;
32358 BOOL bLogged = FALSE;
32359 BOOL bInit = TRUE;
32361 zName = utf8ToUnicode(zFilename);
32362 if( zName==0 ){
32363 /* out of memory */
32364 return SQLITE_IOERR_NOMEM;
32367 /* Initialize the local lockdata */
32368 memset(&pFile->local, 0, sizeof(pFile->local));
32370 /* Replace the backslashes from the filename and lowercase it
32371 ** to derive a mutex name. */
32372 zTok = osCharLowerW(zName);
32373 for (;*zTok;zTok++){
32374 if (*zTok == '\\') *zTok = '_';
32377 /* Create/open the named mutex */
32378 pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
32379 if (!pFile->hMutex){
32380 pFile->lastErrno = osGetLastError();
32381 winLogError(SQLITE_IOERR, pFile->lastErrno,
32382 "winceCreateLock1", zFilename);
32383 sqlite3_free(zName);
32384 return SQLITE_IOERR;
32387 /* Acquire the mutex before continuing */
32388 winceMutexAcquire(pFile->hMutex);
32390 /* Since the names of named mutexes, semaphores, file mappings etc are
32391 ** case-sensitive, take advantage of that by uppercasing the mutex name
32392 ** and using that as the shared filemapping name.
32394 osCharUpperW(zName);
32395 pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
32396 PAGE_READWRITE, 0, sizeof(winceLock),
32397 zName);
32399 /* Set a flag that indicates we're the first to create the memory so it
32400 ** must be zero-initialized */
32401 lastErrno = osGetLastError();
32402 if (lastErrno == ERROR_ALREADY_EXISTS){
32403 bInit = FALSE;
32406 sqlite3_free(zName);
32408 /* If we succeeded in making the shared memory handle, map it. */
32409 if( pFile->hShared ){
32410 pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
32411 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
32412 /* If mapping failed, close the shared memory handle and erase it */
32413 if( !pFile->shared ){
32414 pFile->lastErrno = osGetLastError();
32415 winLogError(SQLITE_IOERR, pFile->lastErrno,
32416 "winceCreateLock2", zFilename);
32417 bLogged = TRUE;
32418 osCloseHandle(pFile->hShared);
32419 pFile->hShared = NULL;
32423 /* If shared memory could not be created, then close the mutex and fail */
32424 if( pFile->hShared==NULL ){
32425 if( !bLogged ){
32426 pFile->lastErrno = lastErrno;
32427 winLogError(SQLITE_IOERR, pFile->lastErrno,
32428 "winceCreateLock3", zFilename);
32429 bLogged = TRUE;
32431 winceMutexRelease(pFile->hMutex);
32432 osCloseHandle(pFile->hMutex);
32433 pFile->hMutex = NULL;
32434 return SQLITE_IOERR;
32437 /* Initialize the shared memory if we're supposed to */
32438 if( bInit ){
32439 memset(pFile->shared, 0, sizeof(winceLock));
32442 winceMutexRelease(pFile->hMutex);
32443 return SQLITE_OK;
32447 ** Destroy the part of winFile that deals with wince locks
32449 static void winceDestroyLock(winFile *pFile){
32450 if (pFile->hMutex){
32451 /* Acquire the mutex */
32452 winceMutexAcquire(pFile->hMutex);
32454 /* The following blocks should probably assert in debug mode, but they
32455 are to cleanup in case any locks remained open */
32456 if (pFile->local.nReaders){
32457 pFile->shared->nReaders --;
32459 if (pFile->local.bReserved){
32460 pFile->shared->bReserved = FALSE;
32462 if (pFile->local.bPending){
32463 pFile->shared->bPending = FALSE;
32465 if (pFile->local.bExclusive){
32466 pFile->shared->bExclusive = FALSE;
32469 /* De-reference and close our copy of the shared memory handle */
32470 osUnmapViewOfFile(pFile->shared);
32471 osCloseHandle(pFile->hShared);
32473 /* Done with the mutex */
32474 winceMutexRelease(pFile->hMutex);
32475 osCloseHandle(pFile->hMutex);
32476 pFile->hMutex = NULL;
32481 ** An implementation of the LockFile() API of Windows for CE
32483 static BOOL winceLockFile(
32484 LPHANDLE phFile,
32485 DWORD dwFileOffsetLow,
32486 DWORD dwFileOffsetHigh,
32487 DWORD nNumberOfBytesToLockLow,
32488 DWORD nNumberOfBytesToLockHigh
32490 winFile *pFile = HANDLE_TO_WINFILE(phFile);
32491 BOOL bReturn = FALSE;
32493 UNUSED_PARAMETER(dwFileOffsetHigh);
32494 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
32496 if (!pFile->hMutex) return TRUE;
32497 winceMutexAcquire(pFile->hMutex);
32499 /* Wanting an exclusive lock? */
32500 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
32501 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
32502 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
32503 pFile->shared->bExclusive = TRUE;
32504 pFile->local.bExclusive = TRUE;
32505 bReturn = TRUE;
32509 /* Want a read-only lock? */
32510 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
32511 nNumberOfBytesToLockLow == 1){
32512 if (pFile->shared->bExclusive == 0){
32513 pFile->local.nReaders ++;
32514 if (pFile->local.nReaders == 1){
32515 pFile->shared->nReaders ++;
32517 bReturn = TRUE;
32521 /* Want a pending lock? */
32522 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
32523 && nNumberOfBytesToLockLow == 1){
32524 /* If no pending lock has been acquired, then acquire it */
32525 if (pFile->shared->bPending == 0) {
32526 pFile->shared->bPending = TRUE;
32527 pFile->local.bPending = TRUE;
32528 bReturn = TRUE;
32532 /* Want a reserved lock? */
32533 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
32534 && nNumberOfBytesToLockLow == 1){
32535 if (pFile->shared->bReserved == 0) {
32536 pFile->shared->bReserved = TRUE;
32537 pFile->local.bReserved = TRUE;
32538 bReturn = TRUE;
32542 winceMutexRelease(pFile->hMutex);
32543 return bReturn;
32547 ** An implementation of the UnlockFile API of Windows for CE
32549 static BOOL winceUnlockFile(
32550 LPHANDLE phFile,
32551 DWORD dwFileOffsetLow,
32552 DWORD dwFileOffsetHigh,
32553 DWORD nNumberOfBytesToUnlockLow,
32554 DWORD nNumberOfBytesToUnlockHigh
32556 winFile *pFile = HANDLE_TO_WINFILE(phFile);
32557 BOOL bReturn = FALSE;
32559 UNUSED_PARAMETER(dwFileOffsetHigh);
32560 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
32562 if (!pFile->hMutex) return TRUE;
32563 winceMutexAcquire(pFile->hMutex);
32565 /* Releasing a reader lock or an exclusive lock */
32566 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
32567 /* Did we have an exclusive lock? */
32568 if (pFile->local.bExclusive){
32569 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
32570 pFile->local.bExclusive = FALSE;
32571 pFile->shared->bExclusive = FALSE;
32572 bReturn = TRUE;
32575 /* Did we just have a reader lock? */
32576 else if (pFile->local.nReaders){
32577 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
32578 || nNumberOfBytesToUnlockLow == 1);
32579 pFile->local.nReaders --;
32580 if (pFile->local.nReaders == 0)
32582 pFile->shared->nReaders --;
32584 bReturn = TRUE;
32588 /* Releasing a pending lock */
32589 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
32590 && nNumberOfBytesToUnlockLow == 1){
32591 if (pFile->local.bPending){
32592 pFile->local.bPending = FALSE;
32593 pFile->shared->bPending = FALSE;
32594 bReturn = TRUE;
32597 /* Releasing a reserved lock */
32598 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
32599 && nNumberOfBytesToUnlockLow == 1){
32600 if (pFile->local.bReserved) {
32601 pFile->local.bReserved = FALSE;
32602 pFile->shared->bReserved = FALSE;
32603 bReturn = TRUE;
32607 winceMutexRelease(pFile->hMutex);
32608 return bReturn;
32611 ** End of the special code for wince
32612 *****************************************************************************/
32613 #endif /* SQLITE_OS_WINCE */
32616 ** Lock a file region.
32618 static BOOL winLockFile(
32619 LPHANDLE phFile,
32620 DWORD flags,
32621 DWORD offsetLow,
32622 DWORD offsetHigh,
32623 DWORD numBytesLow,
32624 DWORD numBytesHigh
32626 #if SQLITE_OS_WINCE
32628 ** NOTE: Windows CE is handled differently here due its lack of the Win32
32629 ** API LockFile.
32631 return winceLockFile(phFile, offsetLow, offsetHigh,
32632 numBytesLow, numBytesHigh);
32633 #else
32634 if( isNT() ){
32635 OVERLAPPED ovlp;
32636 memset(&ovlp, 0, sizeof(OVERLAPPED));
32637 ovlp.Offset = offsetLow;
32638 ovlp.OffsetHigh = offsetHigh;
32639 return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
32640 }else{
32641 return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32642 numBytesHigh);
32644 #endif
32648 ** Unlock a file region.
32650 static BOOL winUnlockFile(
32651 LPHANDLE phFile,
32652 DWORD offsetLow,
32653 DWORD offsetHigh,
32654 DWORD numBytesLow,
32655 DWORD numBytesHigh
32657 #if SQLITE_OS_WINCE
32659 ** NOTE: Windows CE is handled differently here due its lack of the Win32
32660 ** API UnlockFile.
32662 return winceUnlockFile(phFile, offsetLow, offsetHigh,
32663 numBytesLow, numBytesHigh);
32664 #else
32665 if( isNT() ){
32666 OVERLAPPED ovlp;
32667 memset(&ovlp, 0, sizeof(OVERLAPPED));
32668 ovlp.Offset = offsetLow;
32669 ovlp.OffsetHigh = offsetHigh;
32670 return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
32671 }else{
32672 return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32673 numBytesHigh);
32675 #endif
32678 /*****************************************************************************
32679 ** The next group of routines implement the I/O methods specified
32680 ** by the sqlite3_io_methods object.
32681 ******************************************************************************/
32684 ** Some Microsoft compilers lack this definition.
32686 #ifndef INVALID_SET_FILE_POINTER
32687 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
32688 #endif
32691 ** Move the current position of the file handle passed as the first
32692 ** argument to offset iOffset within the file. If successful, return 0.
32693 ** Otherwise, set pFile->lastErrno and return non-zero.
32695 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
32696 #if !SQLITE_OS_WINRT
32697 LONG upperBits; /* Most sig. 32 bits of new offset */
32698 LONG lowerBits; /* Least sig. 32 bits of new offset */
32699 DWORD dwRet; /* Value returned by SetFilePointer() */
32700 DWORD lastErrno; /* Value returned by GetLastError() */
32702 OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
32704 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
32705 lowerBits = (LONG)(iOffset & 0xffffffff);
32707 /* API oddity: If successful, SetFilePointer() returns a dword
32708 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
32709 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
32710 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
32711 ** whether an error has actually occurred, it is also necessary to call
32712 ** GetLastError().
32714 dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
32716 if( (dwRet==INVALID_SET_FILE_POINTER
32717 && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
32718 pFile->lastErrno = lastErrno;
32719 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32720 "seekWinFile", pFile->zPath);
32721 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
32722 return 1;
32725 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
32726 return 0;
32727 #else
32729 ** Same as above, except that this implementation works for WinRT.
32732 LARGE_INTEGER x; /* The new offset */
32733 BOOL bRet; /* Value returned by SetFilePointerEx() */
32735 x.QuadPart = iOffset;
32736 bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
32738 if(!bRet){
32739 pFile->lastErrno = osGetLastError();
32740 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32741 "seekWinFile", pFile->zPath);
32742 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
32743 return 1;
32746 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
32747 return 0;
32748 #endif
32751 #if SQLITE_MAX_MMAP_SIZE>0
32752 /* Forward references to VFS methods */
32753 static int winUnmapfile(winFile*);
32754 #endif
32757 ** Close a file.
32759 ** It is reported that an attempt to close a handle might sometimes
32760 ** fail. This is a very unreasonable result, but Windows is notorious
32761 ** for being unreasonable so I do not doubt that it might happen. If
32762 ** the close fails, we pause for 100 milliseconds and try again. As
32763 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
32764 ** giving up and returning an error.
32766 #define MX_CLOSE_ATTEMPT 3
32767 static int winClose(sqlite3_file *id){
32768 int rc, cnt = 0;
32769 winFile *pFile = (winFile*)id;
32771 assert( id!=0 );
32772 #ifndef SQLITE_OMIT_WAL
32773 assert( pFile->pShm==0 );
32774 #endif
32775 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
32776 OSTRACE(("CLOSE file=%p\n", pFile->h));
32778 #if SQLITE_MAX_MMAP_SIZE>0
32779 rc = winUnmapfile(pFile);
32780 if( rc!=SQLITE_OK ) return rc;
32781 #endif
32784 rc = osCloseHandle(pFile->h);
32785 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
32786 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
32787 #if SQLITE_OS_WINCE
32788 #define WINCE_DELETION_ATTEMPTS 3
32789 winceDestroyLock(pFile);
32790 if( pFile->zDeleteOnClose ){
32791 int cnt = 0;
32792 while(
32793 osDeleteFileW(pFile->zDeleteOnClose)==0
32794 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
32795 && cnt++ < WINCE_DELETION_ATTEMPTS
32797 sqlite3_win32_sleep(100); /* Wait a little before trying again */
32799 sqlite3_free(pFile->zDeleteOnClose);
32801 #endif
32802 if( rc ){
32803 pFile->h = NULL;
32805 OpenCounter(-1);
32806 OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
32807 return rc ? SQLITE_OK
32808 : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
32809 "winClose", pFile->zPath);
32813 ** Read data from a file into a buffer. Return SQLITE_OK if all
32814 ** bytes were read successfully and SQLITE_IOERR if anything goes
32815 ** wrong.
32817 static int winRead(
32818 sqlite3_file *id, /* File to read from */
32819 void *pBuf, /* Write content into this buffer */
32820 int amt, /* Number of bytes to read */
32821 sqlite3_int64 offset /* Begin reading at this offset */
32823 #if !SQLITE_OS_WINCE
32824 OVERLAPPED overlapped; /* The offset for ReadFile. */
32825 #endif
32826 winFile *pFile = (winFile*)id; /* file handle */
32827 DWORD nRead; /* Number of bytes actually read from file */
32828 int nRetry = 0; /* Number of retrys */
32830 assert( id!=0 );
32831 assert( amt>0 );
32832 assert( offset>=0 );
32833 SimulateIOError(return SQLITE_IOERR_READ);
32834 OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
32835 pFile->h, pBuf, amt, offset, pFile->locktype));
32837 #if SQLITE_MAX_MMAP_SIZE>0
32838 /* Deal with as much of this read request as possible by transfering
32839 ** data from the memory mapping using memcpy(). */
32840 if( offset<pFile->mmapSize ){
32841 if( offset+amt <= pFile->mmapSize ){
32842 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
32843 OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
32844 return SQLITE_OK;
32845 }else{
32846 int nCopy = (int)(pFile->mmapSize - offset);
32847 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
32848 pBuf = &((u8 *)pBuf)[nCopy];
32849 amt -= nCopy;
32850 offset += nCopy;
32853 #endif
32855 #if SQLITE_OS_WINCE
32856 if( seekWinFile(pFile, offset) ){
32857 OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
32858 return SQLITE_FULL;
32860 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
32861 #else
32862 memset(&overlapped, 0, sizeof(OVERLAPPED));
32863 overlapped.Offset = (LONG)(offset & 0xffffffff);
32864 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32865 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
32866 osGetLastError()!=ERROR_HANDLE_EOF ){
32867 #endif
32868 DWORD lastErrno;
32869 if( retryIoerr(&nRetry, &lastErrno) ) continue;
32870 pFile->lastErrno = lastErrno;
32871 OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
32872 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
32873 "winRead", pFile->zPath);
32875 logIoerr(nRetry);
32876 if( nRead<(DWORD)amt ){
32877 /* Unread parts of the buffer must be zero-filled */
32878 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
32879 OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
32880 return SQLITE_IOERR_SHORT_READ;
32883 OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
32884 return SQLITE_OK;
32888 ** Write data from a buffer into a file. Return SQLITE_OK on success
32889 ** or some other error code on failure.
32891 static int winWrite(
32892 sqlite3_file *id, /* File to write into */
32893 const void *pBuf, /* The bytes to be written */
32894 int amt, /* Number of bytes to write */
32895 sqlite3_int64 offset /* Offset into the file to begin writing at */
32897 int rc = 0; /* True if error has occurred, else false */
32898 winFile *pFile = (winFile*)id; /* File handle */
32899 int nRetry = 0; /* Number of retries */
32901 assert( amt>0 );
32902 assert( pFile );
32903 SimulateIOError(return SQLITE_IOERR_WRITE);
32904 SimulateDiskfullError(return SQLITE_FULL);
32906 OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
32907 pFile->h, pBuf, amt, offset, pFile->locktype));
32909 #if SQLITE_MAX_MMAP_SIZE>0
32910 /* Deal with as much of this write request as possible by transfering
32911 ** data from the memory mapping using memcpy(). */
32912 if( offset<pFile->mmapSize ){
32913 if( offset+amt <= pFile->mmapSize ){
32914 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
32915 OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
32916 return SQLITE_OK;
32917 }else{
32918 int nCopy = (int)(pFile->mmapSize - offset);
32919 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
32920 pBuf = &((u8 *)pBuf)[nCopy];
32921 amt -= nCopy;
32922 offset += nCopy;
32925 #endif
32927 #if SQLITE_OS_WINCE
32928 rc = seekWinFile(pFile, offset);
32929 if( rc==0 ){
32930 #else
32932 #endif
32933 #if !SQLITE_OS_WINCE
32934 OVERLAPPED overlapped; /* The offset for WriteFile. */
32935 #endif
32936 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
32937 int nRem = amt; /* Number of bytes yet to be written */
32938 DWORD nWrite; /* Bytes written by each WriteFile() call */
32939 DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
32941 #if !SQLITE_OS_WINCE
32942 memset(&overlapped, 0, sizeof(OVERLAPPED));
32943 overlapped.Offset = (LONG)(offset & 0xffffffff);
32944 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32945 #endif
32947 while( nRem>0 ){
32948 #if SQLITE_OS_WINCE
32949 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
32950 #else
32951 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
32952 #endif
32953 if( retryIoerr(&nRetry, &lastErrno) ) continue;
32954 break;
32956 assert( nWrite==0 || nWrite<=(DWORD)nRem );
32957 if( nWrite==0 || nWrite>(DWORD)nRem ){
32958 lastErrno = osGetLastError();
32959 break;
32961 #if !SQLITE_OS_WINCE
32962 offset += nWrite;
32963 overlapped.Offset = (LONG)(offset & 0xffffffff);
32964 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32965 #endif
32966 aRem += nWrite;
32967 nRem -= nWrite;
32969 if( nRem>0 ){
32970 pFile->lastErrno = lastErrno;
32971 rc = 1;
32975 if( rc ){
32976 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
32977 || ( pFile->lastErrno==ERROR_DISK_FULL )){
32978 OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
32979 return SQLITE_FULL;
32981 OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
32982 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
32983 "winWrite", pFile->zPath);
32984 }else{
32985 logIoerr(nRetry);
32987 OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
32988 return SQLITE_OK;
32992 ** Truncate an open file to a specified size
32994 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
32995 winFile *pFile = (winFile*)id; /* File handle object */
32996 int rc = SQLITE_OK; /* Return code for this function */
32997 DWORD lastErrno;
32999 assert( pFile );
33000 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
33001 OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
33002 pFile->h, nByte, pFile->locktype));
33004 /* If the user has configured a chunk-size for this file, truncate the
33005 ** file so that it consists of an integer number of chunks (i.e. the
33006 ** actual file size after the operation may be larger than the requested
33007 ** size).
33009 if( pFile->szChunk>0 ){
33010 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
33013 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
33014 if( seekWinFile(pFile, nByte) ){
33015 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33016 "winTruncate1", pFile->zPath);
33017 }else if( 0==osSetEndOfFile(pFile->h) &&
33018 ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
33019 pFile->lastErrno = lastErrno;
33020 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33021 "winTruncate2", pFile->zPath);
33024 #if SQLITE_MAX_MMAP_SIZE>0
33025 /* If the file was truncated to a size smaller than the currently
33026 ** mapped region, reduce the effective mapping size as well. SQLite will
33027 ** use read() and write() to access data beyond this point from now on.
33029 if( pFile->pMapRegion && nByte<pFile->mmapSize ){
33030 pFile->mmapSize = nByte;
33032 #endif
33034 OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
33035 return rc;
33038 #ifdef SQLITE_TEST
33040 ** Count the number of fullsyncs and normal syncs. This is used to test
33041 ** that syncs and fullsyncs are occuring at the right times.
33043 SQLITE_API int sqlite3_sync_count = 0;
33044 SQLITE_API int sqlite3_fullsync_count = 0;
33045 #endif
33048 ** Make sure all writes to a particular file are committed to disk.
33050 static int winSync(sqlite3_file *id, int flags){
33051 #ifndef SQLITE_NO_SYNC
33053 ** Used only when SQLITE_NO_SYNC is not defined.
33055 BOOL rc;
33056 #endif
33057 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
33058 (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
33060 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
33061 ** OSTRACE() macros.
33063 winFile *pFile = (winFile*)id;
33064 #else
33065 UNUSED_PARAMETER(id);
33066 #endif
33068 assert( pFile );
33069 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
33070 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
33071 || (flags&0x0F)==SQLITE_SYNC_FULL
33074 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
33075 ** line is to test that doing so does not cause any problems.
33077 SimulateDiskfullError( return SQLITE_FULL );
33079 OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
33080 pFile->h, flags, pFile->locktype));
33082 #ifndef SQLITE_TEST
33083 UNUSED_PARAMETER(flags);
33084 #else
33085 if( (flags&0x0F)==SQLITE_SYNC_FULL ){
33086 sqlite3_fullsync_count++;
33088 sqlite3_sync_count++;
33089 #endif
33091 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
33092 ** no-op
33094 #ifdef SQLITE_NO_SYNC
33095 return SQLITE_OK;
33096 #else
33097 rc = osFlushFileBuffers(pFile->h);
33098 SimulateIOError( rc=FALSE );
33099 if( rc ){
33100 OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
33101 return SQLITE_OK;
33102 }else{
33103 pFile->lastErrno = osGetLastError();
33104 OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
33105 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
33106 "winSync", pFile->zPath);
33108 #endif
33112 ** Determine the current size of a file in bytes
33114 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
33115 winFile *pFile = (winFile*)id;
33116 int rc = SQLITE_OK;
33118 assert( id!=0 );
33119 assert( pSize!=0 );
33120 SimulateIOError(return SQLITE_IOERR_FSTAT);
33121 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
33123 #if SQLITE_OS_WINRT
33125 FILE_STANDARD_INFO info;
33126 if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
33127 &info, sizeof(info)) ){
33128 *pSize = info.EndOfFile.QuadPart;
33129 }else{
33130 pFile->lastErrno = osGetLastError();
33131 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33132 "winFileSize", pFile->zPath);
33135 #else
33137 DWORD upperBits;
33138 DWORD lowerBits;
33139 DWORD lastErrno;
33141 lowerBits = osGetFileSize(pFile->h, &upperBits);
33142 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
33143 if( (lowerBits == INVALID_FILE_SIZE)
33144 && ((lastErrno = osGetLastError())!=NO_ERROR) ){
33145 pFile->lastErrno = lastErrno;
33146 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33147 "winFileSize", pFile->zPath);
33150 #endif
33151 OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
33152 pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
33153 return rc;
33157 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
33159 #ifndef LOCKFILE_FAIL_IMMEDIATELY
33160 # define LOCKFILE_FAIL_IMMEDIATELY 1
33161 #endif
33163 #ifndef LOCKFILE_EXCLUSIVE_LOCK
33164 # define LOCKFILE_EXCLUSIVE_LOCK 2
33165 #endif
33168 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
33169 ** When the LockFile function was used, it was always expected to fail
33170 ** immediately if the lock could not be obtained. Also, it always expected to
33171 ** obtain an exclusive lock. These flags are used with the LockFileEx function
33172 ** and reflect those expectations; therefore, they should not be changed.
33174 #ifndef SQLITE_LOCKFILE_FLAGS
33175 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
33176 LOCKFILE_EXCLUSIVE_LOCK)
33177 #endif
33180 ** Currently, SQLite never calls the LockFileEx function without wanting the
33181 ** call to fail immediately if the lock cannot be obtained.
33183 #ifndef SQLITE_LOCKFILEEX_FLAGS
33184 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
33185 #endif
33188 ** Acquire a reader lock.
33189 ** Different API routines are called depending on whether or not this
33190 ** is Win9x or WinNT.
33192 static int getReadLock(winFile *pFile){
33193 int res;
33194 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
33195 if( isNT() ){
33196 #if SQLITE_OS_WINCE
33198 ** NOTE: Windows CE is handled differently here due its lack of the Win32
33199 ** API LockFileEx.
33201 res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
33202 #else
33203 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
33204 SHARED_SIZE, 0);
33205 #endif
33207 #ifdef SQLITE_WIN32_HAS_ANSI
33208 else{
33209 int lk;
33210 sqlite3_randomness(sizeof(lk), &lk);
33211 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
33212 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
33213 SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
33215 #endif
33216 if( res == 0 ){
33217 pFile->lastErrno = osGetLastError();
33218 /* No need to log a failure to lock */
33220 OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
33221 return res;
33225 ** Undo a readlock
33227 static int unlockReadLock(winFile *pFile){
33228 int res;
33229 DWORD lastErrno;
33230 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
33231 if( isNT() ){
33232 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33234 #ifdef SQLITE_WIN32_HAS_ANSI
33235 else{
33236 res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
33238 #endif
33239 if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
33240 pFile->lastErrno = lastErrno;
33241 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
33242 "unlockReadLock", pFile->zPath);
33244 OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
33245 return res;
33249 ** Lock the file with the lock specified by parameter locktype - one
33250 ** of the following:
33252 ** (1) SHARED_LOCK
33253 ** (2) RESERVED_LOCK
33254 ** (3) PENDING_LOCK
33255 ** (4) EXCLUSIVE_LOCK
33257 ** Sometimes when requesting one lock state, additional lock states
33258 ** are inserted in between. The locking might fail on one of the later
33259 ** transitions leaving the lock state different from what it started but
33260 ** still short of its goal. The following chart shows the allowed
33261 ** transitions and the inserted intermediate states:
33263 ** UNLOCKED -> SHARED
33264 ** SHARED -> RESERVED
33265 ** SHARED -> (PENDING) -> EXCLUSIVE
33266 ** RESERVED -> (PENDING) -> EXCLUSIVE
33267 ** PENDING -> EXCLUSIVE
33269 ** This routine will only increase a lock. The winUnlock() routine
33270 ** erases all locks at once and returns us immediately to locking level 0.
33271 ** It is not possible to lower the locking level one step at a time. You
33272 ** must go straight to locking level 0.
33274 static int winLock(sqlite3_file *id, int locktype){
33275 int rc = SQLITE_OK; /* Return code from subroutines */
33276 int res = 1; /* Result of a Windows lock call */
33277 int newLocktype; /* Set pFile->locktype to this value before exiting */
33278 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
33279 winFile *pFile = (winFile*)id;
33280 DWORD lastErrno = NO_ERROR;
33282 assert( id!=0 );
33283 OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
33284 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
33286 /* If there is already a lock of this type or more restrictive on the
33287 ** OsFile, do nothing. Don't use the end_lock: exit path, as
33288 ** sqlite3OsEnterMutex() hasn't been called yet.
33290 if( pFile->locktype>=locktype ){
33291 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
33292 return SQLITE_OK;
33295 /* Make sure the locking sequence is correct
33297 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
33298 assert( locktype!=PENDING_LOCK );
33299 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
33301 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
33302 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
33303 ** the PENDING_LOCK byte is temporary.
33305 newLocktype = pFile->locktype;
33306 if( (pFile->locktype==NO_LOCK)
33307 || ( (locktype==EXCLUSIVE_LOCK)
33308 && (pFile->locktype==RESERVED_LOCK))
33310 int cnt = 3;
33311 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
33312 PENDING_BYTE, 0, 1, 0))==0 ){
33313 /* Try 3 times to get the pending lock. This is needed to work
33314 ** around problems caused by indexing and/or anti-virus software on
33315 ** Windows systems.
33316 ** If you are using this code as a model for alternative VFSes, do not
33317 ** copy this retry logic. It is a hack intended for Windows only.
33319 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
33320 pFile->h, cnt, sqlite3ErrName(res)));
33321 if( cnt ) sqlite3_win32_sleep(1);
33323 gotPendingLock = res;
33324 if( !res ){
33325 lastErrno = osGetLastError();
33329 /* Acquire a shared lock
33331 if( locktype==SHARED_LOCK && res ){
33332 assert( pFile->locktype==NO_LOCK );
33333 res = getReadLock(pFile);
33334 if( res ){
33335 newLocktype = SHARED_LOCK;
33336 }else{
33337 lastErrno = osGetLastError();
33341 /* Acquire a RESERVED lock
33343 if( locktype==RESERVED_LOCK && res ){
33344 assert( pFile->locktype==SHARED_LOCK );
33345 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
33346 if( res ){
33347 newLocktype = RESERVED_LOCK;
33348 }else{
33349 lastErrno = osGetLastError();
33353 /* Acquire a PENDING lock
33355 if( locktype==EXCLUSIVE_LOCK && res ){
33356 newLocktype = PENDING_LOCK;
33357 gotPendingLock = 0;
33360 /* Acquire an EXCLUSIVE lock
33362 if( locktype==EXCLUSIVE_LOCK && res ){
33363 assert( pFile->locktype>=SHARED_LOCK );
33364 res = unlockReadLock(pFile);
33365 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
33366 SHARED_SIZE, 0);
33367 if( res ){
33368 newLocktype = EXCLUSIVE_LOCK;
33369 }else{
33370 lastErrno = osGetLastError();
33371 getReadLock(pFile);
33375 /* If we are holding a PENDING lock that ought to be released, then
33376 ** release it now.
33378 if( gotPendingLock && locktype==SHARED_LOCK ){
33379 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
33382 /* Update the state of the lock has held in the file descriptor then
33383 ** return the appropriate result code.
33385 if( res ){
33386 rc = SQLITE_OK;
33387 }else{
33388 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
33389 pFile->h, locktype, newLocktype));
33390 pFile->lastErrno = lastErrno;
33391 rc = SQLITE_BUSY;
33393 pFile->locktype = (u8)newLocktype;
33394 OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
33395 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
33396 return rc;
33400 ** This routine checks if there is a RESERVED lock held on the specified
33401 ** file by this or any other process. If such a lock is held, return
33402 ** non-zero, otherwise zero.
33404 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
33405 int rc;
33406 winFile *pFile = (winFile*)id;
33408 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
33409 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
33411 assert( id!=0 );
33412 if( pFile->locktype>=RESERVED_LOCK ){
33413 rc = 1;
33414 OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
33415 }else{
33416 rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
33417 if( rc ){
33418 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
33420 rc = !rc;
33421 OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
33423 *pResOut = rc;
33424 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
33425 pFile->h, pResOut, *pResOut));
33426 return SQLITE_OK;
33430 ** Lower the locking level on file descriptor id to locktype. locktype
33431 ** must be either NO_LOCK or SHARED_LOCK.
33433 ** If the locking level of the file descriptor is already at or below
33434 ** the requested locking level, this routine is a no-op.
33436 ** It is not possible for this routine to fail if the second argument
33437 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
33438 ** might return SQLITE_IOERR;
33440 static int winUnlock(sqlite3_file *id, int locktype){
33441 int type;
33442 winFile *pFile = (winFile*)id;
33443 int rc = SQLITE_OK;
33444 assert( pFile!=0 );
33445 assert( locktype<=SHARED_LOCK );
33446 OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
33447 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
33448 type = pFile->locktype;
33449 if( type>=EXCLUSIVE_LOCK ){
33450 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33451 if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
33452 /* This should never happen. We should always be able to
33453 ** reacquire the read lock */
33454 rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
33455 "winUnlock", pFile->zPath);
33458 if( type>=RESERVED_LOCK ){
33459 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
33461 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
33462 unlockReadLock(pFile);
33464 if( type>=PENDING_LOCK ){
33465 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
33467 pFile->locktype = (u8)locktype;
33468 OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
33469 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
33470 return rc;
33474 ** If *pArg is inititially negative then this is a query. Set *pArg to
33475 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
33477 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
33479 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
33480 if( *pArg<0 ){
33481 *pArg = (pFile->ctrlFlags & mask)!=0;
33482 }else if( (*pArg)==0 ){
33483 pFile->ctrlFlags &= ~mask;
33484 }else{
33485 pFile->ctrlFlags |= mask;
33489 /* Forward declaration */
33490 static int getTempname(int nBuf, char *zBuf);
33491 #if SQLITE_MAX_MMAP_SIZE>0
33492 static int winMapfile(winFile*, sqlite3_int64);
33493 #endif
33496 ** Control and query of the open file handle.
33498 static int winFileControl(sqlite3_file *id, int op, void *pArg){
33499 winFile *pFile = (winFile*)id;
33500 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
33501 switch( op ){
33502 case SQLITE_FCNTL_LOCKSTATE: {
33503 *(int*)pArg = pFile->locktype;
33504 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33505 return SQLITE_OK;
33507 case SQLITE_LAST_ERRNO: {
33508 *(int*)pArg = (int)pFile->lastErrno;
33509 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33510 return SQLITE_OK;
33512 case SQLITE_FCNTL_CHUNK_SIZE: {
33513 pFile->szChunk = *(int *)pArg;
33514 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33515 return SQLITE_OK;
33517 case SQLITE_FCNTL_SIZE_HINT: {
33518 if( pFile->szChunk>0 ){
33519 sqlite3_int64 oldSz;
33520 int rc = winFileSize(id, &oldSz);
33521 if( rc==SQLITE_OK ){
33522 sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
33523 if( newSz>oldSz ){
33524 SimulateIOErrorBenign(1);
33525 rc = winTruncate(id, newSz);
33526 SimulateIOErrorBenign(0);
33529 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
33530 return rc;
33532 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33533 return SQLITE_OK;
33535 case SQLITE_FCNTL_PERSIST_WAL: {
33536 winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
33537 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33538 return SQLITE_OK;
33540 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
33541 winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
33542 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33543 return SQLITE_OK;
33545 case SQLITE_FCNTL_VFSNAME: {
33546 *(char**)pArg = sqlite3_mprintf("win32");
33547 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33548 return SQLITE_OK;
33550 case SQLITE_FCNTL_WIN32_AV_RETRY: {
33551 int *a = (int*)pArg;
33552 if( a[0]>0 ){
33553 win32IoerrRetry = a[0];
33554 }else{
33555 a[0] = win32IoerrRetry;
33557 if( a[1]>0 ){
33558 win32IoerrRetryDelay = a[1];
33559 }else{
33560 a[1] = win32IoerrRetryDelay;
33562 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33563 return SQLITE_OK;
33565 case SQLITE_FCNTL_TEMPFILENAME: {
33566 char *zTFile = sqlite3MallocZero( pFile->pVfs->mxPathname );
33567 if( zTFile ){
33568 getTempname(pFile->pVfs->mxPathname, zTFile);
33569 *(char**)pArg = zTFile;
33571 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33572 return SQLITE_OK;
33574 #if SQLITE_MAX_MMAP_SIZE>0
33575 case SQLITE_FCNTL_MMAP_SIZE: {
33576 i64 newLimit = *(i64*)pArg;
33577 int rc = SQLITE_OK;
33578 if( newLimit>sqlite3GlobalConfig.mxMmap ){
33579 newLimit = sqlite3GlobalConfig.mxMmap;
33581 *(i64*)pArg = pFile->mmapSizeMax;
33582 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
33583 pFile->mmapSizeMax = newLimit;
33584 if( pFile->mmapSize>0 ){
33585 (void)winUnmapfile(pFile);
33586 rc = winMapfile(pFile, -1);
33589 OSTRACE(("FCNTL file=%p, rc=%d\n", pFile->h, rc));
33590 return rc;
33592 #endif
33594 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
33595 return SQLITE_NOTFOUND;
33599 ** Return the sector size in bytes of the underlying block device for
33600 ** the specified file. This is almost always 512 bytes, but may be
33601 ** larger for some devices.
33603 ** SQLite code assumes this function cannot fail. It also assumes that
33604 ** if two files are created in the same file-system directory (i.e.
33605 ** a database and its journal file) that the sector size will be the
33606 ** same for both.
33608 static int winSectorSize(sqlite3_file *id){
33609 (void)id;
33610 return SQLITE_DEFAULT_SECTOR_SIZE;
33614 ** Return a vector of device characteristics.
33616 static int winDeviceCharacteristics(sqlite3_file *id){
33617 winFile *p = (winFile*)id;
33618 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
33619 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
33623 ** Windows will only let you create file view mappings
33624 ** on allocation size granularity boundaries.
33625 ** During sqlite3_os_init() we do a GetSystemInfo()
33626 ** to get the granularity size.
33628 SYSTEM_INFO winSysInfo;
33630 #ifndef SQLITE_OMIT_WAL
33633 ** Helper functions to obtain and relinquish the global mutex. The
33634 ** global mutex is used to protect the winLockInfo objects used by
33635 ** this file, all of which may be shared by multiple threads.
33637 ** Function winShmMutexHeld() is used to assert() that the global mutex
33638 ** is held when required. This function is only used as part of assert()
33639 ** statements. e.g.
33641 ** winShmEnterMutex()
33642 ** assert( winShmMutexHeld() );
33643 ** winShmLeaveMutex()
33645 static void winShmEnterMutex(void){
33646 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33648 static void winShmLeaveMutex(void){
33649 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33651 #ifdef SQLITE_DEBUG
33652 static int winShmMutexHeld(void) {
33653 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33655 #endif
33658 ** Object used to represent a single file opened and mmapped to provide
33659 ** shared memory. When multiple threads all reference the same
33660 ** log-summary, each thread has its own winFile object, but they all
33661 ** point to a single instance of this object. In other words, each
33662 ** log-summary is opened only once per process.
33664 ** winShmMutexHeld() must be true when creating or destroying
33665 ** this object or while reading or writing the following fields:
33667 ** nRef
33668 ** pNext
33670 ** The following fields are read-only after the object is created:
33672 ** fid
33673 ** zFilename
33675 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
33676 ** winShmMutexHeld() is true when reading or writing any other field
33677 ** in this structure.
33680 struct winShmNode {
33681 sqlite3_mutex *mutex; /* Mutex to access this object */
33682 char *zFilename; /* Name of the file */
33683 winFile hFile; /* File handle from winOpen */
33685 int szRegion; /* Size of shared-memory regions */
33686 int nRegion; /* Size of array apRegion */
33687 struct ShmRegion {
33688 HANDLE hMap; /* File handle from CreateFileMapping */
33689 void *pMap;
33690 } *aRegion;
33691 DWORD lastErrno; /* The Windows errno from the last I/O error */
33693 int nRef; /* Number of winShm objects pointing to this */
33694 winShm *pFirst; /* All winShm objects pointing to this */
33695 winShmNode *pNext; /* Next in list of all winShmNode objects */
33696 #ifdef SQLITE_DEBUG
33697 u8 nextShmId; /* Next available winShm.id value */
33698 #endif
33702 ** A global array of all winShmNode objects.
33704 ** The winShmMutexHeld() must be true while reading or writing this list.
33706 static winShmNode *winShmNodeList = 0;
33709 ** Structure used internally by this VFS to record the state of an
33710 ** open shared memory connection.
33712 ** The following fields are initialized when this object is created and
33713 ** are read-only thereafter:
33715 ** winShm.pShmNode
33716 ** winShm.id
33718 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
33719 ** while accessing any read/write fields.
33721 struct winShm {
33722 winShmNode *pShmNode; /* The underlying winShmNode object */
33723 winShm *pNext; /* Next winShm with the same winShmNode */
33724 u8 hasMutex; /* True if holding the winShmNode mutex */
33725 u16 sharedMask; /* Mask of shared locks held */
33726 u16 exclMask; /* Mask of exclusive locks held */
33727 #ifdef SQLITE_DEBUG
33728 u8 id; /* Id of this connection with its winShmNode */
33729 #endif
33733 ** Constants used for locking
33735 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
33736 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
33739 ** Apply advisory locks for all n bytes beginning at ofst.
33741 #define _SHM_UNLCK 1
33742 #define _SHM_RDLCK 2
33743 #define _SHM_WRLCK 3
33744 static int winShmSystemLock(
33745 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
33746 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
33747 int ofst, /* Offset to first byte to be locked/unlocked */
33748 int nByte /* Number of bytes to lock or unlock */
33750 int rc = 0; /* Result code form Lock/UnlockFileEx() */
33752 /* Access to the winShmNode object is serialized by the caller */
33753 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
33755 OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
33756 pFile->hFile.h, lockType, ofst, nByte));
33758 /* Release/Acquire the system-level lock */
33759 if( lockType==_SHM_UNLCK ){
33760 rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
33761 }else{
33762 /* Initialize the locking parameters */
33763 DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
33764 if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
33765 rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
33768 if( rc!= 0 ){
33769 rc = SQLITE_OK;
33770 }else{
33771 pFile->lastErrno = osGetLastError();
33772 rc = SQLITE_BUSY;
33775 OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
33776 pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
33777 "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
33779 return rc;
33782 /* Forward references to VFS methods */
33783 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
33784 static int winDelete(sqlite3_vfs *,const char*,int);
33787 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
33789 ** This is not a VFS shared-memory method; it is a utility function called
33790 ** by VFS shared-memory methods.
33792 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
33793 winShmNode **pp;
33794 winShmNode *p;
33795 BOOL bRc;
33796 assert( winShmMutexHeld() );
33797 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
33798 osGetCurrentProcessId(), deleteFlag));
33799 pp = &winShmNodeList;
33800 while( (p = *pp)!=0 ){
33801 if( p->nRef==0 ){
33802 int i;
33803 if( p->mutex ) sqlite3_mutex_free(p->mutex);
33804 for(i=0; i<p->nRegion; i++){
33805 bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
33806 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
33807 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
33808 bRc = osCloseHandle(p->aRegion[i].hMap);
33809 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
33810 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
33812 if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
33813 SimulateIOErrorBenign(1);
33814 winClose((sqlite3_file *)&p->hFile);
33815 SimulateIOErrorBenign(0);
33817 if( deleteFlag ){
33818 SimulateIOErrorBenign(1);
33819 sqlite3BeginBenignMalloc();
33820 winDelete(pVfs, p->zFilename, 0);
33821 sqlite3EndBenignMalloc();
33822 SimulateIOErrorBenign(0);
33824 *pp = p->pNext;
33825 sqlite3_free(p->aRegion);
33826 sqlite3_free(p);
33827 }else{
33828 pp = &p->pNext;
33834 ** Open the shared-memory area associated with database file pDbFd.
33836 ** When opening a new shared-memory file, if no other instances of that
33837 ** file are currently open, in this process or in other processes, then
33838 ** the file must be truncated to zero length or have its header cleared.
33840 static int winOpenSharedMemory(winFile *pDbFd){
33841 struct winShm *p; /* The connection to be opened */
33842 struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
33843 int rc; /* Result code */
33844 struct winShmNode *pNew; /* Newly allocated winShmNode */
33845 int nName; /* Size of zName in bytes */
33847 assert( pDbFd->pShm==0 ); /* Not previously opened */
33849 /* Allocate space for the new sqlite3_shm object. Also speculatively
33850 ** allocate space for a new winShmNode and filename.
33852 p = sqlite3MallocZero( sizeof(*p) );
33853 if( p==0 ) return SQLITE_IOERR_NOMEM;
33854 nName = sqlite3Strlen30(pDbFd->zPath);
33855 pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
33856 if( pNew==0 ){
33857 sqlite3_free(p);
33858 return SQLITE_IOERR_NOMEM;
33860 pNew->zFilename = (char*)&pNew[1];
33861 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
33862 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
33864 /* Look to see if there is an existing winShmNode that can be used.
33865 ** If no matching winShmNode currently exists, create a new one.
33867 winShmEnterMutex();
33868 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
33869 /* TBD need to come up with better match here. Perhaps
33870 ** use FILE_ID_BOTH_DIR_INFO Structure.
33872 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
33874 if( pShmNode ){
33875 sqlite3_free(pNew);
33876 }else{
33877 pShmNode = pNew;
33878 pNew = 0;
33879 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
33880 pShmNode->pNext = winShmNodeList;
33881 winShmNodeList = pShmNode;
33883 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33884 if( pShmNode->mutex==0 ){
33885 rc = SQLITE_IOERR_NOMEM;
33886 goto shm_open_err;
33889 rc = winOpen(pDbFd->pVfs,
33890 pShmNode->zFilename, /* Name of the file (UTF-8) */
33891 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
33892 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
33894 if( SQLITE_OK!=rc ){
33895 goto shm_open_err;
33898 /* Check to see if another process is holding the dead-man switch.
33899 ** If not, truncate the file to zero length.
33901 if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
33902 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
33903 if( rc!=SQLITE_OK ){
33904 rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
33905 "winOpenShm", pDbFd->zPath);
33908 if( rc==SQLITE_OK ){
33909 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33910 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
33912 if( rc ) goto shm_open_err;
33915 /* Make the new connection a child of the winShmNode */
33916 p->pShmNode = pShmNode;
33917 #ifdef SQLITE_DEBUG
33918 p->id = pShmNode->nextShmId++;
33919 #endif
33920 pShmNode->nRef++;
33921 pDbFd->pShm = p;
33922 winShmLeaveMutex();
33924 /* The reference count on pShmNode has already been incremented under
33925 ** the cover of the winShmEnterMutex() mutex and the pointer from the
33926 ** new (struct winShm) object to the pShmNode has been set. All that is
33927 ** left to do is to link the new object into the linked list starting
33928 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
33929 ** mutex.
33931 sqlite3_mutex_enter(pShmNode->mutex);
33932 p->pNext = pShmNode->pFirst;
33933 pShmNode->pFirst = p;
33934 sqlite3_mutex_leave(pShmNode->mutex);
33935 return SQLITE_OK;
33937 /* Jump here on any error */
33938 shm_open_err:
33939 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33940 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
33941 sqlite3_free(p);
33942 sqlite3_free(pNew);
33943 winShmLeaveMutex();
33944 return rc;
33948 ** Close a connection to shared-memory. Delete the underlying
33949 ** storage if deleteFlag is true.
33951 static int winShmUnmap(
33952 sqlite3_file *fd, /* Database holding shared memory */
33953 int deleteFlag /* Delete after closing if true */
33955 winFile *pDbFd; /* Database holding shared-memory */
33956 winShm *p; /* The connection to be closed */
33957 winShmNode *pShmNode; /* The underlying shared-memory file */
33958 winShm **pp; /* For looping over sibling connections */
33960 pDbFd = (winFile*)fd;
33961 p = pDbFd->pShm;
33962 if( p==0 ) return SQLITE_OK;
33963 pShmNode = p->pShmNode;
33965 /* Remove connection p from the set of connections associated
33966 ** with pShmNode */
33967 sqlite3_mutex_enter(pShmNode->mutex);
33968 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
33969 *pp = p->pNext;
33971 /* Free the connection p */
33972 sqlite3_free(p);
33973 pDbFd->pShm = 0;
33974 sqlite3_mutex_leave(pShmNode->mutex);
33976 /* If pShmNode->nRef has reached 0, then close the underlying
33977 ** shared-memory file, too */
33978 winShmEnterMutex();
33979 assert( pShmNode->nRef>0 );
33980 pShmNode->nRef--;
33981 if( pShmNode->nRef==0 ){
33982 winShmPurge(pDbFd->pVfs, deleteFlag);
33984 winShmLeaveMutex();
33986 return SQLITE_OK;
33990 ** Change the lock state for a shared-memory segment.
33992 static int winShmLock(
33993 sqlite3_file *fd, /* Database file holding the shared memory */
33994 int ofst, /* First lock to acquire or release */
33995 int n, /* Number of locks to acquire or release */
33996 int flags /* What to do with the lock */
33998 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
33999 winShm *p = pDbFd->pShm; /* The shared memory being locked */
34000 winShm *pX; /* For looping over all siblings */
34001 winShmNode *pShmNode = p->pShmNode;
34002 int rc = SQLITE_OK; /* Result code */
34003 u16 mask; /* Mask of locks to take or release */
34005 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
34006 assert( n>=1 );
34007 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
34008 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
34009 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
34010 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
34011 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
34013 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
34014 assert( n>1 || mask==(1<<ofst) );
34015 sqlite3_mutex_enter(pShmNode->mutex);
34016 if( flags & SQLITE_SHM_UNLOCK ){
34017 u16 allMask = 0; /* Mask of locks held by siblings */
34019 /* See if any siblings hold this same lock */
34020 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34021 if( pX==p ) continue;
34022 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
34023 allMask |= pX->sharedMask;
34026 /* Unlock the system-level locks */
34027 if( (mask & allMask)==0 ){
34028 rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
34029 }else{
34030 rc = SQLITE_OK;
34033 /* Undo the local locks */
34034 if( rc==SQLITE_OK ){
34035 p->exclMask &= ~mask;
34036 p->sharedMask &= ~mask;
34038 }else if( flags & SQLITE_SHM_SHARED ){
34039 u16 allShared = 0; /* Union of locks held by connections other than "p" */
34041 /* Find out which shared locks are already held by sibling connections.
34042 ** If any sibling already holds an exclusive lock, go ahead and return
34043 ** SQLITE_BUSY.
34045 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34046 if( (pX->exclMask & mask)!=0 ){
34047 rc = SQLITE_BUSY;
34048 break;
34050 allShared |= pX->sharedMask;
34053 /* Get shared locks at the system level, if necessary */
34054 if( rc==SQLITE_OK ){
34055 if( (allShared & mask)==0 ){
34056 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
34057 }else{
34058 rc = SQLITE_OK;
34062 /* Get the local shared locks */
34063 if( rc==SQLITE_OK ){
34064 p->sharedMask |= mask;
34066 }else{
34067 /* Make sure no sibling connections hold locks that will block this
34068 ** lock. If any do, return SQLITE_BUSY right away.
34070 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34071 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
34072 rc = SQLITE_BUSY;
34073 break;
34077 /* Get the exclusive locks at the system level. Then if successful
34078 ** also mark the local connection as being locked.
34080 if( rc==SQLITE_OK ){
34081 rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
34082 if( rc==SQLITE_OK ){
34083 assert( (p->sharedMask & mask)==0 );
34084 p->exclMask |= mask;
34088 sqlite3_mutex_leave(pShmNode->mutex);
34089 OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
34090 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
34091 sqlite3ErrName(rc)));
34092 return rc;
34096 ** Implement a memory barrier or memory fence on shared memory.
34098 ** All loads and stores begun before the barrier must complete before
34099 ** any load or store begun after the barrier.
34101 static void winShmBarrier(
34102 sqlite3_file *fd /* Database holding the shared memory */
34104 UNUSED_PARAMETER(fd);
34105 /* MemoryBarrier(); // does not work -- do not know why not */
34106 winShmEnterMutex();
34107 winShmLeaveMutex();
34111 ** This function is called to obtain a pointer to region iRegion of the
34112 ** shared-memory associated with the database file fd. Shared-memory regions
34113 ** are numbered starting from zero. Each shared-memory region is szRegion
34114 ** bytes in size.
34116 ** If an error occurs, an error code is returned and *pp is set to NULL.
34118 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
34119 ** region has not been allocated (by any client, including one running in a
34120 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
34121 ** isWrite is non-zero and the requested shared-memory region has not yet
34122 ** been allocated, it is allocated by this function.
34124 ** If the shared-memory region has already been allocated or is allocated by
34125 ** this call as described above, then it is mapped into this processes
34126 ** address space (if it is not already), *pp is set to point to the mapped
34127 ** memory and SQLITE_OK returned.
34129 static int winShmMap(
34130 sqlite3_file *fd, /* Handle open on database file */
34131 int iRegion, /* Region to retrieve */
34132 int szRegion, /* Size of regions */
34133 int isWrite, /* True to extend file if necessary */
34134 void volatile **pp /* OUT: Mapped memory */
34136 winFile *pDbFd = (winFile*)fd;
34137 winShm *p = pDbFd->pShm;
34138 winShmNode *pShmNode;
34139 int rc = SQLITE_OK;
34141 if( !p ){
34142 rc = winOpenSharedMemory(pDbFd);
34143 if( rc!=SQLITE_OK ) return rc;
34144 p = pDbFd->pShm;
34146 pShmNode = p->pShmNode;
34148 sqlite3_mutex_enter(pShmNode->mutex);
34149 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
34151 if( pShmNode->nRegion<=iRegion ){
34152 struct ShmRegion *apNew; /* New aRegion[] array */
34153 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
34154 sqlite3_int64 sz; /* Current size of wal-index file */
34156 pShmNode->szRegion = szRegion;
34158 /* The requested region is not mapped into this processes address space.
34159 ** Check to see if it has been allocated (i.e. if the wal-index file is
34160 ** large enough to contain the requested region).
34162 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
34163 if( rc!=SQLITE_OK ){
34164 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34165 "winShmMap1", pDbFd->zPath);
34166 goto shmpage_out;
34169 if( sz<nByte ){
34170 /* The requested memory region does not exist. If isWrite is set to
34171 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
34173 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
34174 ** the requested memory region.
34176 if( !isWrite ) goto shmpage_out;
34177 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
34178 if( rc!=SQLITE_OK ){
34179 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34180 "winShmMap2", pDbFd->zPath);
34181 goto shmpage_out;
34185 /* Map the requested memory region into this processes address space. */
34186 apNew = (struct ShmRegion *)sqlite3_realloc(
34187 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
34189 if( !apNew ){
34190 rc = SQLITE_IOERR_NOMEM;
34191 goto shmpage_out;
34193 pShmNode->aRegion = apNew;
34195 while( pShmNode->nRegion<=iRegion ){
34196 HANDLE hMap = NULL; /* file-mapping handle */
34197 void *pMap = 0; /* Mapped memory region */
34199 #if SQLITE_OS_WINRT
34200 hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
34201 NULL, PAGE_READWRITE, nByte, NULL
34203 #elif defined(SQLITE_WIN32_HAS_WIDE)
34204 hMap = osCreateFileMappingW(pShmNode->hFile.h,
34205 NULL, PAGE_READWRITE, 0, nByte, NULL
34207 #elif defined(SQLITE_WIN32_HAS_ANSI)
34208 hMap = osCreateFileMappingA(pShmNode->hFile.h,
34209 NULL, PAGE_READWRITE, 0, nByte, NULL
34211 #endif
34212 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
34213 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
34214 hMap ? "ok" : "failed"));
34215 if( hMap ){
34216 int iOffset = pShmNode->nRegion*szRegion;
34217 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34218 #if SQLITE_OS_WINRT
34219 pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
34220 iOffset - iOffsetShift, szRegion + iOffsetShift
34222 #else
34223 pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
34224 0, iOffset - iOffsetShift, szRegion + iOffsetShift
34226 #endif
34227 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
34228 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
34229 szRegion, pMap ? "ok" : "failed"));
34231 if( !pMap ){
34232 pShmNode->lastErrno = osGetLastError();
34233 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
34234 "winShmMap3", pDbFd->zPath);
34235 if( hMap ) osCloseHandle(hMap);
34236 goto shmpage_out;
34239 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
34240 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
34241 pShmNode->nRegion++;
34245 shmpage_out:
34246 if( pShmNode->nRegion>iRegion ){
34247 int iOffset = iRegion*szRegion;
34248 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34249 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
34250 *pp = (void *)&p[iOffsetShift];
34251 }else{
34252 *pp = 0;
34254 sqlite3_mutex_leave(pShmNode->mutex);
34255 return rc;
34258 #else
34259 # define winShmMap 0
34260 # define winShmLock 0
34261 # define winShmBarrier 0
34262 # define winShmUnmap 0
34263 #endif /* #ifndef SQLITE_OMIT_WAL */
34266 ** Cleans up the mapped region of the specified file, if any.
34268 #if SQLITE_MAX_MMAP_SIZE>0
34269 static int winUnmapfile(winFile *pFile){
34270 assert( pFile!=0 );
34271 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
34272 "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
34273 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
34274 pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
34275 if( pFile->pMapRegion ){
34276 if( !osUnmapViewOfFile(pFile->pMapRegion) ){
34277 pFile->lastErrno = osGetLastError();
34278 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
34279 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
34280 pFile->pMapRegion));
34281 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
34282 "winUnmap1", pFile->zPath);
34284 pFile->pMapRegion = 0;
34285 pFile->mmapSize = 0;
34286 pFile->mmapSizeActual = 0;
34288 if( pFile->hMap!=NULL ){
34289 if( !osCloseHandle(pFile->hMap) ){
34290 pFile->lastErrno = osGetLastError();
34291 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
34292 osGetCurrentProcessId(), pFile, pFile->hMap));
34293 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
34294 "winUnmap2", pFile->zPath);
34296 pFile->hMap = NULL;
34298 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34299 osGetCurrentProcessId(), pFile));
34300 return SQLITE_OK;
34304 ** Memory map or remap the file opened by file-descriptor pFd (if the file
34305 ** is already mapped, the existing mapping is replaced by the new). Or, if
34306 ** there already exists a mapping for this file, and there are still
34307 ** outstanding xFetch() references to it, this function is a no-op.
34309 ** If parameter nByte is non-negative, then it is the requested size of
34310 ** the mapping to create. Otherwise, if nByte is less than zero, then the
34311 ** requested size is the size of the file on disk. The actual size of the
34312 ** created mapping is either the requested size or the value configured
34313 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
34315 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
34316 ** recreated as a result of outstanding references) or an SQLite error
34317 ** code otherwise.
34319 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
34320 sqlite3_int64 nMap = nByte;
34321 int rc;
34323 assert( nMap>=0 || pFd->nFetchOut==0 );
34324 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
34325 osGetCurrentProcessId(), pFd, nByte));
34327 if( pFd->nFetchOut>0 ) return SQLITE_OK;
34329 if( nMap<0 ){
34330 rc = winFileSize((sqlite3_file*)pFd, &nMap);
34331 if( rc ){
34332 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
34333 osGetCurrentProcessId(), pFd));
34334 return SQLITE_IOERR_FSTAT;
34337 if( nMap>pFd->mmapSizeMax ){
34338 nMap = pFd->mmapSizeMax;
34340 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
34342 if( nMap==0 && pFd->mmapSize>0 ){
34343 winUnmapfile(pFd);
34345 if( nMap!=pFd->mmapSize ){
34346 void *pNew = 0;
34347 DWORD protect = PAGE_READONLY;
34348 DWORD flags = FILE_MAP_READ;
34350 winUnmapfile(pFd);
34351 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
34352 protect = PAGE_READWRITE;
34353 flags |= FILE_MAP_WRITE;
34355 #if SQLITE_OS_WINRT
34356 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
34357 #elif defined(SQLITE_WIN32_HAS_WIDE)
34358 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
34359 (DWORD)((nMap>>32) & 0xffffffff),
34360 (DWORD)(nMap & 0xffffffff), NULL);
34361 #elif defined(SQLITE_WIN32_HAS_ANSI)
34362 pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
34363 (DWORD)((nMap>>32) & 0xffffffff),
34364 (DWORD)(nMap & 0xffffffff), NULL);
34365 #endif
34366 if( pFd->hMap==NULL ){
34367 pFd->lastErrno = osGetLastError();
34368 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
34369 "winMapfile", pFd->zPath);
34370 /* Log the error, but continue normal operation using xRead/xWrite */
34371 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=SQLITE_IOERR_MMAP\n",
34372 osGetCurrentProcessId(), pFd));
34373 return SQLITE_OK;
34375 assert( (nMap % winSysInfo.dwPageSize)==0 );
34376 assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
34377 #if SQLITE_OS_WINRT
34378 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
34379 #else
34380 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
34381 #endif
34382 if( pNew==NULL ){
34383 osCloseHandle(pFd->hMap);
34384 pFd->hMap = NULL;
34385 pFd->lastErrno = osGetLastError();
34386 winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
34387 "winMapfile", pFd->zPath);
34388 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=SQLITE_IOERR_MMAP\n",
34389 osGetCurrentProcessId(), pFd));
34390 return SQLITE_OK;
34392 pFd->pMapRegion = pNew;
34393 pFd->mmapSize = nMap;
34394 pFd->mmapSizeActual = nMap;
34397 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34398 osGetCurrentProcessId(), pFd));
34399 return SQLITE_OK;
34401 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
34404 ** If possible, return a pointer to a mapping of file fd starting at offset
34405 ** iOff. The mapping must be valid for at least nAmt bytes.
34407 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
34408 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
34409 ** Finally, if an error does occur, return an SQLite error code. The final
34410 ** value of *pp is undefined in this case.
34412 ** If this function does return a pointer, the caller must eventually
34413 ** release the reference by calling winUnfetch().
34415 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
34416 #if SQLITE_MAX_MMAP_SIZE>0
34417 winFile *pFd = (winFile*)fd; /* The underlying database file */
34418 #endif
34419 *pp = 0;
34421 OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
34422 osGetCurrentProcessId(), fd, iOff, nAmt, pp));
34424 #if SQLITE_MAX_MMAP_SIZE>0
34425 if( pFd->mmapSizeMax>0 ){
34426 if( pFd->pMapRegion==0 ){
34427 int rc = winMapfile(pFd, -1);
34428 if( rc!=SQLITE_OK ){
34429 OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
34430 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
34431 return rc;
34434 if( pFd->mmapSize >= iOff+nAmt ){
34435 *pp = &((u8 *)pFd->pMapRegion)[iOff];
34436 pFd->nFetchOut++;
34439 #endif
34441 OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
34442 osGetCurrentProcessId(), fd, pp, *pp));
34443 return SQLITE_OK;
34447 ** If the third argument is non-NULL, then this function releases a
34448 ** reference obtained by an earlier call to winFetch(). The second
34449 ** argument passed to this function must be the same as the corresponding
34450 ** argument that was passed to the winFetch() invocation.
34452 ** Or, if the third argument is NULL, then this function is being called
34453 ** to inform the VFS layer that, according to POSIX, any existing mapping
34454 ** may now be invalid and should be unmapped.
34456 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
34457 #if SQLITE_MAX_MMAP_SIZE>0
34458 winFile *pFd = (winFile*)fd; /* The underlying database file */
34460 /* If p==0 (unmap the entire file) then there must be no outstanding
34461 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
34462 ** then there must be at least one outstanding. */
34463 assert( (p==0)==(pFd->nFetchOut==0) );
34465 /* If p!=0, it must match the iOff value. */
34466 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
34468 OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
34469 osGetCurrentProcessId(), pFd, iOff, p));
34471 if( p ){
34472 pFd->nFetchOut--;
34473 }else{
34474 /* FIXME: If Windows truly always prevents truncating or deleting a
34475 ** file while a mapping is held, then the following winUnmapfile() call
34476 ** is unnecessary can can be omitted - potentially improving
34477 ** performance. */
34478 winUnmapfile(pFd);
34481 assert( pFd->nFetchOut>=0 );
34482 #endif
34484 OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34485 osGetCurrentProcessId(), fd));
34486 return SQLITE_OK;
34490 ** Here ends the implementation of all sqlite3_file methods.
34492 ********************** End sqlite3_file Methods *******************************
34493 ******************************************************************************/
34496 ** This vector defines all the methods that can operate on an
34497 ** sqlite3_file for win32.
34499 static const sqlite3_io_methods winIoMethod = {
34500 3, /* iVersion */
34501 winClose, /* xClose */
34502 winRead, /* xRead */
34503 winWrite, /* xWrite */
34504 winTruncate, /* xTruncate */
34505 winSync, /* xSync */
34506 winFileSize, /* xFileSize */
34507 winLock, /* xLock */
34508 winUnlock, /* xUnlock */
34509 winCheckReservedLock, /* xCheckReservedLock */
34510 winFileControl, /* xFileControl */
34511 winSectorSize, /* xSectorSize */
34512 winDeviceCharacteristics, /* xDeviceCharacteristics */
34513 winShmMap, /* xShmMap */
34514 winShmLock, /* xShmLock */
34515 winShmBarrier, /* xShmBarrier */
34516 winShmUnmap, /* xShmUnmap */
34517 winFetch, /* xFetch */
34518 winUnfetch /* xUnfetch */
34521 /****************************************************************************
34522 **************************** sqlite3_vfs methods ****************************
34524 ** This division contains the implementation of methods on the
34525 ** sqlite3_vfs object.
34529 ** Convert a UTF-8 filename into whatever form the underlying
34530 ** operating system wants filenames in. Space to hold the result
34531 ** is obtained from malloc and must be freed by the calling
34532 ** function.
34534 static void *convertUtf8Filename(const char *zFilename){
34535 void *zConverted = 0;
34536 if( isNT() ){
34537 zConverted = utf8ToUnicode(zFilename);
34539 #ifdef SQLITE_WIN32_HAS_ANSI
34540 else{
34541 zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
34543 #endif
34544 /* caller will handle out of memory */
34545 return zConverted;
34549 ** Maximum pathname length (in bytes) for windows. The MAX_PATH macro is
34550 ** in characters, so we allocate 3 bytes per character assuming worst-case
34551 ** 3-bytes-per-character UTF8.
34553 #ifndef SQLITE_WIN32_MAX_PATH
34554 # define SQLITE_WIN32_MAX_PATH (MAX_PATH*3)
34555 #endif
34558 ** Create a temporary file name in zBuf. zBuf must be big enough to
34559 ** hold at pVfs->mxPathname characters.
34561 static int getTempname(int nBuf, char *zBuf){
34562 static char zChars[] =
34563 "abcdefghijklmnopqrstuvwxyz"
34564 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
34565 "0123456789";
34566 size_t i, j;
34567 int nTempPath;
34568 char zTempPath[SQLITE_WIN32_MAX_PATH+2];
34570 /* It's odd to simulate an io-error here, but really this is just
34571 ** using the io-error infrastructure to test that SQLite handles this
34572 ** function failing.
34574 SimulateIOError( return SQLITE_IOERR );
34576 if( sqlite3_temp_directory ){
34577 sqlite3_snprintf(SQLITE_WIN32_MAX_PATH-30, zTempPath, "%s",
34578 sqlite3_temp_directory);
34580 #if !SQLITE_OS_WINRT
34581 else if( isNT() ){
34582 char *zMulti;
34583 WCHAR zWidePath[MAX_PATH];
34584 if( osGetTempPathW(MAX_PATH-30, zWidePath)==0 ){
34585 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
34586 return SQLITE_IOERR_GETTEMPPATH;
34588 zMulti = unicodeToUtf8(zWidePath);
34589 if( zMulti ){
34590 sqlite3_snprintf(SQLITE_WIN32_MAX_PATH-30, zTempPath, "%s", zMulti);
34591 sqlite3_free(zMulti);
34592 }else{
34593 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
34594 return SQLITE_IOERR_NOMEM;
34597 #ifdef SQLITE_WIN32_HAS_ANSI
34598 else{
34599 char *zUtf8;
34600 char zMbcsPath[SQLITE_WIN32_MAX_PATH];
34601 if( osGetTempPathA(SQLITE_WIN32_MAX_PATH-30, zMbcsPath)==0 ){
34602 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
34603 return SQLITE_IOERR_GETTEMPPATH;
34605 zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
34606 if( zUtf8 ){
34607 sqlite3_snprintf(SQLITE_WIN32_MAX_PATH-30, zTempPath, "%s", zUtf8);
34608 sqlite3_free(zUtf8);
34609 }else{
34610 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
34611 return SQLITE_IOERR_NOMEM;
34614 #else
34615 else{
34617 ** Compiled without ANSI support and the current operating system
34618 ** is not Windows NT; therefore, just zero the temporary buffer.
34620 memset(zTempPath, 0, SQLITE_WIN32_MAX_PATH+2);
34622 #endif /* SQLITE_WIN32_HAS_ANSI */
34623 #else
34624 else{
34626 ** Compiled for WinRT and the sqlite3_temp_directory is not set;
34627 ** therefore, just zero the temporary buffer.
34629 memset(zTempPath, 0, SQLITE_WIN32_MAX_PATH+2);
34631 #endif /* !SQLITE_OS_WINRT */
34633 /* Check that the output buffer is large enough for the temporary file
34634 ** name. If it is not, return SQLITE_ERROR.
34636 nTempPath = sqlite3Strlen30(zTempPath);
34638 if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
34639 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
34640 return SQLITE_ERROR;
34643 for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
34644 zTempPath[i] = 0;
34646 sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
34647 "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
34648 zTempPath);
34649 j = sqlite3Strlen30(zBuf);
34650 sqlite3_randomness(15, &zBuf[j]);
34651 for(i=0; i<15; i++, j++){
34652 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
34654 zBuf[j] = 0;
34655 zBuf[j+1] = 0;
34657 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
34658 return SQLITE_OK;
34662 ** Return TRUE if the named file is really a directory. Return false if
34663 ** it is something other than a directory, or if there is any kind of memory
34664 ** allocation failure.
34666 static int winIsDir(const void *zConverted){
34667 DWORD attr;
34668 int rc = 0;
34669 DWORD lastErrno;
34671 if( isNT() ){
34672 int cnt = 0;
34673 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34674 memset(&sAttrData, 0, sizeof(sAttrData));
34675 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
34676 GetFileExInfoStandard,
34677 &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
34678 if( !rc ){
34679 return 0; /* Invalid name? */
34681 attr = sAttrData.dwFileAttributes;
34682 #if SQLITE_OS_WINCE==0
34683 }else{
34684 attr = osGetFileAttributesA((char*)zConverted);
34685 #endif
34687 return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
34691 ** Open a file.
34693 static int winOpen(
34694 sqlite3_vfs *pVfs, /* Not used */
34695 const char *zName, /* Name of the file (UTF-8) */
34696 sqlite3_file *id, /* Write the SQLite file handle here */
34697 int flags, /* Open mode flags */
34698 int *pOutFlags /* Status return flags */
34700 HANDLE h;
34701 DWORD lastErrno;
34702 DWORD dwDesiredAccess;
34703 DWORD dwShareMode;
34704 DWORD dwCreationDisposition;
34705 DWORD dwFlagsAndAttributes = 0;
34706 #if SQLITE_OS_WINCE
34707 int isTemp = 0;
34708 #endif
34709 winFile *pFile = (winFile*)id;
34710 void *zConverted; /* Filename in OS encoding */
34711 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
34712 int cnt = 0;
34714 /* If argument zPath is a NULL pointer, this function is required to open
34715 ** a temporary file. Use this buffer to store the file name in.
34717 char zTmpname[SQLITE_WIN32_MAX_PATH+2]; /* Buffer used to create temp filename */
34719 int rc = SQLITE_OK; /* Function Return Code */
34720 #if !defined(NDEBUG) || SQLITE_OS_WINCE
34721 int eType = flags&0xFFFFFF00; /* Type of file to open */
34722 #endif
34724 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
34725 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
34726 int isCreate = (flags & SQLITE_OPEN_CREATE);
34727 int isReadonly = (flags & SQLITE_OPEN_READONLY);
34728 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
34730 #ifndef NDEBUG
34731 int isOpenJournal = (isCreate && (
34732 eType==SQLITE_OPEN_MASTER_JOURNAL
34733 || eType==SQLITE_OPEN_MAIN_JOURNAL
34734 || eType==SQLITE_OPEN_WAL
34736 #endif
34738 OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
34739 zUtf8Name, id, flags, pOutFlags));
34741 /* Check the following statements are true:
34743 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
34744 ** (b) if CREATE is set, then READWRITE must also be set, and
34745 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
34746 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
34748 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
34749 assert(isCreate==0 || isReadWrite);
34750 assert(isExclusive==0 || isCreate);
34751 assert(isDelete==0 || isCreate);
34753 /* The main DB, main journal, WAL file and master journal are never
34754 ** automatically deleted. Nor are they ever temporary files. */
34755 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
34756 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
34757 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
34758 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
34760 /* Assert that the upper layer has set one of the "file-type" flags. */
34761 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
34762 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
34763 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
34764 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
34767 assert( pFile!=0 );
34768 memset(pFile, 0, sizeof(winFile));
34769 pFile->h = INVALID_HANDLE_VALUE;
34771 #if SQLITE_OS_WINRT
34772 if( !sqlite3_temp_directory ){
34773 sqlite3_log(SQLITE_ERROR,
34774 "sqlite3_temp_directory variable should be set for WinRT");
34776 #endif
34778 /* If the second argument to this function is NULL, generate a
34779 ** temporary file name to use
34781 if( !zUtf8Name ){
34782 assert(isDelete && !isOpenJournal);
34783 rc = getTempname(SQLITE_WIN32_MAX_PATH+2, zTmpname);
34784 if( rc!=SQLITE_OK ){
34785 OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
34786 return rc;
34788 zUtf8Name = zTmpname;
34791 /* Database filenames are double-zero terminated if they are not
34792 ** URIs with parameters. Hence, they can always be passed into
34793 ** sqlite3_uri_parameter().
34795 assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
34796 zUtf8Name[strlen(zUtf8Name)+1]==0 );
34798 /* Convert the filename to the system encoding. */
34799 zConverted = convertUtf8Filename(zUtf8Name);
34800 if( zConverted==0 ){
34801 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
34802 return SQLITE_IOERR_NOMEM;
34805 if( winIsDir(zConverted) ){
34806 sqlite3_free(zConverted);
34807 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
34808 return SQLITE_CANTOPEN_ISDIR;
34811 if( isReadWrite ){
34812 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
34813 }else{
34814 dwDesiredAccess = GENERIC_READ;
34817 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
34818 ** created. SQLite doesn't use it to indicate "exclusive access"
34819 ** as it is usually understood.
34821 if( isExclusive ){
34822 /* Creates a new file, only if it does not already exist. */
34823 /* If the file exists, it fails. */
34824 dwCreationDisposition = CREATE_NEW;
34825 }else if( isCreate ){
34826 /* Open existing file, or create if it doesn't exist */
34827 dwCreationDisposition = OPEN_ALWAYS;
34828 }else{
34829 /* Opens a file, only if it exists. */
34830 dwCreationDisposition = OPEN_EXISTING;
34833 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
34835 if( isDelete ){
34836 #if SQLITE_OS_WINCE
34837 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
34838 isTemp = 1;
34839 #else
34840 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
34841 | FILE_ATTRIBUTE_HIDDEN
34842 | FILE_FLAG_DELETE_ON_CLOSE;
34843 #endif
34844 }else{
34845 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
34847 /* Reports from the internet are that performance is always
34848 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
34849 #if SQLITE_OS_WINCE
34850 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
34851 #endif
34853 if( isNT() ){
34854 #if SQLITE_OS_WINRT
34855 CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
34856 extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
34857 extendedParameters.dwFileAttributes =
34858 dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
34859 extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
34860 extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
34861 extendedParameters.lpSecurityAttributes = NULL;
34862 extendedParameters.hTemplateFile = NULL;
34863 while( (h = osCreateFile2((LPCWSTR)zConverted,
34864 dwDesiredAccess,
34865 dwShareMode,
34866 dwCreationDisposition,
34867 &extendedParameters))==INVALID_HANDLE_VALUE &&
34868 retryIoerr(&cnt, &lastErrno) ){
34869 /* Noop */
34871 #else
34872 while( (h = osCreateFileW((LPCWSTR)zConverted,
34873 dwDesiredAccess,
34874 dwShareMode, NULL,
34875 dwCreationDisposition,
34876 dwFlagsAndAttributes,
34877 NULL))==INVALID_HANDLE_VALUE &&
34878 retryIoerr(&cnt, &lastErrno) ){
34879 /* Noop */
34881 #endif
34883 #ifdef SQLITE_WIN32_HAS_ANSI
34884 else{
34885 while( (h = osCreateFileA((LPCSTR)zConverted,
34886 dwDesiredAccess,
34887 dwShareMode, NULL,
34888 dwCreationDisposition,
34889 dwFlagsAndAttributes,
34890 NULL))==INVALID_HANDLE_VALUE &&
34891 retryIoerr(&cnt, &lastErrno) ){
34892 /* Noop */
34895 #endif
34896 logIoerr(cnt);
34898 OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
34899 dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
34901 if( h==INVALID_HANDLE_VALUE ){
34902 pFile->lastErrno = lastErrno;
34903 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
34904 sqlite3_free(zConverted);
34905 if( isReadWrite && !isExclusive ){
34906 return winOpen(pVfs, zName, id,
34907 ((flags|SQLITE_OPEN_READONLY) &
34908 ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
34909 pOutFlags);
34910 }else{
34911 return SQLITE_CANTOPEN_BKPT;
34915 if( pOutFlags ){
34916 if( isReadWrite ){
34917 *pOutFlags = SQLITE_OPEN_READWRITE;
34918 }else{
34919 *pOutFlags = SQLITE_OPEN_READONLY;
34923 OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
34924 "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
34925 *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
34927 #if SQLITE_OS_WINCE
34928 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
34929 && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
34931 osCloseHandle(h);
34932 sqlite3_free(zConverted);
34933 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
34934 return rc;
34936 if( isTemp ){
34937 pFile->zDeleteOnClose = zConverted;
34938 }else
34939 #endif
34941 sqlite3_free(zConverted);
34944 pFile->pMethod = &winIoMethod;
34945 pFile->pVfs = pVfs;
34946 pFile->h = h;
34947 if( isReadonly ){
34948 pFile->ctrlFlags |= WINFILE_RDONLY;
34950 if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
34951 pFile->ctrlFlags |= WINFILE_PSOW;
34953 pFile->lastErrno = NO_ERROR;
34954 pFile->zPath = zName;
34955 #if SQLITE_MAX_MMAP_SIZE>0
34956 pFile->hMap = NULL;
34957 pFile->pMapRegion = 0;
34958 pFile->mmapSize = 0;
34959 pFile->mmapSizeActual = 0;
34960 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
34961 #endif
34963 OpenCounter(+1);
34964 return rc;
34968 ** Delete the named file.
34970 ** Note that Windows does not allow a file to be deleted if some other
34971 ** process has it open. Sometimes a virus scanner or indexing program
34972 ** will open a journal file shortly after it is created in order to do
34973 ** whatever it does. While this other process is holding the
34974 ** file open, we will be unable to delete it. To work around this
34975 ** problem, we delay 100 milliseconds and try to delete again. Up
34976 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
34977 ** up and returning an error.
34979 static int winDelete(
34980 sqlite3_vfs *pVfs, /* Not used on win32 */
34981 const char *zFilename, /* Name of file to delete */
34982 int syncDir /* Not used on win32 */
34984 int cnt = 0;
34985 int rc;
34986 DWORD attr;
34987 DWORD lastErrno;
34988 void *zConverted;
34989 UNUSED_PARAMETER(pVfs);
34990 UNUSED_PARAMETER(syncDir);
34992 SimulateIOError(return SQLITE_IOERR_DELETE);
34993 OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
34995 zConverted = convertUtf8Filename(zFilename);
34996 if( zConverted==0 ){
34997 return SQLITE_IOERR_NOMEM;
34999 if( isNT() ){
35000 do {
35001 #if SQLITE_OS_WINRT
35002 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35003 memset(&sAttrData, 0, sizeof(sAttrData));
35004 if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
35005 &sAttrData) ){
35006 attr = sAttrData.dwFileAttributes;
35007 }else{
35008 lastErrno = osGetLastError();
35009 if( lastErrno==ERROR_FILE_NOT_FOUND
35010 || lastErrno==ERROR_PATH_NOT_FOUND ){
35011 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35012 }else{
35013 rc = SQLITE_ERROR;
35015 break;
35017 #else
35018 attr = osGetFileAttributesW(zConverted);
35019 #endif
35020 if ( attr==INVALID_FILE_ATTRIBUTES ){
35021 lastErrno = osGetLastError();
35022 if( lastErrno==ERROR_FILE_NOT_FOUND
35023 || lastErrno==ERROR_PATH_NOT_FOUND ){
35024 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35025 }else{
35026 rc = SQLITE_ERROR;
35028 break;
35030 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
35031 rc = SQLITE_ERROR; /* Files only. */
35032 break;
35034 if ( osDeleteFileW(zConverted) ){
35035 rc = SQLITE_OK; /* Deleted OK. */
35036 break;
35038 if ( !retryIoerr(&cnt, &lastErrno) ){
35039 rc = SQLITE_ERROR; /* No more retries. */
35040 break;
35042 } while(1);
35044 #ifdef SQLITE_WIN32_HAS_ANSI
35045 else{
35046 do {
35047 attr = osGetFileAttributesA(zConverted);
35048 if ( attr==INVALID_FILE_ATTRIBUTES ){
35049 lastErrno = osGetLastError();
35050 if( lastErrno==ERROR_FILE_NOT_FOUND
35051 || lastErrno==ERROR_PATH_NOT_FOUND ){
35052 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35053 }else{
35054 rc = SQLITE_ERROR;
35056 break;
35058 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
35059 rc = SQLITE_ERROR; /* Files only. */
35060 break;
35062 if ( osDeleteFileA(zConverted) ){
35063 rc = SQLITE_OK; /* Deleted OK. */
35064 break;
35066 if ( !retryIoerr(&cnt, &lastErrno) ){
35067 rc = SQLITE_ERROR; /* No more retries. */
35068 break;
35070 } while(1);
35072 #endif
35073 if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
35074 rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
35075 "winDelete", zFilename);
35076 }else{
35077 logIoerr(cnt);
35079 sqlite3_free(zConverted);
35080 OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
35081 return rc;
35085 ** Check the existence and status of a file.
35087 static int winAccess(
35088 sqlite3_vfs *pVfs, /* Not used on win32 */
35089 const char *zFilename, /* Name of file to check */
35090 int flags, /* Type of test to make on this file */
35091 int *pResOut /* OUT: Result */
35093 DWORD attr;
35094 int rc = 0;
35095 DWORD lastErrno;
35096 void *zConverted;
35097 UNUSED_PARAMETER(pVfs);
35099 SimulateIOError( return SQLITE_IOERR_ACCESS; );
35100 OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
35101 zFilename, flags, pResOut));
35103 zConverted = convertUtf8Filename(zFilename);
35104 if( zConverted==0 ){
35105 OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
35106 return SQLITE_IOERR_NOMEM;
35108 if( isNT() ){
35109 int cnt = 0;
35110 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35111 memset(&sAttrData, 0, sizeof(sAttrData));
35112 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
35113 GetFileExInfoStandard,
35114 &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
35115 if( rc ){
35116 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
35117 ** as if it does not exist.
35119 if( flags==SQLITE_ACCESS_EXISTS
35120 && sAttrData.nFileSizeHigh==0
35121 && sAttrData.nFileSizeLow==0 ){
35122 attr = INVALID_FILE_ATTRIBUTES;
35123 }else{
35124 attr = sAttrData.dwFileAttributes;
35126 }else{
35127 logIoerr(cnt);
35128 if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
35129 winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
35130 sqlite3_free(zConverted);
35131 return SQLITE_IOERR_ACCESS;
35132 }else{
35133 attr = INVALID_FILE_ATTRIBUTES;
35137 #ifdef SQLITE_WIN32_HAS_ANSI
35138 else{
35139 attr = osGetFileAttributesA((char*)zConverted);
35141 #endif
35142 sqlite3_free(zConverted);
35143 switch( flags ){
35144 case SQLITE_ACCESS_READ:
35145 case SQLITE_ACCESS_EXISTS:
35146 rc = attr!=INVALID_FILE_ATTRIBUTES;
35147 break;
35148 case SQLITE_ACCESS_READWRITE:
35149 rc = attr!=INVALID_FILE_ATTRIBUTES &&
35150 (attr & FILE_ATTRIBUTE_READONLY)==0;
35151 break;
35152 default:
35153 assert(!"Invalid flags argument");
35155 *pResOut = rc;
35156 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
35157 zFilename, pResOut, *pResOut));
35158 return SQLITE_OK;
35163 ** Returns non-zero if the specified path name should be used verbatim. If
35164 ** non-zero is returned from this function, the calling function must simply
35165 ** use the provided path name verbatim -OR- resolve it into a full path name
35166 ** using the GetFullPathName Win32 API function (if available).
35168 static BOOL winIsVerbatimPathname(
35169 const char *zPathname
35172 ** If the path name starts with a forward slash or a backslash, it is either
35173 ** a legal UNC name, a volume relative path, or an absolute path name in the
35174 ** "Unix" format on Windows. There is no easy way to differentiate between
35175 ** the final two cases; therefore, we return the safer return value of TRUE
35176 ** so that callers of this function will simply use it verbatim.
35178 if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
35179 return TRUE;
35183 ** If the path name starts with a letter and a colon it is either a volume
35184 ** relative path or an absolute path. Callers of this function must not
35185 ** attempt to treat it as a relative path name (i.e. they should simply use
35186 ** it verbatim).
35188 if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
35189 return TRUE;
35193 ** If we get to this point, the path name should almost certainly be a purely
35194 ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
35196 return FALSE;
35200 ** Turn a relative pathname into a full pathname. Write the full
35201 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
35202 ** bytes in size.
35204 static int winFullPathname(
35205 sqlite3_vfs *pVfs, /* Pointer to vfs object */
35206 const char *zRelative, /* Possibly relative input path */
35207 int nFull, /* Size of output buffer in bytes */
35208 char *zFull /* Output buffer */
35211 #if defined(__CYGWIN__)
35212 SimulateIOError( return SQLITE_ERROR );
35213 UNUSED_PARAMETER(nFull);
35214 assert( pVfs->mxPathname>=SQLITE_WIN32_MAX_PATH );
35215 assert( nFull>=pVfs->mxPathname );
35216 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35218 ** NOTE: We are dealing with a relative path name and the data
35219 ** directory has been set. Therefore, use it as the basis
35220 ** for converting the relative path name to an absolute
35221 ** one by prepending the data directory and a slash.
35223 char zOut[SQLITE_WIN32_MAX_PATH+1];
35224 if( cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
35225 SQLITE_WIN32_MAX_PATH+1)<0 ){
35226 winLogError(SQLITE_CANTOPEN_FULLPATH, (DWORD)errno, "cygwin_conv_path",
35227 zRelative);
35228 return SQLITE_CANTOPEN_FULLPATH;
35230 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
35231 sqlite3_data_directory, zOut);
35232 }else{
35233 if( cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull)<0 ){
35234 winLogError(SQLITE_CANTOPEN_FULLPATH, (DWORD)errno, "cygwin_conv_path",
35235 zRelative);
35236 return SQLITE_CANTOPEN_FULLPATH;
35239 return SQLITE_OK;
35240 #endif
35242 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
35243 SimulateIOError( return SQLITE_ERROR );
35244 /* WinCE has no concept of a relative pathname, or so I am told. */
35245 /* WinRT has no way to convert a relative path to an absolute one. */
35246 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35248 ** NOTE: We are dealing with a relative path name and the data
35249 ** directory has been set. Therefore, use it as the basis
35250 ** for converting the relative path name to an absolute
35251 ** one by prepending the data directory and a backslash.
35253 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
35254 sqlite3_data_directory, zRelative);
35255 }else{
35256 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
35258 return SQLITE_OK;
35259 #endif
35261 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
35262 DWORD nByte;
35263 void *zConverted;
35264 char *zOut;
35266 /* If this path name begins with "/X:", where "X" is any alphabetic
35267 ** character, discard the initial "/" from the pathname.
35269 if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
35270 zRelative++;
35273 /* It's odd to simulate an io-error here, but really this is just
35274 ** using the io-error infrastructure to test that SQLite handles this
35275 ** function failing. This function could fail if, for example, the
35276 ** current working directory has been unlinked.
35278 SimulateIOError( return SQLITE_ERROR );
35279 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35281 ** NOTE: We are dealing with a relative path name and the data
35282 ** directory has been set. Therefore, use it as the basis
35283 ** for converting the relative path name to an absolute
35284 ** one by prepending the data directory and a backslash.
35286 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
35287 sqlite3_data_directory, zRelative);
35288 return SQLITE_OK;
35290 zConverted = convertUtf8Filename(zRelative);
35291 if( zConverted==0 ){
35292 return SQLITE_IOERR_NOMEM;
35294 if( isNT() ){
35295 LPWSTR zTemp;
35296 nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
35297 if( nByte==0 ){
35298 winLogError(SQLITE_ERROR, osGetLastError(),
35299 "GetFullPathNameW1", zConverted);
35300 sqlite3_free(zConverted);
35301 return SQLITE_CANTOPEN_FULLPATH;
35303 nByte += 3;
35304 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
35305 if( zTemp==0 ){
35306 sqlite3_free(zConverted);
35307 return SQLITE_IOERR_NOMEM;
35309 nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
35310 if( nByte==0 ){
35311 winLogError(SQLITE_ERROR, osGetLastError(),
35312 "GetFullPathNameW2", zConverted);
35313 sqlite3_free(zConverted);
35314 sqlite3_free(zTemp);
35315 return SQLITE_CANTOPEN_FULLPATH;
35317 sqlite3_free(zConverted);
35318 zOut = unicodeToUtf8(zTemp);
35319 sqlite3_free(zTemp);
35321 #ifdef SQLITE_WIN32_HAS_ANSI
35322 else{
35323 char *zTemp;
35324 nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
35325 if( nByte==0 ){
35326 winLogError(SQLITE_ERROR, osGetLastError(),
35327 "GetFullPathNameA1", zConverted);
35328 sqlite3_free(zConverted);
35329 return SQLITE_CANTOPEN_FULLPATH;
35331 nByte += 3;
35332 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
35333 if( zTemp==0 ){
35334 sqlite3_free(zConverted);
35335 return SQLITE_IOERR_NOMEM;
35337 nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
35338 if( nByte==0 ){
35339 winLogError(SQLITE_ERROR, osGetLastError(),
35340 "GetFullPathNameA2", zConverted);
35341 sqlite3_free(zConverted);
35342 sqlite3_free(zTemp);
35343 return SQLITE_CANTOPEN_FULLPATH;
35345 sqlite3_free(zConverted);
35346 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
35347 sqlite3_free(zTemp);
35349 #endif
35350 if( zOut ){
35351 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
35352 sqlite3_free(zOut);
35353 return SQLITE_OK;
35354 }else{
35355 return SQLITE_IOERR_NOMEM;
35357 #endif
35360 #ifndef SQLITE_OMIT_LOAD_EXTENSION
35362 ** Interfaces for opening a shared library, finding entry points
35363 ** within the shared library, and closing the shared library.
35366 ** Interfaces for opening a shared library, finding entry points
35367 ** within the shared library, and closing the shared library.
35369 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
35370 HANDLE h;
35371 void *zConverted = convertUtf8Filename(zFilename);
35372 UNUSED_PARAMETER(pVfs);
35373 if( zConverted==0 ){
35374 return 0;
35376 if( isNT() ){
35377 #if SQLITE_OS_WINRT
35378 h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
35379 #else
35380 h = osLoadLibraryW((LPCWSTR)zConverted);
35381 #endif
35383 #ifdef SQLITE_WIN32_HAS_ANSI
35384 else{
35385 h = osLoadLibraryA((char*)zConverted);
35387 #endif
35388 sqlite3_free(zConverted);
35389 return (void*)h;
35391 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
35392 UNUSED_PARAMETER(pVfs);
35393 getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
35395 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
35396 UNUSED_PARAMETER(pVfs);
35397 return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
35399 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
35400 UNUSED_PARAMETER(pVfs);
35401 osFreeLibrary((HANDLE)pHandle);
35403 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
35404 #define winDlOpen 0
35405 #define winDlError 0
35406 #define winDlSym 0
35407 #define winDlClose 0
35408 #endif
35412 ** Write up to nBuf bytes of randomness into zBuf.
35414 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35415 int n = 0;
35416 UNUSED_PARAMETER(pVfs);
35417 #if defined(SQLITE_TEST)
35418 n = nBuf;
35419 memset(zBuf, 0, nBuf);
35420 #else
35421 if( sizeof(SYSTEMTIME)<=nBuf-n ){
35422 SYSTEMTIME x;
35423 osGetSystemTime(&x);
35424 memcpy(&zBuf[n], &x, sizeof(x));
35425 n += sizeof(x);
35427 if( sizeof(DWORD)<=nBuf-n ){
35428 DWORD pid = osGetCurrentProcessId();
35429 memcpy(&zBuf[n], &pid, sizeof(pid));
35430 n += sizeof(pid);
35432 #if SQLITE_OS_WINRT
35433 if( sizeof(ULONGLONG)<=nBuf-n ){
35434 ULONGLONG cnt = osGetTickCount64();
35435 memcpy(&zBuf[n], &cnt, sizeof(cnt));
35436 n += sizeof(cnt);
35438 #else
35439 if( sizeof(DWORD)<=nBuf-n ){
35440 DWORD cnt = osGetTickCount();
35441 memcpy(&zBuf[n], &cnt, sizeof(cnt));
35442 n += sizeof(cnt);
35444 #endif
35445 if( sizeof(LARGE_INTEGER)<=nBuf-n ){
35446 LARGE_INTEGER i;
35447 osQueryPerformanceCounter(&i);
35448 memcpy(&zBuf[n], &i, sizeof(i));
35449 n += sizeof(i);
35451 #endif
35452 return n;
35457 ** Sleep for a little while. Return the amount of time slept.
35459 static int winSleep(sqlite3_vfs *pVfs, int microsec){
35460 sqlite3_win32_sleep((microsec+999)/1000);
35461 UNUSED_PARAMETER(pVfs);
35462 return ((microsec+999)/1000)*1000;
35466 ** The following variable, if set to a non-zero value, is interpreted as
35467 ** the number of seconds since 1970 and is used to set the result of
35468 ** sqlite3OsCurrentTime() during testing.
35470 #ifdef SQLITE_TEST
35471 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
35472 #endif
35475 ** Find the current time (in Universal Coordinated Time). Write into *piNow
35476 ** the current time and date as a Julian Day number times 86_400_000. In
35477 ** other words, write into *piNow the number of milliseconds since the Julian
35478 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
35479 ** proleptic Gregorian calendar.
35481 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
35482 ** cannot be found.
35484 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
35485 /* FILETIME structure is a 64-bit value representing the number of
35486 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
35488 FILETIME ft;
35489 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
35490 #ifdef SQLITE_TEST
35491 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
35492 #endif
35493 /* 2^32 - to avoid use of LL and warnings in gcc */
35494 static const sqlite3_int64 max32BitValue =
35495 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
35496 (sqlite3_int64)294967296;
35498 #if SQLITE_OS_WINCE
35499 SYSTEMTIME time;
35500 osGetSystemTime(&time);
35501 /* if SystemTimeToFileTime() fails, it returns zero. */
35502 if (!osSystemTimeToFileTime(&time,&ft)){
35503 return SQLITE_ERROR;
35505 #else
35506 osGetSystemTimeAsFileTime( &ft );
35507 #endif
35509 *piNow = winFiletimeEpoch +
35510 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
35511 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
35513 #ifdef SQLITE_TEST
35514 if( sqlite3_current_time ){
35515 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
35517 #endif
35518 UNUSED_PARAMETER(pVfs);
35519 return SQLITE_OK;
35523 ** Find the current time (in Universal Coordinated Time). Write the
35524 ** current time and date as a Julian Day number into *prNow and
35525 ** return 0. Return 1 if the time and date cannot be found.
35527 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
35528 int rc;
35529 sqlite3_int64 i;
35530 rc = winCurrentTimeInt64(pVfs, &i);
35531 if( !rc ){
35532 *prNow = i/86400000.0;
35534 return rc;
35538 ** The idea is that this function works like a combination of
35539 ** GetLastError() and FormatMessage() on Windows (or errno and
35540 ** strerror_r() on Unix). After an error is returned by an OS
35541 ** function, SQLite calls this function with zBuf pointing to
35542 ** a buffer of nBuf bytes. The OS layer should populate the
35543 ** buffer with a nul-terminated UTF-8 encoded error message
35544 ** describing the last IO error to have occurred within the calling
35545 ** thread.
35547 ** If the error message is too large for the supplied buffer,
35548 ** it should be truncated. The return value of xGetLastError
35549 ** is zero if the error message fits in the buffer, or non-zero
35550 ** otherwise (if the message was truncated). If non-zero is returned,
35551 ** then it is not necessary to include the nul-terminator character
35552 ** in the output buffer.
35554 ** Not supplying an error message will have no adverse effect
35555 ** on SQLite. It is fine to have an implementation that never
35556 ** returns an error message:
35558 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35559 ** assert(zBuf[0]=='\0');
35560 ** return 0;
35561 ** }
35563 ** However if an error message is supplied, it will be incorporated
35564 ** by sqlite into the error message available to the user using
35565 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
35567 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35568 UNUSED_PARAMETER(pVfs);
35569 return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
35573 ** Initialize and deinitialize the operating system interface.
35575 SQLITE_API int sqlite3_os_init(void){
35576 static sqlite3_vfs winVfs = {
35577 3, /* iVersion */
35578 sizeof(winFile), /* szOsFile */
35579 SQLITE_WIN32_MAX_PATH, /* mxPathname */
35580 0, /* pNext */
35581 "win32", /* zName */
35582 0, /* pAppData */
35583 winOpen, /* xOpen */
35584 winDelete, /* xDelete */
35585 winAccess, /* xAccess */
35586 winFullPathname, /* xFullPathname */
35587 winDlOpen, /* xDlOpen */
35588 winDlError, /* xDlError */
35589 winDlSym, /* xDlSym */
35590 winDlClose, /* xDlClose */
35591 winRandomness, /* xRandomness */
35592 winSleep, /* xSleep */
35593 winCurrentTime, /* xCurrentTime */
35594 winGetLastError, /* xGetLastError */
35595 winCurrentTimeInt64, /* xCurrentTimeInt64 */
35596 winSetSystemCall, /* xSetSystemCall */
35597 winGetSystemCall, /* xGetSystemCall */
35598 winNextSystemCall, /* xNextSystemCall */
35601 /* Double-check that the aSyscall[] array has been constructed
35602 ** correctly. See ticket [bb3a86e890c8e96ab] */
35603 assert( ArraySize(aSyscall)==74 );
35605 /* get memory map allocation granularity */
35606 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
35607 #if SQLITE_OS_WINRT
35608 osGetNativeSystemInfo(&winSysInfo);
35609 #else
35610 osGetSystemInfo(&winSysInfo);
35611 #endif
35612 assert( winSysInfo.dwAllocationGranularity>0 );
35613 assert( winSysInfo.dwPageSize>0 );
35615 sqlite3_vfs_register(&winVfs, 1);
35616 return SQLITE_OK;
35619 SQLITE_API int sqlite3_os_end(void){
35620 #if SQLITE_OS_WINRT
35621 if( sleepObj!=NULL ){
35622 osCloseHandle(sleepObj);
35623 sleepObj = NULL;
35625 #endif
35626 return SQLITE_OK;
35629 #endif /* SQLITE_OS_WIN */
35631 /************** End of os_win.c **********************************************/
35632 /************** Begin file bitvec.c ******************************************/
35634 ** 2008 February 16
35636 ** The author disclaims copyright to this source code. In place of
35637 ** a legal notice, here is a blessing:
35639 ** May you do good and not evil.
35640 ** May you find forgiveness for yourself and forgive others.
35641 ** May you share freely, never taking more than you give.
35643 *************************************************************************
35644 ** This file implements an object that represents a fixed-length
35645 ** bitmap. Bits are numbered starting with 1.
35647 ** A bitmap is used to record which pages of a database file have been
35648 ** journalled during a transaction, or which pages have the "dont-write"
35649 ** property. Usually only a few pages are meet either condition.
35650 ** So the bitmap is usually sparse and has low cardinality.
35651 ** But sometimes (for example when during a DROP of a large table) most
35652 ** or all of the pages in a database can get journalled. In those cases,
35653 ** the bitmap becomes dense with high cardinality. The algorithm needs
35654 ** to handle both cases well.
35656 ** The size of the bitmap is fixed when the object is created.
35658 ** All bits are clear when the bitmap is created. Individual bits
35659 ** may be set or cleared one at a time.
35661 ** Test operations are about 100 times more common that set operations.
35662 ** Clear operations are exceedingly rare. There are usually between
35663 ** 5 and 500 set operations per Bitvec object, though the number of sets can
35664 ** sometimes grow into tens of thousands or larger. The size of the
35665 ** Bitvec object is the number of pages in the database file at the
35666 ** start of a transaction, and is thus usually less than a few thousand,
35667 ** but can be as large as 2 billion for a really big database.
35670 /* Size of the Bitvec structure in bytes. */
35671 #define BITVEC_SZ 512
35673 /* Round the union size down to the nearest pointer boundary, since that's how
35674 ** it will be aligned within the Bitvec struct. */
35675 #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
35677 /* Type of the array "element" for the bitmap representation.
35678 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
35679 ** Setting this to the "natural word" size of your CPU may improve
35680 ** performance. */
35681 #define BITVEC_TELEM u8
35682 /* Size, in bits, of the bitmap element. */
35683 #define BITVEC_SZELEM 8
35684 /* Number of elements in a bitmap array. */
35685 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
35686 /* Number of bits in the bitmap array. */
35687 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
35689 /* Number of u32 values in hash table. */
35690 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
35691 /* Maximum number of entries in hash table before
35692 ** sub-dividing and re-hashing. */
35693 #define BITVEC_MXHASH (BITVEC_NINT/2)
35694 /* Hashing function for the aHash representation.
35695 ** Empirical testing showed that the *37 multiplier
35696 ** (an arbitrary prime)in the hash function provided
35697 ** no fewer collisions than the no-op *1. */
35698 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
35700 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
35704 ** A bitmap is an instance of the following structure.
35706 ** This bitmap records the existence of zero or more bits
35707 ** with values between 1 and iSize, inclusive.
35709 ** There are three possible representations of the bitmap.
35710 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
35711 ** bitmap. The least significant bit is bit 1.
35713 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
35714 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
35716 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
35717 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
35718 ** handles up to iDivisor separate values of i. apSub[0] holds
35719 ** values between 1 and iDivisor. apSub[1] holds values between
35720 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
35721 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
35722 ** to hold deal with values between 1 and iDivisor.
35724 struct Bitvec {
35725 u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
35726 u32 nSet; /* Number of bits that are set - only valid for aHash
35727 ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
35728 ** this would be 125. */
35729 u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
35730 /* Should >=0 for apSub element. */
35731 /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
35732 /* For a BITVEC_SZ of 512, this would be 34,359,739. */
35733 union {
35734 BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
35735 u32 aHash[BITVEC_NINT]; /* Hash table representation */
35736 Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
35737 } u;
35741 ** Create a new bitmap object able to handle bits between 0 and iSize,
35742 ** inclusive. Return a pointer to the new object. Return NULL if
35743 ** malloc fails.
35745 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
35746 Bitvec *p;
35747 assert( sizeof(*p)==BITVEC_SZ );
35748 p = sqlite3MallocZero( sizeof(*p) );
35749 if( p ){
35750 p->iSize = iSize;
35752 return p;
35756 ** Check to see if the i-th bit is set. Return true or false.
35757 ** If p is NULL (if the bitmap has not been created) or if
35758 ** i is out of range, then return false.
35760 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
35761 if( p==0 ) return 0;
35762 if( i>p->iSize || i==0 ) return 0;
35763 i--;
35764 while( p->iDivisor ){
35765 u32 bin = i/p->iDivisor;
35766 i = i%p->iDivisor;
35767 p = p->u.apSub[bin];
35768 if (!p) {
35769 return 0;
35772 if( p->iSize<=BITVEC_NBIT ){
35773 return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
35774 } else{
35775 u32 h = BITVEC_HASH(i++);
35776 while( p->u.aHash[h] ){
35777 if( p->u.aHash[h]==i ) return 1;
35778 h = (h+1) % BITVEC_NINT;
35780 return 0;
35785 ** Set the i-th bit. Return 0 on success and an error code if
35786 ** anything goes wrong.
35788 ** This routine might cause sub-bitmaps to be allocated. Failing
35789 ** to get the memory needed to hold the sub-bitmap is the only
35790 ** that can go wrong with an insert, assuming p and i are valid.
35792 ** The calling function must ensure that p is a valid Bitvec object
35793 ** and that the value for "i" is within range of the Bitvec object.
35794 ** Otherwise the behavior is undefined.
35796 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
35797 u32 h;
35798 if( p==0 ) return SQLITE_OK;
35799 assert( i>0 );
35800 assert( i<=p->iSize );
35801 i--;
35802 while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
35803 u32 bin = i/p->iDivisor;
35804 i = i%p->iDivisor;
35805 if( p->u.apSub[bin]==0 ){
35806 p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
35807 if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
35809 p = p->u.apSub[bin];
35811 if( p->iSize<=BITVEC_NBIT ){
35812 p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
35813 return SQLITE_OK;
35815 h = BITVEC_HASH(i++);
35816 /* if there wasn't a hash collision, and this doesn't */
35817 /* completely fill the hash, then just add it without */
35818 /* worring about sub-dividing and re-hashing. */
35819 if( !p->u.aHash[h] ){
35820 if (p->nSet<(BITVEC_NINT-1)) {
35821 goto bitvec_set_end;
35822 } else {
35823 goto bitvec_set_rehash;
35826 /* there was a collision, check to see if it's already */
35827 /* in hash, if not, try to find a spot for it */
35828 do {
35829 if( p->u.aHash[h]==i ) return SQLITE_OK;
35830 h++;
35831 if( h>=BITVEC_NINT ) h = 0;
35832 } while( p->u.aHash[h] );
35833 /* we didn't find it in the hash. h points to the first */
35834 /* available free spot. check to see if this is going to */
35835 /* make our hash too "full". */
35836 bitvec_set_rehash:
35837 if( p->nSet>=BITVEC_MXHASH ){
35838 unsigned int j;
35839 int rc;
35840 u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
35841 if( aiValues==0 ){
35842 return SQLITE_NOMEM;
35843 }else{
35844 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
35845 memset(p->u.apSub, 0, sizeof(p->u.apSub));
35846 p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
35847 rc = sqlite3BitvecSet(p, i);
35848 for(j=0; j<BITVEC_NINT; j++){
35849 if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
35851 sqlite3StackFree(0, aiValues);
35852 return rc;
35855 bitvec_set_end:
35856 p->nSet++;
35857 p->u.aHash[h] = i;
35858 return SQLITE_OK;
35862 ** Clear the i-th bit.
35864 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
35865 ** that BitvecClear can use to rebuilt its hash table.
35867 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
35868 if( p==0 ) return;
35869 assert( i>0 );
35870 i--;
35871 while( p->iDivisor ){
35872 u32 bin = i/p->iDivisor;
35873 i = i%p->iDivisor;
35874 p = p->u.apSub[bin];
35875 if (!p) {
35876 return;
35879 if( p->iSize<=BITVEC_NBIT ){
35880 p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
35881 }else{
35882 unsigned int j;
35883 u32 *aiValues = pBuf;
35884 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
35885 memset(p->u.aHash, 0, sizeof(p->u.aHash));
35886 p->nSet = 0;
35887 for(j=0; j<BITVEC_NINT; j++){
35888 if( aiValues[j] && aiValues[j]!=(i+1) ){
35889 u32 h = BITVEC_HASH(aiValues[j]-1);
35890 p->nSet++;
35891 while( p->u.aHash[h] ){
35892 h++;
35893 if( h>=BITVEC_NINT ) h = 0;
35895 p->u.aHash[h] = aiValues[j];
35902 ** Destroy a bitmap object. Reclaim all memory used.
35904 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
35905 if( p==0 ) return;
35906 if( p->iDivisor ){
35907 unsigned int i;
35908 for(i=0; i<BITVEC_NPTR; i++){
35909 sqlite3BitvecDestroy(p->u.apSub[i]);
35912 sqlite3_free(p);
35916 ** Return the value of the iSize parameter specified when Bitvec *p
35917 ** was created.
35919 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
35920 return p->iSize;
35923 #ifndef SQLITE_OMIT_BUILTIN_TEST
35925 ** Let V[] be an array of unsigned characters sufficient to hold
35926 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
35927 ** Then the following macros can be used to set, clear, or test
35928 ** individual bits within V.
35930 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
35931 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
35932 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
35935 ** This routine runs an extensive test of the Bitvec code.
35937 ** The input is an array of integers that acts as a program
35938 ** to test the Bitvec. The integers are opcodes followed
35939 ** by 0, 1, or 3 operands, depending on the opcode. Another
35940 ** opcode follows immediately after the last operand.
35942 ** There are 6 opcodes numbered from 0 through 5. 0 is the
35943 ** "halt" opcode and causes the test to end.
35945 ** 0 Halt and return the number of errors
35946 ** 1 N S X Set N bits beginning with S and incrementing by X
35947 ** 2 N S X Clear N bits beginning with S and incrementing by X
35948 ** 3 N Set N randomly chosen bits
35949 ** 4 N Clear N randomly chosen bits
35950 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
35952 ** The opcodes 1 through 4 perform set and clear operations are performed
35953 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
35954 ** Opcode 5 works on the linear array only, not on the Bitvec.
35955 ** Opcode 5 is used to deliberately induce a fault in order to
35956 ** confirm that error detection works.
35958 ** At the conclusion of the test the linear array is compared
35959 ** against the Bitvec object. If there are any differences,
35960 ** an error is returned. If they are the same, zero is returned.
35962 ** If a memory allocation error occurs, return -1.
35964 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
35965 Bitvec *pBitvec = 0;
35966 unsigned char *pV = 0;
35967 int rc = -1;
35968 int i, nx, pc, op;
35969 void *pTmpSpace;
35971 /* Allocate the Bitvec to be tested and a linear array of
35972 ** bits to act as the reference */
35973 pBitvec = sqlite3BitvecCreate( sz );
35974 pV = sqlite3MallocZero( (sz+7)/8 + 1 );
35975 pTmpSpace = sqlite3_malloc(BITVEC_SZ);
35976 if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
35978 /* NULL pBitvec tests */
35979 sqlite3BitvecSet(0, 1);
35980 sqlite3BitvecClear(0, 1, pTmpSpace);
35982 /* Run the program */
35983 pc = 0;
35984 while( (op = aOp[pc])!=0 ){
35985 switch( op ){
35986 case 1:
35987 case 2:
35988 case 5: {
35989 nx = 4;
35990 i = aOp[pc+2] - 1;
35991 aOp[pc+2] += aOp[pc+3];
35992 break;
35994 case 3:
35995 case 4:
35996 default: {
35997 nx = 2;
35998 sqlite3_randomness(sizeof(i), &i);
35999 break;
36002 if( (--aOp[pc+1]) > 0 ) nx = 0;
36003 pc += nx;
36004 i = (i & 0x7fffffff)%sz;
36005 if( (op & 1)!=0 ){
36006 SETBIT(pV, (i+1));
36007 if( op!=5 ){
36008 if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
36010 }else{
36011 CLEARBIT(pV, (i+1));
36012 sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
36016 /* Test to make sure the linear array exactly matches the
36017 ** Bitvec object. Start with the assumption that they do
36018 ** match (rc==0). Change rc to non-zero if a discrepancy
36019 ** is found.
36021 rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
36022 + sqlite3BitvecTest(pBitvec, 0)
36023 + (sqlite3BitvecSize(pBitvec) - sz);
36024 for(i=1; i<=sz; i++){
36025 if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
36026 rc = i;
36027 break;
36031 /* Free allocated structure */
36032 bitvec_end:
36033 sqlite3_free(pTmpSpace);
36034 sqlite3_free(pV);
36035 sqlite3BitvecDestroy(pBitvec);
36036 return rc;
36038 #endif /* SQLITE_OMIT_BUILTIN_TEST */
36040 /************** End of bitvec.c **********************************************/
36041 /************** Begin file pcache.c ******************************************/
36043 ** 2008 August 05
36045 ** The author disclaims copyright to this source code. In place of
36046 ** a legal notice, here is a blessing:
36048 ** May you do good and not evil.
36049 ** May you find forgiveness for yourself and forgive others.
36050 ** May you share freely, never taking more than you give.
36052 *************************************************************************
36053 ** This file implements that page cache.
36057 ** A complete page cache is an instance of this structure.
36059 struct PCache {
36060 PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
36061 PgHdr *pSynced; /* Last synced page in dirty page list */
36062 int nRef; /* Number of referenced pages */
36063 int szCache; /* Configured cache size */
36064 int szPage; /* Size of every page in this cache */
36065 int szExtra; /* Size of extra space for each page */
36066 int bPurgeable; /* True if pages are on backing store */
36067 int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
36068 void *pStress; /* Argument to xStress */
36069 sqlite3_pcache *pCache; /* Pluggable cache module */
36070 PgHdr *pPage1; /* Reference to page 1 */
36074 ** Some of the assert() macros in this code are too expensive to run
36075 ** even during normal debugging. Use them only rarely on long-running
36076 ** tests. Enable the expensive asserts using the
36077 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
36079 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
36080 # define expensive_assert(X) assert(X)
36081 #else
36082 # define expensive_assert(X)
36083 #endif
36085 /********************************** Linked List Management ********************/
36087 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
36089 ** Check that the pCache->pSynced variable is set correctly. If it
36090 ** is not, either fail an assert or return zero. Otherwise, return
36091 ** non-zero. This is only used in debugging builds, as follows:
36093 ** expensive_assert( pcacheCheckSynced(pCache) );
36095 static int pcacheCheckSynced(PCache *pCache){
36096 PgHdr *p;
36097 for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
36098 assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
36100 return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
36102 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
36105 ** Remove page pPage from the list of dirty pages.
36107 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
36108 PCache *p = pPage->pCache;
36110 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
36111 assert( pPage->pDirtyPrev || pPage==p->pDirty );
36113 /* Update the PCache1.pSynced variable if necessary. */
36114 if( p->pSynced==pPage ){
36115 PgHdr *pSynced = pPage->pDirtyPrev;
36116 while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
36117 pSynced = pSynced->pDirtyPrev;
36119 p->pSynced = pSynced;
36122 if( pPage->pDirtyNext ){
36123 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
36124 }else{
36125 assert( pPage==p->pDirtyTail );
36126 p->pDirtyTail = pPage->pDirtyPrev;
36128 if( pPage->pDirtyPrev ){
36129 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
36130 }else{
36131 assert( pPage==p->pDirty );
36132 p->pDirty = pPage->pDirtyNext;
36134 pPage->pDirtyNext = 0;
36135 pPage->pDirtyPrev = 0;
36137 expensive_assert( pcacheCheckSynced(p) );
36141 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
36142 ** pPage).
36144 static void pcacheAddToDirtyList(PgHdr *pPage){
36145 PCache *p = pPage->pCache;
36147 assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
36149 pPage->pDirtyNext = p->pDirty;
36150 if( pPage->pDirtyNext ){
36151 assert( pPage->pDirtyNext->pDirtyPrev==0 );
36152 pPage->pDirtyNext->pDirtyPrev = pPage;
36154 p->pDirty = pPage;
36155 if( !p->pDirtyTail ){
36156 p->pDirtyTail = pPage;
36158 if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
36159 p->pSynced = pPage;
36161 expensive_assert( pcacheCheckSynced(p) );
36165 ** Wrapper around the pluggable caches xUnpin method. If the cache is
36166 ** being used for an in-memory database, this function is a no-op.
36168 static void pcacheUnpin(PgHdr *p){
36169 PCache *pCache = p->pCache;
36170 if( pCache->bPurgeable ){
36171 if( p->pgno==1 ){
36172 pCache->pPage1 = 0;
36174 sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
36178 /*************************************************** General Interfaces ******
36180 ** Initialize and shutdown the page cache subsystem. Neither of these
36181 ** functions are threadsafe.
36183 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
36184 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
36185 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
36186 ** built-in default page cache is used instead of the application defined
36187 ** page cache. */
36188 sqlite3PCacheSetDefault();
36190 return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
36192 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
36193 if( sqlite3GlobalConfig.pcache2.xShutdown ){
36194 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
36195 sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
36200 ** Return the size in bytes of a PCache object.
36202 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
36205 ** Create a new PCache object. Storage space to hold the object
36206 ** has already been allocated and is passed in as the p pointer.
36207 ** The caller discovers how much space needs to be allocated by
36208 ** calling sqlite3PcacheSize().
36210 SQLITE_PRIVATE void sqlite3PcacheOpen(
36211 int szPage, /* Size of every page */
36212 int szExtra, /* Extra space associated with each page */
36213 int bPurgeable, /* True if pages are on backing store */
36214 int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
36215 void *pStress, /* Argument to xStress */
36216 PCache *p /* Preallocated space for the PCache */
36218 memset(p, 0, sizeof(PCache));
36219 p->szPage = szPage;
36220 p->szExtra = szExtra;
36221 p->bPurgeable = bPurgeable;
36222 p->xStress = xStress;
36223 p->pStress = pStress;
36224 p->szCache = 100;
36228 ** Change the page size for PCache object. The caller must ensure that there
36229 ** are no outstanding page references when this function is called.
36231 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
36232 assert( pCache->nRef==0 && pCache->pDirty==0 );
36233 if( pCache->pCache ){
36234 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
36235 pCache->pCache = 0;
36236 pCache->pPage1 = 0;
36238 pCache->szPage = szPage;
36242 ** Compute the number of pages of cache requested.
36244 static int numberOfCachePages(PCache *p){
36245 if( p->szCache>=0 ){
36246 return p->szCache;
36247 }else{
36248 return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
36253 ** Try to obtain a page from the cache.
36255 SQLITE_PRIVATE int sqlite3PcacheFetch(
36256 PCache *pCache, /* Obtain the page from this cache */
36257 Pgno pgno, /* Page number to obtain */
36258 int createFlag, /* If true, create page if it does not exist already */
36259 PgHdr **ppPage /* Write the page here */
36261 sqlite3_pcache_page *pPage = 0;
36262 PgHdr *pPgHdr = 0;
36263 int eCreate;
36265 assert( pCache!=0 );
36266 assert( createFlag==1 || createFlag==0 );
36267 assert( pgno>0 );
36269 /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
36270 ** allocate it now.
36272 if( !pCache->pCache && createFlag ){
36273 sqlite3_pcache *p;
36274 p = sqlite3GlobalConfig.pcache2.xCreate(
36275 pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
36277 if( !p ){
36278 return SQLITE_NOMEM;
36280 sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
36281 pCache->pCache = p;
36284 eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
36285 if( pCache->pCache ){
36286 pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
36289 if( !pPage && eCreate==1 ){
36290 PgHdr *pPg;
36292 /* Find a dirty page to write-out and recycle. First try to find a
36293 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
36294 ** cleared), but if that is not possible settle for any other
36295 ** unreferenced dirty page.
36297 expensive_assert( pcacheCheckSynced(pCache) );
36298 for(pPg=pCache->pSynced;
36299 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
36300 pPg=pPg->pDirtyPrev
36302 pCache->pSynced = pPg;
36303 if( !pPg ){
36304 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
36306 if( pPg ){
36307 int rc;
36308 #ifdef SQLITE_LOG_CACHE_SPILL
36309 sqlite3_log(SQLITE_FULL,
36310 "spill page %d making room for %d - cache used: %d/%d",
36311 pPg->pgno, pgno,
36312 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
36313 numberOfCachePages(pCache));
36314 #endif
36315 rc = pCache->xStress(pCache->pStress, pPg);
36316 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
36317 return rc;
36321 pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
36324 if( pPage ){
36325 pPgHdr = (PgHdr *)pPage->pExtra;
36327 if( !pPgHdr->pPage ){
36328 memset(pPgHdr, 0, sizeof(PgHdr));
36329 pPgHdr->pPage = pPage;
36330 pPgHdr->pData = pPage->pBuf;
36331 pPgHdr->pExtra = (void *)&pPgHdr[1];
36332 memset(pPgHdr->pExtra, 0, pCache->szExtra);
36333 pPgHdr->pCache = pCache;
36334 pPgHdr->pgno = pgno;
36336 assert( pPgHdr->pCache==pCache );
36337 assert( pPgHdr->pgno==pgno );
36338 assert( pPgHdr->pData==pPage->pBuf );
36339 assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
36341 if( 0==pPgHdr->nRef ){
36342 pCache->nRef++;
36344 pPgHdr->nRef++;
36345 if( pgno==1 ){
36346 pCache->pPage1 = pPgHdr;
36349 *ppPage = pPgHdr;
36350 return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
36354 ** Decrement the reference count on a page. If the page is clean and the
36355 ** reference count drops to 0, then it is made elible for recycling.
36357 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
36358 assert( p->nRef>0 );
36359 p->nRef--;
36360 if( p->nRef==0 ){
36361 PCache *pCache = p->pCache;
36362 pCache->nRef--;
36363 if( (p->flags&PGHDR_DIRTY)==0 ){
36364 pcacheUnpin(p);
36365 }else{
36366 /* Move the page to the head of the dirty list. */
36367 pcacheRemoveFromDirtyList(p);
36368 pcacheAddToDirtyList(p);
36374 ** Increase the reference count of a supplied page by 1.
36376 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
36377 assert(p->nRef>0);
36378 p->nRef++;
36382 ** Drop a page from the cache. There must be exactly one reference to the
36383 ** page. This function deletes that reference, so after it returns the
36384 ** page pointed to by p is invalid.
36386 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
36387 PCache *pCache;
36388 assert( p->nRef==1 );
36389 if( p->flags&PGHDR_DIRTY ){
36390 pcacheRemoveFromDirtyList(p);
36392 pCache = p->pCache;
36393 pCache->nRef--;
36394 if( p->pgno==1 ){
36395 pCache->pPage1 = 0;
36397 sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
36401 ** Make sure the page is marked as dirty. If it isn't dirty already,
36402 ** make it so.
36404 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
36405 p->flags &= ~PGHDR_DONT_WRITE;
36406 assert( p->nRef>0 );
36407 if( 0==(p->flags & PGHDR_DIRTY) ){
36408 p->flags |= PGHDR_DIRTY;
36409 pcacheAddToDirtyList( p);
36414 ** Make sure the page is marked as clean. If it isn't clean already,
36415 ** make it so.
36417 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
36418 if( (p->flags & PGHDR_DIRTY) ){
36419 pcacheRemoveFromDirtyList(p);
36420 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
36421 if( p->nRef==0 ){
36422 pcacheUnpin(p);
36428 ** Make every page in the cache clean.
36430 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
36431 PgHdr *p;
36432 while( (p = pCache->pDirty)!=0 ){
36433 sqlite3PcacheMakeClean(p);
36438 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
36440 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
36441 PgHdr *p;
36442 for(p=pCache->pDirty; p; p=p->pDirtyNext){
36443 p->flags &= ~PGHDR_NEED_SYNC;
36445 pCache->pSynced = pCache->pDirtyTail;
36449 ** Change the page number of page p to newPgno.
36451 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
36452 PCache *pCache = p->pCache;
36453 assert( p->nRef>0 );
36454 assert( newPgno>0 );
36455 sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
36456 p->pgno = newPgno;
36457 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
36458 pcacheRemoveFromDirtyList(p);
36459 pcacheAddToDirtyList(p);
36464 ** Drop every cache entry whose page number is greater than "pgno". The
36465 ** caller must ensure that there are no outstanding references to any pages
36466 ** other than page 1 with a page number greater than pgno.
36468 ** If there is a reference to page 1 and the pgno parameter passed to this
36469 ** function is 0, then the data area associated with page 1 is zeroed, but
36470 ** the page object is not dropped.
36472 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
36473 if( pCache->pCache ){
36474 PgHdr *p;
36475 PgHdr *pNext;
36476 for(p=pCache->pDirty; p; p=pNext){
36477 pNext = p->pDirtyNext;
36478 /* This routine never gets call with a positive pgno except right
36479 ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
36480 ** it must be that pgno==0.
36482 assert( p->pgno>0 );
36483 if( ALWAYS(p->pgno>pgno) ){
36484 assert( p->flags&PGHDR_DIRTY );
36485 sqlite3PcacheMakeClean(p);
36488 if( pgno==0 && pCache->pPage1 ){
36489 memset(pCache->pPage1->pData, 0, pCache->szPage);
36490 pgno = 1;
36492 sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
36497 ** Close a cache.
36499 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
36500 if( pCache->pCache ){
36501 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
36506 ** Discard the contents of the cache.
36508 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
36509 sqlite3PcacheTruncate(pCache, 0);
36513 ** Merge two lists of pages connected by pDirty and in pgno order.
36514 ** Do not both fixing the pDirtyPrev pointers.
36516 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
36517 PgHdr result, *pTail;
36518 pTail = &result;
36519 while( pA && pB ){
36520 if( pA->pgno<pB->pgno ){
36521 pTail->pDirty = pA;
36522 pTail = pA;
36523 pA = pA->pDirty;
36524 }else{
36525 pTail->pDirty = pB;
36526 pTail = pB;
36527 pB = pB->pDirty;
36530 if( pA ){
36531 pTail->pDirty = pA;
36532 }else if( pB ){
36533 pTail->pDirty = pB;
36534 }else{
36535 pTail->pDirty = 0;
36537 return result.pDirty;
36541 ** Sort the list of pages in accending order by pgno. Pages are
36542 ** connected by pDirty pointers. The pDirtyPrev pointers are
36543 ** corrupted by this sort.
36545 ** Since there cannot be more than 2^31 distinct pages in a database,
36546 ** there cannot be more than 31 buckets required by the merge sorter.
36547 ** One extra bucket is added to catch overflow in case something
36548 ** ever changes to make the previous sentence incorrect.
36550 #define N_SORT_BUCKET 32
36551 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
36552 PgHdr *a[N_SORT_BUCKET], *p;
36553 int i;
36554 memset(a, 0, sizeof(a));
36555 while( pIn ){
36556 p = pIn;
36557 pIn = p->pDirty;
36558 p->pDirty = 0;
36559 for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
36560 if( a[i]==0 ){
36561 a[i] = p;
36562 break;
36563 }else{
36564 p = pcacheMergeDirtyList(a[i], p);
36565 a[i] = 0;
36568 if( NEVER(i==N_SORT_BUCKET-1) ){
36569 /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
36570 ** the input list. But that is impossible.
36572 a[i] = pcacheMergeDirtyList(a[i], p);
36575 p = a[0];
36576 for(i=1; i<N_SORT_BUCKET; i++){
36577 p = pcacheMergeDirtyList(p, a[i]);
36579 return p;
36583 ** Return a list of all dirty pages in the cache, sorted by page number.
36585 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
36586 PgHdr *p;
36587 for(p=pCache->pDirty; p; p=p->pDirtyNext){
36588 p->pDirty = p->pDirtyNext;
36590 return pcacheSortDirtyList(pCache->pDirty);
36594 ** Return the total number of referenced pages held by the cache.
36596 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
36597 return pCache->nRef;
36601 ** Return the number of references to the page supplied as an argument.
36603 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
36604 return p->nRef;
36608 ** Return the total number of pages in the cache.
36610 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
36611 int nPage = 0;
36612 if( pCache->pCache ){
36613 nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
36615 return nPage;
36618 #ifdef SQLITE_TEST
36620 ** Get the suggested cache-size value.
36622 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
36623 return numberOfCachePages(pCache);
36625 #endif
36628 ** Set the suggested cache-size value.
36630 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
36631 pCache->szCache = mxPage;
36632 if( pCache->pCache ){
36633 sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
36634 numberOfCachePages(pCache));
36639 ** Free up as much memory as possible from the page cache.
36641 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
36642 if( pCache->pCache ){
36643 sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
36647 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
36649 ** For all dirty pages currently in the cache, invoke the specified
36650 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
36651 ** defined.
36653 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
36654 PgHdr *pDirty;
36655 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
36656 xIter(pDirty);
36659 #endif
36661 /************** End of pcache.c **********************************************/
36662 /************** Begin file pcache1.c *****************************************/
36664 ** 2008 November 05
36666 ** The author disclaims copyright to this source code. In place of
36667 ** a legal notice, here is a blessing:
36669 ** May you do good and not evil.
36670 ** May you find forgiveness for yourself and forgive others.
36671 ** May you share freely, never taking more than you give.
36673 *************************************************************************
36675 ** This file implements the default page cache implementation (the
36676 ** sqlite3_pcache interface). It also contains part of the implementation
36677 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
36678 ** If the default page cache implementation is overriden, then neither of
36679 ** these two features are available.
36683 typedef struct PCache1 PCache1;
36684 typedef struct PgHdr1 PgHdr1;
36685 typedef struct PgFreeslot PgFreeslot;
36686 typedef struct PGroup PGroup;
36688 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
36689 ** of one or more PCaches that are able to recycle each others unpinned
36690 ** pages when they are under memory pressure. A PGroup is an instance of
36691 ** the following object.
36693 ** This page cache implementation works in one of two modes:
36695 ** (1) Every PCache is the sole member of its own PGroup. There is
36696 ** one PGroup per PCache.
36698 ** (2) There is a single global PGroup that all PCaches are a member
36699 ** of.
36701 ** Mode 1 uses more memory (since PCache instances are not able to rob
36702 ** unused pages from other PCaches) but it also operates without a mutex,
36703 ** and is therefore often faster. Mode 2 requires a mutex in order to be
36704 ** threadsafe, but recycles pages more efficiently.
36706 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
36707 ** PGroup which is the pcache1.grp global variable and its mutex is
36708 ** SQLITE_MUTEX_STATIC_LRU.
36710 struct PGroup {
36711 sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
36712 unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
36713 unsigned int nMinPage; /* Sum of nMin for purgeable caches */
36714 unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
36715 unsigned int nCurrentPage; /* Number of purgeable pages allocated */
36716 PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
36719 /* Each page cache is an instance of the following object. Every
36720 ** open database file (including each in-memory database and each
36721 ** temporary or transient database) has a single page cache which
36722 ** is an instance of this object.
36724 ** Pointers to structures of this type are cast and returned as
36725 ** opaque sqlite3_pcache* handles.
36727 struct PCache1 {
36728 /* Cache configuration parameters. Page size (szPage) and the purgeable
36729 ** flag (bPurgeable) are set when the cache is created. nMax may be
36730 ** modified at any time by a call to the pcache1Cachesize() method.
36731 ** The PGroup mutex must be held when accessing nMax.
36733 PGroup *pGroup; /* PGroup this cache belongs to */
36734 int szPage; /* Size of allocated pages in bytes */
36735 int szExtra; /* Size of extra space in bytes */
36736 int bPurgeable; /* True if cache is purgeable */
36737 unsigned int nMin; /* Minimum number of pages reserved */
36738 unsigned int nMax; /* Configured "cache_size" value */
36739 unsigned int n90pct; /* nMax*9/10 */
36740 unsigned int iMaxKey; /* Largest key seen since xTruncate() */
36742 /* Hash table of all pages. The following variables may only be accessed
36743 ** when the accessor is holding the PGroup mutex.
36745 unsigned int nRecyclable; /* Number of pages in the LRU list */
36746 unsigned int nPage; /* Total number of pages in apHash */
36747 unsigned int nHash; /* Number of slots in apHash[] */
36748 PgHdr1 **apHash; /* Hash table for fast lookup by key */
36752 ** Each cache entry is represented by an instance of the following
36753 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
36754 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
36755 ** in memory.
36757 struct PgHdr1 {
36758 sqlite3_pcache_page page;
36759 unsigned int iKey; /* Key value (page number) */
36760 PgHdr1 *pNext; /* Next in hash table chain */
36761 PCache1 *pCache; /* Cache that currently owns this page */
36762 PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
36763 PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
36767 ** Free slots in the allocator used to divide up the buffer provided using
36768 ** the SQLITE_CONFIG_PAGECACHE mechanism.
36770 struct PgFreeslot {
36771 PgFreeslot *pNext; /* Next free slot */
36775 ** Global data used by this cache.
36777 static SQLITE_WSD struct PCacheGlobal {
36778 PGroup grp; /* The global PGroup for mode (2) */
36780 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
36781 ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
36782 ** fixed at sqlite3_initialize() time and do not require mutex protection.
36783 ** The nFreeSlot and pFree values do require mutex protection.
36785 int isInit; /* True if initialized */
36786 int szSlot; /* Size of each free slot */
36787 int nSlot; /* The number of pcache slots */
36788 int nReserve; /* Try to keep nFreeSlot above this */
36789 void *pStart, *pEnd; /* Bounds of pagecache malloc range */
36790 /* Above requires no mutex. Use mutex below for variable that follow. */
36791 sqlite3_mutex *mutex; /* Mutex for accessing the following: */
36792 PgFreeslot *pFree; /* Free page blocks */
36793 int nFreeSlot; /* Number of unused pcache slots */
36794 /* The following value requires a mutex to change. We skip the mutex on
36795 ** reading because (1) most platforms read a 32-bit integer atomically and
36796 ** (2) even if an incorrect value is read, no great harm is done since this
36797 ** is really just an optimization. */
36798 int bUnderPressure; /* True if low on PAGECACHE memory */
36799 } pcache1_g;
36802 ** All code in this file should access the global structure above via the
36803 ** alias "pcache1". This ensures that the WSD emulation is used when
36804 ** compiling for systems that do not support real WSD.
36806 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
36809 ** Macros to enter and leave the PCache LRU mutex.
36811 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
36812 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
36814 /******************************************************************************/
36815 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
36818 ** This function is called during initialization if a static buffer is
36819 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
36820 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
36821 ** enough to contain 'n' buffers of 'sz' bytes each.
36823 ** This routine is called from sqlite3_initialize() and so it is guaranteed
36824 ** to be serialized already. There is no need for further mutexing.
36826 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
36827 if( pcache1.isInit ){
36828 PgFreeslot *p;
36829 sz = ROUNDDOWN8(sz);
36830 pcache1.szSlot = sz;
36831 pcache1.nSlot = pcache1.nFreeSlot = n;
36832 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
36833 pcache1.pStart = pBuf;
36834 pcache1.pFree = 0;
36835 pcache1.bUnderPressure = 0;
36836 while( n-- ){
36837 p = (PgFreeslot*)pBuf;
36838 p->pNext = pcache1.pFree;
36839 pcache1.pFree = p;
36840 pBuf = (void*)&((char*)pBuf)[sz];
36842 pcache1.pEnd = pBuf;
36847 ** Malloc function used within this file to allocate space from the buffer
36848 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
36849 ** such buffer exists or there is no space left in it, this function falls
36850 ** back to sqlite3Malloc().
36852 ** Multiple threads can run this routine at the same time. Global variables
36853 ** in pcache1 need to be protected via mutex.
36855 static void *pcache1Alloc(int nByte){
36856 void *p = 0;
36857 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36858 sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
36859 if( nByte<=pcache1.szSlot ){
36860 sqlite3_mutex_enter(pcache1.mutex);
36861 p = (PgHdr1 *)pcache1.pFree;
36862 if( p ){
36863 pcache1.pFree = pcache1.pFree->pNext;
36864 pcache1.nFreeSlot--;
36865 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
36866 assert( pcache1.nFreeSlot>=0 );
36867 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
36869 sqlite3_mutex_leave(pcache1.mutex);
36871 if( p==0 ){
36872 /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
36873 ** it from sqlite3Malloc instead.
36875 p = sqlite3Malloc(nByte);
36876 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
36877 if( p ){
36878 int sz = sqlite3MallocSize(p);
36879 sqlite3_mutex_enter(pcache1.mutex);
36880 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
36881 sqlite3_mutex_leave(pcache1.mutex);
36883 #endif
36884 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
36886 return p;
36890 ** Free an allocated buffer obtained from pcache1Alloc().
36892 static int pcache1Free(void *p){
36893 int nFreed = 0;
36894 if( p==0 ) return 0;
36895 if( p>=pcache1.pStart && p<pcache1.pEnd ){
36896 PgFreeslot *pSlot;
36897 sqlite3_mutex_enter(pcache1.mutex);
36898 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
36899 pSlot = (PgFreeslot*)p;
36900 pSlot->pNext = pcache1.pFree;
36901 pcache1.pFree = pSlot;
36902 pcache1.nFreeSlot++;
36903 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
36904 assert( pcache1.nFreeSlot<=pcache1.nSlot );
36905 sqlite3_mutex_leave(pcache1.mutex);
36906 }else{
36907 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
36908 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
36909 nFreed = sqlite3MallocSize(p);
36910 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
36911 sqlite3_mutex_enter(pcache1.mutex);
36912 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
36913 sqlite3_mutex_leave(pcache1.mutex);
36914 #endif
36915 sqlite3_free(p);
36917 return nFreed;
36920 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36922 ** Return the size of a pcache allocation
36924 static int pcache1MemSize(void *p){
36925 if( p>=pcache1.pStart && p<pcache1.pEnd ){
36926 return pcache1.szSlot;
36927 }else{
36928 int iSize;
36929 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
36930 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
36931 iSize = sqlite3MallocSize(p);
36932 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
36933 return iSize;
36936 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36939 ** Allocate a new page object initially associated with cache pCache.
36941 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
36942 PgHdr1 *p = 0;
36943 void *pPg;
36945 /* The group mutex must be released before pcache1Alloc() is called. This
36946 ** is because it may call sqlite3_release_memory(), which assumes that
36947 ** this mutex is not held. */
36948 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36949 pcache1LeaveMutex(pCache->pGroup);
36950 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36951 pPg = pcache1Alloc(pCache->szPage);
36952 p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
36953 if( !pPg || !p ){
36954 pcache1Free(pPg);
36955 sqlite3_free(p);
36956 pPg = 0;
36958 #else
36959 pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
36960 p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
36961 #endif
36962 pcache1EnterMutex(pCache->pGroup);
36964 if( pPg ){
36965 p->page.pBuf = pPg;
36966 p->page.pExtra = &p[1];
36967 if( pCache->bPurgeable ){
36968 pCache->pGroup->nCurrentPage++;
36970 return p;
36972 return 0;
36976 ** Free a page object allocated by pcache1AllocPage().
36978 ** The pointer is allowed to be NULL, which is prudent. But it turns out
36979 ** that the current implementation happens to never call this routine
36980 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
36982 static void pcache1FreePage(PgHdr1 *p){
36983 if( ALWAYS(p) ){
36984 PCache1 *pCache = p->pCache;
36985 assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
36986 pcache1Free(p->page.pBuf);
36987 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36988 sqlite3_free(p);
36989 #endif
36990 if( pCache->bPurgeable ){
36991 pCache->pGroup->nCurrentPage--;
36997 ** Malloc function used by SQLite to obtain space from the buffer configured
36998 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
36999 ** exists, this function falls back to sqlite3Malloc().
37001 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
37002 return pcache1Alloc(sz);
37006 ** Free an allocated buffer obtained from sqlite3PageMalloc().
37008 SQLITE_PRIVATE void sqlite3PageFree(void *p){
37009 pcache1Free(p);
37014 ** Return true if it desirable to avoid allocating a new page cache
37015 ** entry.
37017 ** If memory was allocated specifically to the page cache using
37018 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
37019 ** it is desirable to avoid allocating a new page cache entry because
37020 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
37021 ** for all page cache needs and we should not need to spill the
37022 ** allocation onto the heap.
37024 ** Or, the heap is used for all page cache memory but the heap is
37025 ** under memory pressure, then again it is desirable to avoid
37026 ** allocating a new page cache entry in order to avoid stressing
37027 ** the heap even further.
37029 static int pcache1UnderMemoryPressure(PCache1 *pCache){
37030 if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
37031 return pcache1.bUnderPressure;
37032 }else{
37033 return sqlite3HeapNearlyFull();
37037 /******************************************************************************/
37038 /******** General Implementation Functions ************************************/
37041 ** This function is used to resize the hash table used by the cache passed
37042 ** as the first argument.
37044 ** The PCache mutex must be held when this function is called.
37046 static int pcache1ResizeHash(PCache1 *p){
37047 PgHdr1 **apNew;
37048 unsigned int nNew;
37049 unsigned int i;
37051 assert( sqlite3_mutex_held(p->pGroup->mutex) );
37053 nNew = p->nHash*2;
37054 if( nNew<256 ){
37055 nNew = 256;
37058 pcache1LeaveMutex(p->pGroup);
37059 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
37060 apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
37061 if( p->nHash ){ sqlite3EndBenignMalloc(); }
37062 pcache1EnterMutex(p->pGroup);
37063 if( apNew ){
37064 for(i=0; i<p->nHash; i++){
37065 PgHdr1 *pPage;
37066 PgHdr1 *pNext = p->apHash[i];
37067 while( (pPage = pNext)!=0 ){
37068 unsigned int h = pPage->iKey % nNew;
37069 pNext = pPage->pNext;
37070 pPage->pNext = apNew[h];
37071 apNew[h] = pPage;
37074 sqlite3_free(p->apHash);
37075 p->apHash = apNew;
37076 p->nHash = nNew;
37079 return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
37083 ** This function is used internally to remove the page pPage from the
37084 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
37085 ** LRU list, then this function is a no-op.
37087 ** The PGroup mutex must be held when this function is called.
37089 ** If pPage is NULL then this routine is a no-op.
37091 static void pcache1PinPage(PgHdr1 *pPage){
37092 PCache1 *pCache;
37093 PGroup *pGroup;
37095 if( pPage==0 ) return;
37096 pCache = pPage->pCache;
37097 pGroup = pCache->pGroup;
37098 assert( sqlite3_mutex_held(pGroup->mutex) );
37099 if( pPage->pLruNext || pPage==pGroup->pLruTail ){
37100 if( pPage->pLruPrev ){
37101 pPage->pLruPrev->pLruNext = pPage->pLruNext;
37103 if( pPage->pLruNext ){
37104 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
37106 if( pGroup->pLruHead==pPage ){
37107 pGroup->pLruHead = pPage->pLruNext;
37109 if( pGroup->pLruTail==pPage ){
37110 pGroup->pLruTail = pPage->pLruPrev;
37112 pPage->pLruNext = 0;
37113 pPage->pLruPrev = 0;
37114 pPage->pCache->nRecyclable--;
37120 ** Remove the page supplied as an argument from the hash table
37121 ** (PCache1.apHash structure) that it is currently stored in.
37123 ** The PGroup mutex must be held when this function is called.
37125 static void pcache1RemoveFromHash(PgHdr1 *pPage){
37126 unsigned int h;
37127 PCache1 *pCache = pPage->pCache;
37128 PgHdr1 **pp;
37130 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37131 h = pPage->iKey % pCache->nHash;
37132 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
37133 *pp = (*pp)->pNext;
37135 pCache->nPage--;
37139 ** If there are currently more than nMaxPage pages allocated, try
37140 ** to recycle pages to reduce the number allocated to nMaxPage.
37142 static void pcache1EnforceMaxPage(PGroup *pGroup){
37143 assert( sqlite3_mutex_held(pGroup->mutex) );
37144 while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
37145 PgHdr1 *p = pGroup->pLruTail;
37146 assert( p->pCache->pGroup==pGroup );
37147 pcache1PinPage(p);
37148 pcache1RemoveFromHash(p);
37149 pcache1FreePage(p);
37154 ** Discard all pages from cache pCache with a page number (key value)
37155 ** greater than or equal to iLimit. Any pinned pages that meet this
37156 ** criteria are unpinned before they are discarded.
37158 ** The PCache mutex must be held when this function is called.
37160 static void pcache1TruncateUnsafe(
37161 PCache1 *pCache, /* The cache to truncate */
37162 unsigned int iLimit /* Drop pages with this pgno or larger */
37164 TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
37165 unsigned int h;
37166 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37167 for(h=0; h<pCache->nHash; h++){
37168 PgHdr1 **pp = &pCache->apHash[h];
37169 PgHdr1 *pPage;
37170 while( (pPage = *pp)!=0 ){
37171 if( pPage->iKey>=iLimit ){
37172 pCache->nPage--;
37173 *pp = pPage->pNext;
37174 pcache1PinPage(pPage);
37175 pcache1FreePage(pPage);
37176 }else{
37177 pp = &pPage->pNext;
37178 TESTONLY( nPage++; )
37182 assert( pCache->nPage==nPage );
37185 /******************************************************************************/
37186 /******** sqlite3_pcache Methods **********************************************/
37189 ** Implementation of the sqlite3_pcache.xInit method.
37191 static int pcache1Init(void *NotUsed){
37192 UNUSED_PARAMETER(NotUsed);
37193 assert( pcache1.isInit==0 );
37194 memset(&pcache1, 0, sizeof(pcache1));
37195 if( sqlite3GlobalConfig.bCoreMutex ){
37196 pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
37197 pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
37199 pcache1.grp.mxPinned = 10;
37200 pcache1.isInit = 1;
37201 return SQLITE_OK;
37205 ** Implementation of the sqlite3_pcache.xShutdown method.
37206 ** Note that the static mutex allocated in xInit does
37207 ** not need to be freed.
37209 static void pcache1Shutdown(void *NotUsed){
37210 UNUSED_PARAMETER(NotUsed);
37211 assert( pcache1.isInit!=0 );
37212 memset(&pcache1, 0, sizeof(pcache1));
37216 ** Implementation of the sqlite3_pcache.xCreate method.
37218 ** Allocate a new cache.
37220 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
37221 PCache1 *pCache; /* The newly created page cache */
37222 PGroup *pGroup; /* The group the new page cache will belong to */
37223 int sz; /* Bytes of memory required to allocate the new cache */
37226 ** The separateCache variable is true if each PCache has its own private
37227 ** PGroup. In other words, separateCache is true for mode (1) where no
37228 ** mutexing is required.
37230 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
37232 ** * Always use a unified cache in single-threaded applications
37234 ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
37235 ** use separate caches (mode-1)
37237 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
37238 const int separateCache = 0;
37239 #else
37240 int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
37241 #endif
37243 assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
37244 assert( szExtra < 300 );
37246 sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
37247 pCache = (PCache1 *)sqlite3MallocZero(sz);
37248 if( pCache ){
37249 if( separateCache ){
37250 pGroup = (PGroup*)&pCache[1];
37251 pGroup->mxPinned = 10;
37252 }else{
37253 pGroup = &pcache1.grp;
37255 pCache->pGroup = pGroup;
37256 pCache->szPage = szPage;
37257 pCache->szExtra = szExtra;
37258 pCache->bPurgeable = (bPurgeable ? 1 : 0);
37259 if( bPurgeable ){
37260 pCache->nMin = 10;
37261 pcache1EnterMutex(pGroup);
37262 pGroup->nMinPage += pCache->nMin;
37263 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37264 pcache1LeaveMutex(pGroup);
37267 return (sqlite3_pcache *)pCache;
37271 ** Implementation of the sqlite3_pcache.xCachesize method.
37273 ** Configure the cache_size limit for a cache.
37275 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
37276 PCache1 *pCache = (PCache1 *)p;
37277 if( pCache->bPurgeable ){
37278 PGroup *pGroup = pCache->pGroup;
37279 pcache1EnterMutex(pGroup);
37280 pGroup->nMaxPage += (nMax - pCache->nMax);
37281 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37282 pCache->nMax = nMax;
37283 pCache->n90pct = pCache->nMax*9/10;
37284 pcache1EnforceMaxPage(pGroup);
37285 pcache1LeaveMutex(pGroup);
37290 ** Implementation of the sqlite3_pcache.xShrink method.
37292 ** Free up as much memory as possible.
37294 static void pcache1Shrink(sqlite3_pcache *p){
37295 PCache1 *pCache = (PCache1*)p;
37296 if( pCache->bPurgeable ){
37297 PGroup *pGroup = pCache->pGroup;
37298 int savedMaxPage;
37299 pcache1EnterMutex(pGroup);
37300 savedMaxPage = pGroup->nMaxPage;
37301 pGroup->nMaxPage = 0;
37302 pcache1EnforceMaxPage(pGroup);
37303 pGroup->nMaxPage = savedMaxPage;
37304 pcache1LeaveMutex(pGroup);
37309 ** Implementation of the sqlite3_pcache.xPagecount method.
37311 static int pcache1Pagecount(sqlite3_pcache *p){
37312 int n;
37313 PCache1 *pCache = (PCache1*)p;
37314 pcache1EnterMutex(pCache->pGroup);
37315 n = pCache->nPage;
37316 pcache1LeaveMutex(pCache->pGroup);
37317 return n;
37321 ** Implementation of the sqlite3_pcache.xFetch method.
37323 ** Fetch a page by key value.
37325 ** Whether or not a new page may be allocated by this function depends on
37326 ** the value of the createFlag argument. 0 means do not allocate a new
37327 ** page. 1 means allocate a new page if space is easily available. 2
37328 ** means to try really hard to allocate a new page.
37330 ** For a non-purgeable cache (a cache used as the storage for an in-memory
37331 ** database) there is really no difference between createFlag 1 and 2. So
37332 ** the calling function (pcache.c) will never have a createFlag of 1 on
37333 ** a non-purgeable cache.
37335 ** There are three different approaches to obtaining space for a page,
37336 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
37338 ** 1. Regardless of the value of createFlag, the cache is searched for a
37339 ** copy of the requested page. If one is found, it is returned.
37341 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
37342 ** returned.
37344 ** 3. If createFlag is 1, and the page is not already in the cache, then
37345 ** return NULL (do not allocate a new page) if any of the following
37346 ** conditions are true:
37348 ** (a) the number of pages pinned by the cache is greater than
37349 ** PCache1.nMax, or
37351 ** (b) the number of pages pinned by the cache is greater than
37352 ** the sum of nMax for all purgeable caches, less the sum of
37353 ** nMin for all other purgeable caches, or
37355 ** 4. If none of the first three conditions apply and the cache is marked
37356 ** as purgeable, and if one of the following is true:
37358 ** (a) The number of pages allocated for the cache is already
37359 ** PCache1.nMax, or
37361 ** (b) The number of pages allocated for all purgeable caches is
37362 ** already equal to or greater than the sum of nMax for all
37363 ** purgeable caches,
37365 ** (c) The system is under memory pressure and wants to avoid
37366 ** unnecessary pages cache entry allocations
37368 ** then attempt to recycle a page from the LRU list. If it is the right
37369 ** size, return the recycled buffer. Otherwise, free the buffer and
37370 ** proceed to step 5.
37372 ** 5. Otherwise, allocate and return a new page buffer.
37374 static sqlite3_pcache_page *pcache1Fetch(
37375 sqlite3_pcache *p,
37376 unsigned int iKey,
37377 int createFlag
37379 unsigned int nPinned;
37380 PCache1 *pCache = (PCache1 *)p;
37381 PGroup *pGroup;
37382 PgHdr1 *pPage = 0;
37384 assert( pCache->bPurgeable || createFlag!=1 );
37385 assert( pCache->bPurgeable || pCache->nMin==0 );
37386 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
37387 assert( pCache->nMin==0 || pCache->bPurgeable );
37388 pcache1EnterMutex(pGroup = pCache->pGroup);
37390 /* Step 1: Search the hash table for an existing entry. */
37391 if( pCache->nHash>0 ){
37392 unsigned int h = iKey % pCache->nHash;
37393 for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
37396 /* Step 2: Abort if no existing page is found and createFlag is 0 */
37397 if( pPage || createFlag==0 ){
37398 pcache1PinPage(pPage);
37399 goto fetch_out;
37402 /* The pGroup local variable will normally be initialized by the
37403 ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
37404 ** then pcache1EnterMutex() is a no-op, so we have to initialize the
37405 ** local variable here. Delaying the initialization of pGroup is an
37406 ** optimization: The common case is to exit the module before reaching
37407 ** this point.
37409 #ifdef SQLITE_MUTEX_OMIT
37410 pGroup = pCache->pGroup;
37411 #endif
37413 /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
37414 assert( pCache->nPage >= pCache->nRecyclable );
37415 nPinned = pCache->nPage - pCache->nRecyclable;
37416 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
37417 assert( pCache->n90pct == pCache->nMax*9/10 );
37418 if( createFlag==1 && (
37419 nPinned>=pGroup->mxPinned
37420 || nPinned>=pCache->n90pct
37421 || pcache1UnderMemoryPressure(pCache)
37423 goto fetch_out;
37426 if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
37427 goto fetch_out;
37429 assert( pCache->nHash>0 && pCache->apHash );
37431 /* Step 4. Try to recycle a page. */
37432 if( pCache->bPurgeable && pGroup->pLruTail && (
37433 (pCache->nPage+1>=pCache->nMax)
37434 || pGroup->nCurrentPage>=pGroup->nMaxPage
37435 || pcache1UnderMemoryPressure(pCache)
37437 PCache1 *pOther;
37438 pPage = pGroup->pLruTail;
37439 pcache1RemoveFromHash(pPage);
37440 pcache1PinPage(pPage);
37441 pOther = pPage->pCache;
37443 /* We want to verify that szPage and szExtra are the same for pOther
37444 ** and pCache. Assert that we can verify this by comparing sums. */
37445 assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
37446 assert( pCache->szExtra<512 );
37447 assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
37448 assert( pOther->szExtra<512 );
37450 if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
37451 pcache1FreePage(pPage);
37452 pPage = 0;
37453 }else{
37454 pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
37458 /* Step 5. If a usable page buffer has still not been found,
37459 ** attempt to allocate a new one.
37461 if( !pPage ){
37462 if( createFlag==1 ) sqlite3BeginBenignMalloc();
37463 pPage = pcache1AllocPage(pCache);
37464 if( createFlag==1 ) sqlite3EndBenignMalloc();
37467 if( pPage ){
37468 unsigned int h = iKey % pCache->nHash;
37469 pCache->nPage++;
37470 pPage->iKey = iKey;
37471 pPage->pNext = pCache->apHash[h];
37472 pPage->pCache = pCache;
37473 pPage->pLruPrev = 0;
37474 pPage->pLruNext = 0;
37475 *(void **)pPage->page.pExtra = 0;
37476 pCache->apHash[h] = pPage;
37479 fetch_out:
37480 if( pPage && iKey>pCache->iMaxKey ){
37481 pCache->iMaxKey = iKey;
37483 pcache1LeaveMutex(pGroup);
37484 return &pPage->page;
37489 ** Implementation of the sqlite3_pcache.xUnpin method.
37491 ** Mark a page as unpinned (eligible for asynchronous recycling).
37493 static void pcache1Unpin(
37494 sqlite3_pcache *p,
37495 sqlite3_pcache_page *pPg,
37496 int reuseUnlikely
37498 PCache1 *pCache = (PCache1 *)p;
37499 PgHdr1 *pPage = (PgHdr1 *)pPg;
37500 PGroup *pGroup = pCache->pGroup;
37502 assert( pPage->pCache==pCache );
37503 pcache1EnterMutex(pGroup);
37505 /* It is an error to call this function if the page is already
37506 ** part of the PGroup LRU list.
37508 assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
37509 assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
37511 if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
37512 pcache1RemoveFromHash(pPage);
37513 pcache1FreePage(pPage);
37514 }else{
37515 /* Add the page to the PGroup LRU list. */
37516 if( pGroup->pLruHead ){
37517 pGroup->pLruHead->pLruPrev = pPage;
37518 pPage->pLruNext = pGroup->pLruHead;
37519 pGroup->pLruHead = pPage;
37520 }else{
37521 pGroup->pLruTail = pPage;
37522 pGroup->pLruHead = pPage;
37524 pCache->nRecyclable++;
37527 pcache1LeaveMutex(pCache->pGroup);
37531 ** Implementation of the sqlite3_pcache.xRekey method.
37533 static void pcache1Rekey(
37534 sqlite3_pcache *p,
37535 sqlite3_pcache_page *pPg,
37536 unsigned int iOld,
37537 unsigned int iNew
37539 PCache1 *pCache = (PCache1 *)p;
37540 PgHdr1 *pPage = (PgHdr1 *)pPg;
37541 PgHdr1 **pp;
37542 unsigned int h;
37543 assert( pPage->iKey==iOld );
37544 assert( pPage->pCache==pCache );
37546 pcache1EnterMutex(pCache->pGroup);
37548 h = iOld%pCache->nHash;
37549 pp = &pCache->apHash[h];
37550 while( (*pp)!=pPage ){
37551 pp = &(*pp)->pNext;
37553 *pp = pPage->pNext;
37555 h = iNew%pCache->nHash;
37556 pPage->iKey = iNew;
37557 pPage->pNext = pCache->apHash[h];
37558 pCache->apHash[h] = pPage;
37559 if( iNew>pCache->iMaxKey ){
37560 pCache->iMaxKey = iNew;
37563 pcache1LeaveMutex(pCache->pGroup);
37567 ** Implementation of the sqlite3_pcache.xTruncate method.
37569 ** Discard all unpinned pages in the cache with a page number equal to
37570 ** or greater than parameter iLimit. Any pinned pages with a page number
37571 ** equal to or greater than iLimit are implicitly unpinned.
37573 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
37574 PCache1 *pCache = (PCache1 *)p;
37575 pcache1EnterMutex(pCache->pGroup);
37576 if( iLimit<=pCache->iMaxKey ){
37577 pcache1TruncateUnsafe(pCache, iLimit);
37578 pCache->iMaxKey = iLimit-1;
37580 pcache1LeaveMutex(pCache->pGroup);
37584 ** Implementation of the sqlite3_pcache.xDestroy method.
37586 ** Destroy a cache allocated using pcache1Create().
37588 static void pcache1Destroy(sqlite3_pcache *p){
37589 PCache1 *pCache = (PCache1 *)p;
37590 PGroup *pGroup = pCache->pGroup;
37591 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
37592 pcache1EnterMutex(pGroup);
37593 pcache1TruncateUnsafe(pCache, 0);
37594 assert( pGroup->nMaxPage >= pCache->nMax );
37595 pGroup->nMaxPage -= pCache->nMax;
37596 assert( pGroup->nMinPage >= pCache->nMin );
37597 pGroup->nMinPage -= pCache->nMin;
37598 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37599 pcache1EnforceMaxPage(pGroup);
37600 pcache1LeaveMutex(pGroup);
37601 sqlite3_free(pCache->apHash);
37602 sqlite3_free(pCache);
37606 ** This function is called during initialization (sqlite3_initialize()) to
37607 ** install the default pluggable cache module, assuming the user has not
37608 ** already provided an alternative.
37610 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
37611 static const sqlite3_pcache_methods2 defaultMethods = {
37612 1, /* iVersion */
37613 0, /* pArg */
37614 pcache1Init, /* xInit */
37615 pcache1Shutdown, /* xShutdown */
37616 pcache1Create, /* xCreate */
37617 pcache1Cachesize, /* xCachesize */
37618 pcache1Pagecount, /* xPagecount */
37619 pcache1Fetch, /* xFetch */
37620 pcache1Unpin, /* xUnpin */
37621 pcache1Rekey, /* xRekey */
37622 pcache1Truncate, /* xTruncate */
37623 pcache1Destroy, /* xDestroy */
37624 pcache1Shrink /* xShrink */
37626 sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
37629 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
37631 ** This function is called to free superfluous dynamically allocated memory
37632 ** held by the pager system. Memory in use by any SQLite pager allocated
37633 ** by the current thread may be sqlite3_free()ed.
37635 ** nReq is the number of bytes of memory required. Once this much has
37636 ** been released, the function returns. The return value is the total number
37637 ** of bytes of memory released.
37639 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
37640 int nFree = 0;
37641 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
37642 assert( sqlite3_mutex_notheld(pcache1.mutex) );
37643 if( pcache1.pStart==0 ){
37644 PgHdr1 *p;
37645 pcache1EnterMutex(&pcache1.grp);
37646 while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
37647 nFree += pcache1MemSize(p->page.pBuf);
37648 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
37649 nFree += sqlite3MemSize(p);
37650 #endif
37651 pcache1PinPage(p);
37652 pcache1RemoveFromHash(p);
37653 pcache1FreePage(p);
37655 pcache1LeaveMutex(&pcache1.grp);
37657 return nFree;
37659 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
37661 #ifdef SQLITE_TEST
37663 ** This function is used by test procedures to inspect the internal state
37664 ** of the global cache.
37666 SQLITE_PRIVATE void sqlite3PcacheStats(
37667 int *pnCurrent, /* OUT: Total number of pages cached */
37668 int *pnMax, /* OUT: Global maximum cache size */
37669 int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
37670 int *pnRecyclable /* OUT: Total number of pages available for recycling */
37672 PgHdr1 *p;
37673 int nRecyclable = 0;
37674 for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
37675 nRecyclable++;
37677 *pnCurrent = pcache1.grp.nCurrentPage;
37678 *pnMax = (int)pcache1.grp.nMaxPage;
37679 *pnMin = (int)pcache1.grp.nMinPage;
37680 *pnRecyclable = nRecyclable;
37682 #endif
37684 /************** End of pcache1.c *********************************************/
37685 /************** Begin file rowset.c ******************************************/
37687 ** 2008 December 3
37689 ** The author disclaims copyright to this source code. In place of
37690 ** a legal notice, here is a blessing:
37692 ** May you do good and not evil.
37693 ** May you find forgiveness for yourself and forgive others.
37694 ** May you share freely, never taking more than you give.
37696 *************************************************************************
37698 ** This module implements an object we call a "RowSet".
37700 ** The RowSet object is a collection of rowids. Rowids
37701 ** are inserted into the RowSet in an arbitrary order. Inserts
37702 ** can be intermixed with tests to see if a given rowid has been
37703 ** previously inserted into the RowSet.
37705 ** After all inserts are finished, it is possible to extract the
37706 ** elements of the RowSet in sorted order. Once this extraction
37707 ** process has started, no new elements may be inserted.
37709 ** Hence, the primitive operations for a RowSet are:
37711 ** CREATE
37712 ** INSERT
37713 ** TEST
37714 ** SMALLEST
37715 ** DESTROY
37717 ** The CREATE and DESTROY primitives are the constructor and destructor,
37718 ** obviously. The INSERT primitive adds a new element to the RowSet.
37719 ** TEST checks to see if an element is already in the RowSet. SMALLEST
37720 ** extracts the least value from the RowSet.
37722 ** The INSERT primitive might allocate additional memory. Memory is
37723 ** allocated in chunks so most INSERTs do no allocation. There is an
37724 ** upper bound on the size of allocated memory. No memory is freed
37725 ** until DESTROY.
37727 ** The TEST primitive includes a "batch" number. The TEST primitive
37728 ** will only see elements that were inserted before the last change
37729 ** in the batch number. In other words, if an INSERT occurs between
37730 ** two TESTs where the TESTs have the same batch nubmer, then the
37731 ** value added by the INSERT will not be visible to the second TEST.
37732 ** The initial batch number is zero, so if the very first TEST contains
37733 ** a non-zero batch number, it will see all prior INSERTs.
37735 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
37736 ** that is attempted.
37738 ** The cost of an INSERT is roughly constant. (Sometime new memory
37739 ** has to be allocated on an INSERT.) The cost of a TEST with a new
37740 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
37741 ** The cost of a TEST using the same batch number is O(logN). The cost
37742 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
37743 ** primitives are constant time. The cost of DESTROY is O(N).
37745 ** There is an added cost of O(N) when switching between TEST and
37746 ** SMALLEST primitives.
37751 ** Target size for allocation chunks.
37753 #define ROWSET_ALLOCATION_SIZE 1024
37756 ** The number of rowset entries per allocation chunk.
37758 #define ROWSET_ENTRY_PER_CHUNK \
37759 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
37762 ** Each entry in a RowSet is an instance of the following object.
37764 ** This same object is reused to store a linked list of trees of RowSetEntry
37765 ** objects. In that alternative use, pRight points to the next entry
37766 ** in the list, pLeft points to the tree, and v is unused. The
37767 ** RowSet.pForest value points to the head of this forest list.
37769 struct RowSetEntry {
37770 i64 v; /* ROWID value for this entry */
37771 struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
37772 struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
37776 ** RowSetEntry objects are allocated in large chunks (instances of the
37777 ** following structure) to reduce memory allocation overhead. The
37778 ** chunks are kept on a linked list so that they can be deallocated
37779 ** when the RowSet is destroyed.
37781 struct RowSetChunk {
37782 struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
37783 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
37787 ** A RowSet in an instance of the following structure.
37789 ** A typedef of this structure if found in sqliteInt.h.
37791 struct RowSet {
37792 struct RowSetChunk *pChunk; /* List of all chunk allocations */
37793 sqlite3 *db; /* The database connection */
37794 struct RowSetEntry *pEntry; /* List of entries using pRight */
37795 struct RowSetEntry *pLast; /* Last entry on the pEntry list */
37796 struct RowSetEntry *pFresh; /* Source of new entry objects */
37797 struct RowSetEntry *pForest; /* List of binary trees of entries */
37798 u16 nFresh; /* Number of objects on pFresh */
37799 u8 rsFlags; /* Various flags */
37800 u8 iBatch; /* Current insert batch */
37804 ** Allowed values for RowSet.rsFlags
37806 #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
37807 #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
37810 ** Turn bulk memory into a RowSet object. N bytes of memory
37811 ** are available at pSpace. The db pointer is used as a memory context
37812 ** for any subsequent allocations that need to occur.
37813 ** Return a pointer to the new RowSet object.
37815 ** It must be the case that N is sufficient to make a Rowset. If not
37816 ** an assertion fault occurs.
37818 ** If N is larger than the minimum, use the surplus as an initial
37819 ** allocation of entries available to be filled.
37821 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
37822 RowSet *p;
37823 assert( N >= ROUND8(sizeof(*p)) );
37824 p = pSpace;
37825 p->pChunk = 0;
37826 p->db = db;
37827 p->pEntry = 0;
37828 p->pLast = 0;
37829 p->pForest = 0;
37830 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
37831 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
37832 p->rsFlags = ROWSET_SORTED;
37833 p->iBatch = 0;
37834 return p;
37838 ** Deallocate all chunks from a RowSet. This frees all memory that
37839 ** the RowSet has allocated over its lifetime. This routine is
37840 ** the destructor for the RowSet.
37842 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
37843 struct RowSetChunk *pChunk, *pNextChunk;
37844 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
37845 pNextChunk = pChunk->pNextChunk;
37846 sqlite3DbFree(p->db, pChunk);
37848 p->pChunk = 0;
37849 p->nFresh = 0;
37850 p->pEntry = 0;
37851 p->pLast = 0;
37852 p->pForest = 0;
37853 p->rsFlags = ROWSET_SORTED;
37857 ** Allocate a new RowSetEntry object that is associated with the
37858 ** given RowSet. Return a pointer to the new and completely uninitialized
37859 ** objected.
37861 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
37862 ** routine returns NULL.
37864 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
37865 assert( p!=0 );
37866 if( p->nFresh==0 ){
37867 struct RowSetChunk *pNew;
37868 pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
37869 if( pNew==0 ){
37870 return 0;
37872 pNew->pNextChunk = p->pChunk;
37873 p->pChunk = pNew;
37874 p->pFresh = pNew->aEntry;
37875 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
37877 p->nFresh--;
37878 return p->pFresh++;
37882 ** Insert a new value into a RowSet.
37884 ** The mallocFailed flag of the database connection is set if a
37885 ** memory allocation fails.
37887 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
37888 struct RowSetEntry *pEntry; /* The new entry */
37889 struct RowSetEntry *pLast; /* The last prior entry */
37891 /* This routine is never called after sqlite3RowSetNext() */
37892 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
37894 pEntry = rowSetEntryAlloc(p);
37895 if( pEntry==0 ) return;
37896 pEntry->v = rowid;
37897 pEntry->pRight = 0;
37898 pLast = p->pLast;
37899 if( pLast ){
37900 if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
37901 p->rsFlags &= ~ROWSET_SORTED;
37903 pLast->pRight = pEntry;
37904 }else{
37905 p->pEntry = pEntry;
37907 p->pLast = pEntry;
37911 ** Merge two lists of RowSetEntry objects. Remove duplicates.
37913 ** The input lists are connected via pRight pointers and are
37914 ** assumed to each already be in sorted order.
37916 static struct RowSetEntry *rowSetEntryMerge(
37917 struct RowSetEntry *pA, /* First sorted list to be merged */
37918 struct RowSetEntry *pB /* Second sorted list to be merged */
37920 struct RowSetEntry head;
37921 struct RowSetEntry *pTail;
37923 pTail = &head;
37924 while( pA && pB ){
37925 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
37926 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
37927 if( pA->v<pB->v ){
37928 pTail->pRight = pA;
37929 pA = pA->pRight;
37930 pTail = pTail->pRight;
37931 }else if( pB->v<pA->v ){
37932 pTail->pRight = pB;
37933 pB = pB->pRight;
37934 pTail = pTail->pRight;
37935 }else{
37936 pA = pA->pRight;
37939 if( pA ){
37940 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
37941 pTail->pRight = pA;
37942 }else{
37943 assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
37944 pTail->pRight = pB;
37946 return head.pRight;
37950 ** Sort all elements on the list of RowSetEntry objects into order of
37951 ** increasing v.
37953 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
37954 unsigned int i;
37955 struct RowSetEntry *pNext, *aBucket[40];
37957 memset(aBucket, 0, sizeof(aBucket));
37958 while( pIn ){
37959 pNext = pIn->pRight;
37960 pIn->pRight = 0;
37961 for(i=0; aBucket[i]; i++){
37962 pIn = rowSetEntryMerge(aBucket[i], pIn);
37963 aBucket[i] = 0;
37965 aBucket[i] = pIn;
37966 pIn = pNext;
37968 pIn = 0;
37969 for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
37970 pIn = rowSetEntryMerge(pIn, aBucket[i]);
37972 return pIn;
37977 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
37978 ** Convert this tree into a linked list connected by the pRight pointers
37979 ** and return pointers to the first and last elements of the new list.
37981 static void rowSetTreeToList(
37982 struct RowSetEntry *pIn, /* Root of the input tree */
37983 struct RowSetEntry **ppFirst, /* Write head of the output list here */
37984 struct RowSetEntry **ppLast /* Write tail of the output list here */
37986 assert( pIn!=0 );
37987 if( pIn->pLeft ){
37988 struct RowSetEntry *p;
37989 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
37990 p->pRight = pIn;
37991 }else{
37992 *ppFirst = pIn;
37994 if( pIn->pRight ){
37995 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
37996 }else{
37997 *ppLast = pIn;
37999 assert( (*ppLast)->pRight==0 );
38004 ** Convert a sorted list of elements (connected by pRight) into a binary
38005 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
38006 ** node taken from the head of *ppList. A depth of 2 means a tree with
38007 ** three nodes. And so forth.
38009 ** Use as many entries from the input list as required and update the
38010 ** *ppList to point to the unused elements of the list. If the input
38011 ** list contains too few elements, then construct an incomplete tree
38012 ** and leave *ppList set to NULL.
38014 ** Return a pointer to the root of the constructed binary tree.
38016 static struct RowSetEntry *rowSetNDeepTree(
38017 struct RowSetEntry **ppList,
38018 int iDepth
38020 struct RowSetEntry *p; /* Root of the new tree */
38021 struct RowSetEntry *pLeft; /* Left subtree */
38022 if( *ppList==0 ){
38023 return 0;
38025 if( iDepth==1 ){
38026 p = *ppList;
38027 *ppList = p->pRight;
38028 p->pLeft = p->pRight = 0;
38029 return p;
38031 pLeft = rowSetNDeepTree(ppList, iDepth-1);
38032 p = *ppList;
38033 if( p==0 ){
38034 return pLeft;
38036 p->pLeft = pLeft;
38037 *ppList = p->pRight;
38038 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
38039 return p;
38043 ** Convert a sorted list of elements into a binary tree. Make the tree
38044 ** as deep as it needs to be in order to contain the entire list.
38046 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
38047 int iDepth; /* Depth of the tree so far */
38048 struct RowSetEntry *p; /* Current tree root */
38049 struct RowSetEntry *pLeft; /* Left subtree */
38051 assert( pList!=0 );
38052 p = pList;
38053 pList = p->pRight;
38054 p->pLeft = p->pRight = 0;
38055 for(iDepth=1; pList; iDepth++){
38056 pLeft = p;
38057 p = pList;
38058 pList = p->pRight;
38059 p->pLeft = pLeft;
38060 p->pRight = rowSetNDeepTree(&pList, iDepth);
38062 return p;
38066 ** Take all the entries on p->pEntry and on the trees in p->pForest and
38067 ** sort them all together into one big ordered list on p->pEntry.
38069 ** This routine should only be called once in the life of a RowSet.
38071 static void rowSetToList(RowSet *p){
38073 /* This routine is called only once */
38074 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
38076 if( (p->rsFlags & ROWSET_SORTED)==0 ){
38077 p->pEntry = rowSetEntrySort(p->pEntry);
38080 /* While this module could theoretically support it, sqlite3RowSetNext()
38081 ** is never called after sqlite3RowSetText() for the same RowSet. So
38082 ** there is never a forest to deal with. Should this change, simply
38083 ** remove the assert() and the #if 0. */
38084 assert( p->pForest==0 );
38085 #if 0
38086 while( p->pForest ){
38087 struct RowSetEntry *pTree = p->pForest->pLeft;
38088 if( pTree ){
38089 struct RowSetEntry *pHead, *pTail;
38090 rowSetTreeToList(pTree, &pHead, &pTail);
38091 p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
38093 p->pForest = p->pForest->pRight;
38095 #endif
38096 p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
38100 ** Extract the smallest element from the RowSet.
38101 ** Write the element into *pRowid. Return 1 on success. Return
38102 ** 0 if the RowSet is already empty.
38104 ** After this routine has been called, the sqlite3RowSetInsert()
38105 ** routine may not be called again.
38107 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
38108 assert( p!=0 );
38110 /* Merge the forest into a single sorted list on first call */
38111 if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
38113 /* Return the next entry on the list */
38114 if( p->pEntry ){
38115 *pRowid = p->pEntry->v;
38116 p->pEntry = p->pEntry->pRight;
38117 if( p->pEntry==0 ){
38118 sqlite3RowSetClear(p);
38120 return 1;
38121 }else{
38122 return 0;
38127 ** Check to see if element iRowid was inserted into the rowset as
38128 ** part of any insert batch prior to iBatch. Return 1 or 0.
38130 ** If this is the first test of a new batch and if there exist entires
38131 ** on pRowSet->pEntry, then sort those entires into the forest at
38132 ** pRowSet->pForest so that they can be tested.
38134 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
38135 struct RowSetEntry *p, *pTree;
38137 /* This routine is never called after sqlite3RowSetNext() */
38138 assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
38140 /* Sort entries into the forest on the first test of a new batch
38142 if( iBatch!=pRowSet->iBatch ){
38143 p = pRowSet->pEntry;
38144 if( p ){
38145 struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
38146 if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
38147 p = rowSetEntrySort(p);
38149 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
38150 ppPrevTree = &pTree->pRight;
38151 if( pTree->pLeft==0 ){
38152 pTree->pLeft = rowSetListToTree(p);
38153 break;
38154 }else{
38155 struct RowSetEntry *pAux, *pTail;
38156 rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
38157 pTree->pLeft = 0;
38158 p = rowSetEntryMerge(pAux, p);
38161 if( pTree==0 ){
38162 *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
38163 if( pTree ){
38164 pTree->v = 0;
38165 pTree->pRight = 0;
38166 pTree->pLeft = rowSetListToTree(p);
38169 pRowSet->pEntry = 0;
38170 pRowSet->pLast = 0;
38171 pRowSet->rsFlags |= ROWSET_SORTED;
38173 pRowSet->iBatch = iBatch;
38176 /* Test to see if the iRowid value appears anywhere in the forest.
38177 ** Return 1 if it does and 0 if not.
38179 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
38180 p = pTree->pLeft;
38181 while( p ){
38182 if( p->v<iRowid ){
38183 p = p->pRight;
38184 }else if( p->v>iRowid ){
38185 p = p->pLeft;
38186 }else{
38187 return 1;
38191 return 0;
38194 /************** End of rowset.c **********************************************/
38195 /************** Begin file pager.c *******************************************/
38197 ** 2001 September 15
38199 ** The author disclaims copyright to this source code. In place of
38200 ** a legal notice, here is a blessing:
38202 ** May you do good and not evil.
38203 ** May you find forgiveness for yourself and forgive others.
38204 ** May you share freely, never taking more than you give.
38206 *************************************************************************
38207 ** This is the implementation of the page cache subsystem or "pager".
38209 ** The pager is used to access a database disk file. It implements
38210 ** atomic commit and rollback through the use of a journal file that
38211 ** is separate from the database file. The pager also implements file
38212 ** locking to prevent two processes from writing the same database
38213 ** file simultaneously, or one process from reading the database while
38214 ** another is writing.
38216 #ifndef SQLITE_OMIT_DISKIO
38217 /************** Include wal.h in the middle of pager.c ***********************/
38218 /************** Begin file wal.h *********************************************/
38220 ** 2010 February 1
38222 ** The author disclaims copyright to this source code. In place of
38223 ** a legal notice, here is a blessing:
38225 ** May you do good and not evil.
38226 ** May you find forgiveness for yourself and forgive others.
38227 ** May you share freely, never taking more than you give.
38229 *************************************************************************
38230 ** This header file defines the interface to the write-ahead logging
38231 ** system. Refer to the comments below and the header comment attached to
38232 ** the implementation of each function in log.c for further details.
38235 #ifndef _WAL_H_
38236 #define _WAL_H_
38239 /* Additional values that can be added to the sync_flags argument of
38240 ** sqlite3WalFrames():
38242 #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
38243 #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
38245 #ifdef SQLITE_OMIT_WAL
38246 # define sqlite3WalOpen(x,y,z) 0
38247 # define sqlite3WalLimit(x,y)
38248 # define sqlite3WalClose(w,x,y,z) 0
38249 # define sqlite3WalBeginReadTransaction(y,z) 0
38250 # define sqlite3WalEndReadTransaction(z)
38251 # define sqlite3WalDbsize(y) 0
38252 # define sqlite3WalBeginWriteTransaction(y) 0
38253 # define sqlite3WalEndWriteTransaction(x) 0
38254 # define sqlite3WalUndo(x,y,z) 0
38255 # define sqlite3WalSavepoint(y,z)
38256 # define sqlite3WalSavepointUndo(y,z) 0
38257 # define sqlite3WalFrames(u,v,w,x,y,z) 0
38258 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
38259 # define sqlite3WalCallback(z) 0
38260 # define sqlite3WalExclusiveMode(y,z) 0
38261 # define sqlite3WalHeapMemory(z) 0
38262 # define sqlite3WalFramesize(z) 0
38263 # define sqlite3WalFindFrame(x,y,z) 0
38264 #else
38266 #define WAL_SAVEPOINT_NDATA 4
38268 /* Connection to a write-ahead log (WAL) file.
38269 ** There is one object of this type for each pager.
38271 typedef struct Wal Wal;
38273 /* Open and close a connection to a write-ahead log. */
38274 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
38275 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
38277 /* Set the limiting size of a WAL file. */
38278 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
38280 /* Used by readers to open (lock) and close (unlock) a snapshot. A
38281 ** snapshot is like a read-transaction. It is the state of the database
38282 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
38283 ** preserves the current state even if the other threads or processes
38284 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
38285 ** transaction and releases the lock.
38287 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
38288 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
38290 /* Read a page from the write-ahead log, if it is present. */
38291 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
38292 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
38294 /* If the WAL is not empty, return the size of the database. */
38295 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
38297 /* Obtain or release the WRITER lock. */
38298 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
38299 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
38301 /* Undo any frames written (but not committed) to the log */
38302 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
38304 /* Return an integer that records the current (uncommitted) write
38305 ** position in the WAL */
38306 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
38308 /* Move the write position of the WAL back to iFrame. Called in
38309 ** response to a ROLLBACK TO command. */
38310 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
38312 /* Write a frame or frames to the log. */
38313 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
38315 /* Copy pages from the log to the database file */
38316 SQLITE_PRIVATE int sqlite3WalCheckpoint(
38317 Wal *pWal, /* Write-ahead log connection */
38318 int eMode, /* One of PASSIVE, FULL and RESTART */
38319 int (*xBusy)(void*), /* Function to call when busy */
38320 void *pBusyArg, /* Context argument for xBusyHandler */
38321 int sync_flags, /* Flags to sync db file with (or 0) */
38322 int nBuf, /* Size of buffer nBuf */
38323 u8 *zBuf, /* Temporary buffer to use */
38324 int *pnLog, /* OUT: Number of frames in WAL */
38325 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
38328 /* Return the value to pass to a sqlite3_wal_hook callback, the
38329 ** number of frames in the WAL at the point of the last commit since
38330 ** sqlite3WalCallback() was called. If no commits have occurred since
38331 ** the last call, then return 0.
38333 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
38335 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
38336 ** by the pager layer on the database file.
38338 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
38340 /* Return true if the argument is non-NULL and the WAL module is using
38341 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
38342 ** WAL module is using shared-memory, return false.
38344 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
38346 #ifdef SQLITE_ENABLE_ZIPVFS
38347 /* If the WAL file is not empty, return the number of bytes of content
38348 ** stored in each frame (i.e. the db page-size when the WAL was created).
38350 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
38351 #endif
38353 #endif /* ifndef SQLITE_OMIT_WAL */
38354 #endif /* _WAL_H_ */
38356 /************** End of wal.h *************************************************/
38357 /************** Continuing where we left off in pager.c **********************/
38360 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
38362 ** This comment block describes invariants that hold when using a rollback
38363 ** journal. These invariants do not apply for journal_mode=WAL,
38364 ** journal_mode=MEMORY, or journal_mode=OFF.
38366 ** Within this comment block, a page is deemed to have been synced
38367 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
38368 ** Otherwise, the page is not synced until the xSync method of the VFS
38369 ** is called successfully on the file containing the page.
38371 ** Definition: A page of the database file is said to be "overwriteable" if
38372 ** one or more of the following are true about the page:
38374 ** (a) The original content of the page as it was at the beginning of
38375 ** the transaction has been written into the rollback journal and
38376 ** synced.
38378 ** (b) The page was a freelist leaf page at the start of the transaction.
38380 ** (c) The page number is greater than the largest page that existed in
38381 ** the database file at the start of the transaction.
38383 ** (1) A page of the database file is never overwritten unless one of the
38384 ** following are true:
38386 ** (a) The page and all other pages on the same sector are overwriteable.
38388 ** (b) The atomic page write optimization is enabled, and the entire
38389 ** transaction other than the update of the transaction sequence
38390 ** number consists of a single page change.
38392 ** (2) The content of a page written into the rollback journal exactly matches
38393 ** both the content in the database when the rollback journal was written
38394 ** and the content in the database at the beginning of the current
38395 ** transaction.
38397 ** (3) Writes to the database file are an integer multiple of the page size
38398 ** in length and are aligned on a page boundary.
38400 ** (4) Reads from the database file are either aligned on a page boundary and
38401 ** an integer multiple of the page size in length or are taken from the
38402 ** first 100 bytes of the database file.
38404 ** (5) All writes to the database file are synced prior to the rollback journal
38405 ** being deleted, truncated, or zeroed.
38407 ** (6) If a master journal file is used, then all writes to the database file
38408 ** are synced prior to the master journal being deleted.
38410 ** Definition: Two databases (or the same database at two points it time)
38411 ** are said to be "logically equivalent" if they give the same answer to
38412 ** all queries. Note in particular the content of freelist leaf
38413 ** pages can be changed arbitarily without effecting the logical equivalence
38414 ** of the database.
38416 ** (7) At any time, if any subset, including the empty set and the total set,
38417 ** of the unsynced changes to a rollback journal are removed and the
38418 ** journal is rolled back, the resulting database file will be logical
38419 ** equivalent to the database file at the beginning of the transaction.
38421 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
38422 ** is called to restore the database file to the same size it was at
38423 ** the beginning of the transaction. (In some VFSes, the xTruncate
38424 ** method is a no-op, but that does not change the fact the SQLite will
38425 ** invoke it.)
38427 ** (9) Whenever the database file is modified, at least one bit in the range
38428 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
38429 ** the EXCLUSIVE lock, thus signaling other connections on the same
38430 ** database to flush their caches.
38432 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
38433 ** than one billion transactions.
38435 ** (11) A database file is well-formed at the beginning and at the conclusion
38436 ** of every transaction.
38438 ** (12) An EXCLUSIVE lock is held on the database file when writing to
38439 ** the database file.
38441 ** (13) A SHARED lock is held on the database file while reading any
38442 ** content out of the database file.
38444 ******************************************************************************/
38447 ** Macros for troubleshooting. Normally turned off
38449 #if 0
38450 int sqlite3PagerTrace=1; /* True to enable tracing */
38451 #define sqlite3DebugPrintf printf
38452 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
38453 #else
38454 #define PAGERTRACE(X)
38455 #endif
38458 ** The following two macros are used within the PAGERTRACE() macros above
38459 ** to print out file-descriptors.
38461 ** PAGERID() takes a pointer to a Pager struct as its argument. The
38462 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
38463 ** struct as its argument.
38465 #define PAGERID(p) ((int)(p->fd))
38466 #define FILEHANDLEID(fd) ((int)fd)
38469 ** The Pager.eState variable stores the current 'state' of a pager. A
38470 ** pager may be in any one of the seven states shown in the following
38471 ** state diagram.
38473 ** OPEN <------+------+
38474 ** | | |
38475 ** V | |
38476 ** +---------> READER-------+ |
38477 ** | | |
38478 ** | V |
38479 ** |<-------WRITER_LOCKED------> ERROR
38480 ** | | ^
38481 ** | V |
38482 ** |<------WRITER_CACHEMOD-------->|
38483 ** | | |
38484 ** | V |
38485 ** |<-------WRITER_DBMOD---------->|
38486 ** | | |
38487 ** | V |
38488 ** +<------WRITER_FINISHED-------->+
38491 ** List of state transitions and the C [function] that performs each:
38493 ** OPEN -> READER [sqlite3PagerSharedLock]
38494 ** READER -> OPEN [pager_unlock]
38496 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
38497 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
38498 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
38499 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
38500 ** WRITER_*** -> READER [pager_end_transaction]
38502 ** WRITER_*** -> ERROR [pager_error]
38503 ** ERROR -> OPEN [pager_unlock]
38506 ** OPEN:
38508 ** The pager starts up in this state. Nothing is guaranteed in this
38509 ** state - the file may or may not be locked and the database size is
38510 ** unknown. The database may not be read or written.
38512 ** * No read or write transaction is active.
38513 ** * Any lock, or no lock at all, may be held on the database file.
38514 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
38516 ** READER:
38518 ** In this state all the requirements for reading the database in
38519 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
38520 ** was) in exclusive-locking mode, a user-level read transaction is
38521 ** open. The database size is known in this state.
38523 ** A connection running with locking_mode=normal enters this state when
38524 ** it opens a read-transaction on the database and returns to state
38525 ** OPEN after the read-transaction is completed. However a connection
38526 ** running in locking_mode=exclusive (including temp databases) remains in
38527 ** this state even after the read-transaction is closed. The only way
38528 ** a locking_mode=exclusive connection can transition from READER to OPEN
38529 ** is via the ERROR state (see below).
38531 ** * A read transaction may be active (but a write-transaction cannot).
38532 ** * A SHARED or greater lock is held on the database file.
38533 ** * The dbSize variable may be trusted (even if a user-level read
38534 ** transaction is not active). The dbOrigSize and dbFileSize variables
38535 ** may not be trusted at this point.
38536 ** * If the database is a WAL database, then the WAL connection is open.
38537 ** * Even if a read-transaction is not open, it is guaranteed that
38538 ** there is no hot-journal in the file-system.
38540 ** WRITER_LOCKED:
38542 ** The pager moves to this state from READER when a write-transaction
38543 ** is first opened on the database. In WRITER_LOCKED state, all locks
38544 ** required to start a write-transaction are held, but no actual
38545 ** modifications to the cache or database have taken place.
38547 ** In rollback mode, a RESERVED or (if the transaction was opened with
38548 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
38549 ** moving to this state, but the journal file is not written to or opened
38550 ** to in this state. If the transaction is committed or rolled back while
38551 ** in WRITER_LOCKED state, all that is required is to unlock the database
38552 ** file.
38554 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
38555 ** If the connection is running with locking_mode=exclusive, an attempt
38556 ** is made to obtain an EXCLUSIVE lock on the database file.
38558 ** * A write transaction is active.
38559 ** * If the connection is open in rollback-mode, a RESERVED or greater
38560 ** lock is held on the database file.
38561 ** * If the connection is open in WAL-mode, a WAL write transaction
38562 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
38563 ** called).
38564 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
38565 ** * The contents of the pager cache have not been modified.
38566 ** * The journal file may or may not be open.
38567 ** * Nothing (not even the first header) has been written to the journal.
38569 ** WRITER_CACHEMOD:
38571 ** A pager moves from WRITER_LOCKED state to this state when a page is
38572 ** first modified by the upper layer. In rollback mode the journal file
38573 ** is opened (if it is not already open) and a header written to the
38574 ** start of it. The database file on disk has not been modified.
38576 ** * A write transaction is active.
38577 ** * A RESERVED or greater lock is held on the database file.
38578 ** * The journal file is open and the first header has been written
38579 ** to it, but the header has not been synced to disk.
38580 ** * The contents of the page cache have been modified.
38582 ** WRITER_DBMOD:
38584 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
38585 ** when it modifies the contents of the database file. WAL connections
38586 ** never enter this state (since they do not modify the database file,
38587 ** just the log file).
38589 ** * A write transaction is active.
38590 ** * An EXCLUSIVE or greater lock is held on the database file.
38591 ** * The journal file is open and the first header has been written
38592 ** and synced to disk.
38593 ** * The contents of the page cache have been modified (and possibly
38594 ** written to disk).
38596 ** WRITER_FINISHED:
38598 ** It is not possible for a WAL connection to enter this state.
38600 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
38601 ** state after the entire transaction has been successfully written into the
38602 ** database file. In this state the transaction may be committed simply
38603 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
38604 ** not possible to modify the database further. At this point, the upper
38605 ** layer must either commit or rollback the transaction.
38607 ** * A write transaction is active.
38608 ** * An EXCLUSIVE or greater lock is held on the database file.
38609 ** * All writing and syncing of journal and database data has finished.
38610 ** If no error occurred, all that remains is to finalize the journal to
38611 ** commit the transaction. If an error did occur, the caller will need
38612 ** to rollback the transaction.
38614 ** ERROR:
38616 ** The ERROR state is entered when an IO or disk-full error (including
38617 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
38618 ** difficult to be sure that the in-memory pager state (cache contents,
38619 ** db size etc.) are consistent with the contents of the file-system.
38621 ** Temporary pager files may enter the ERROR state, but in-memory pagers
38622 ** cannot.
38624 ** For example, if an IO error occurs while performing a rollback,
38625 ** the contents of the page-cache may be left in an inconsistent state.
38626 ** At this point it would be dangerous to change back to READER state
38627 ** (as usually happens after a rollback). Any subsequent readers might
38628 ** report database corruption (due to the inconsistent cache), and if
38629 ** they upgrade to writers, they may inadvertently corrupt the database
38630 ** file. To avoid this hazard, the pager switches into the ERROR state
38631 ** instead of READER following such an error.
38633 ** Once it has entered the ERROR state, any attempt to use the pager
38634 ** to read or write data returns an error. Eventually, once all
38635 ** outstanding transactions have been abandoned, the pager is able to
38636 ** transition back to OPEN state, discarding the contents of the
38637 ** page-cache and any other in-memory state at the same time. Everything
38638 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
38639 ** when a read-transaction is next opened on the pager (transitioning
38640 ** the pager into READER state). At that point the system has recovered
38641 ** from the error.
38643 ** Specifically, the pager jumps into the ERROR state if:
38645 ** 1. An error occurs while attempting a rollback. This happens in
38646 ** function sqlite3PagerRollback().
38648 ** 2. An error occurs while attempting to finalize a journal file
38649 ** following a commit in function sqlite3PagerCommitPhaseTwo().
38651 ** 3. An error occurs while attempting to write to the journal or
38652 ** database file in function pagerStress() in order to free up
38653 ** memory.
38655 ** In other cases, the error is returned to the b-tree layer. The b-tree
38656 ** layer then attempts a rollback operation. If the error condition
38657 ** persists, the pager enters the ERROR state via condition (1) above.
38659 ** Condition (3) is necessary because it can be triggered by a read-only
38660 ** statement executed within a transaction. In this case, if the error
38661 ** code were simply returned to the user, the b-tree layer would not
38662 ** automatically attempt a rollback, as it assumes that an error in a
38663 ** read-only statement cannot leave the pager in an internally inconsistent
38664 ** state.
38666 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
38667 ** * There are one or more outstanding references to pages (after the
38668 ** last reference is dropped the pager should move back to OPEN state).
38669 ** * The pager is not an in-memory pager.
38672 ** Notes:
38674 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
38675 ** connection is open in WAL mode. A WAL connection is always in one
38676 ** of the first four states.
38678 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
38679 ** state. There are two exceptions: immediately after exclusive-mode has
38680 ** been turned on (and before any read or write transactions are
38681 ** executed), and when the pager is leaving the "error state".
38683 ** * See also: assert_pager_state().
38685 #define PAGER_OPEN 0
38686 #define PAGER_READER 1
38687 #define PAGER_WRITER_LOCKED 2
38688 #define PAGER_WRITER_CACHEMOD 3
38689 #define PAGER_WRITER_DBMOD 4
38690 #define PAGER_WRITER_FINISHED 5
38691 #define PAGER_ERROR 6
38694 ** The Pager.eLock variable is almost always set to one of the
38695 ** following locking-states, according to the lock currently held on
38696 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38697 ** This variable is kept up to date as locks are taken and released by
38698 ** the pagerLockDb() and pagerUnlockDb() wrappers.
38700 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
38701 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
38702 ** the operation was successful. In these circumstances pagerLockDb() and
38703 ** pagerUnlockDb() take a conservative approach - eLock is always updated
38704 ** when unlocking the file, and only updated when locking the file if the
38705 ** VFS call is successful. This way, the Pager.eLock variable may be set
38706 ** to a less exclusive (lower) value than the lock that is actually held
38707 ** at the system level, but it is never set to a more exclusive value.
38709 ** This is usually safe. If an xUnlock fails or appears to fail, there may
38710 ** be a few redundant xLock() calls or a lock may be held for longer than
38711 ** required, but nothing really goes wrong.
38713 ** The exception is when the database file is unlocked as the pager moves
38714 ** from ERROR to OPEN state. At this point there may be a hot-journal file
38715 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
38716 ** transition, by the same pager or any other). If the call to xUnlock()
38717 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
38718 ** can confuse the call to xCheckReservedLock() call made later as part
38719 ** of hot-journal detection.
38721 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
38722 ** lock held by this process or any others". So xCheckReservedLock may
38723 ** return true because the caller itself is holding an EXCLUSIVE lock (but
38724 ** doesn't know it because of a previous error in xUnlock). If this happens
38725 ** a hot-journal may be mistaken for a journal being created by an active
38726 ** transaction in another process, causing SQLite to read from the database
38727 ** without rolling it back.
38729 ** To work around this, if a call to xUnlock() fails when unlocking the
38730 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
38731 ** is only changed back to a real locking state after a successful call
38732 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
38733 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
38734 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
38735 ** lock on the database file before attempting to roll it back. See function
38736 ** PagerSharedLock() for more detail.
38738 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
38739 ** PAGER_OPEN state.
38741 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
38744 ** A macro used for invoking the codec if there is one
38746 #ifdef SQLITE_HAS_CODEC
38747 # define CODEC1(P,D,N,X,E) \
38748 if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
38749 # define CODEC2(P,D,N,X,E,O) \
38750 if( P->xCodec==0 ){ O=(char*)D; }else \
38751 if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
38752 #else
38753 # define CODEC1(P,D,N,X,E) /* NO-OP */
38754 # define CODEC2(P,D,N,X,E,O) O=(char*)D
38755 #endif
38758 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
38759 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
38760 ** This could conceivably cause corruption following a power failure on
38761 ** such a system. This is currently an undocumented limit.
38763 #define MAX_SECTOR_SIZE 0x10000
38766 ** An instance of the following structure is allocated for each active
38767 ** savepoint and statement transaction in the system. All such structures
38768 ** are stored in the Pager.aSavepoint[] array, which is allocated and
38769 ** resized using sqlite3Realloc().
38771 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
38772 ** set to 0. If a journal-header is written into the main journal while
38773 ** the savepoint is active, then iHdrOffset is set to the byte offset
38774 ** immediately following the last journal record written into the main
38775 ** journal before the journal-header. This is required during savepoint
38776 ** rollback (see pagerPlaybackSavepoint()).
38778 typedef struct PagerSavepoint PagerSavepoint;
38779 struct PagerSavepoint {
38780 i64 iOffset; /* Starting offset in main journal */
38781 i64 iHdrOffset; /* See above */
38782 Bitvec *pInSavepoint; /* Set of pages in this savepoint */
38783 Pgno nOrig; /* Original number of pages in file */
38784 Pgno iSubRec; /* Index of first record in sub-journal */
38785 #ifndef SQLITE_OMIT_WAL
38786 u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
38787 #endif
38791 ** Bits of the Pager.doNotSpill flag. See further description below.
38793 #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
38794 #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
38795 #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
38798 ** A open page cache is an instance of struct Pager. A description of
38799 ** some of the more important member variables follows:
38801 ** eState
38803 ** The current 'state' of the pager object. See the comment and state
38804 ** diagram above for a description of the pager state.
38806 ** eLock
38808 ** For a real on-disk database, the current lock held on the database file -
38809 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38811 ** For a temporary or in-memory database (neither of which require any
38812 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
38813 ** databases always have Pager.exclusiveMode==1, this tricks the pager
38814 ** logic into thinking that it already has all the locks it will ever
38815 ** need (and no reason to release them).
38817 ** In some (obscure) circumstances, this variable may also be set to
38818 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
38819 ** details.
38821 ** changeCountDone
38823 ** This boolean variable is used to make sure that the change-counter
38824 ** (the 4-byte header field at byte offset 24 of the database file) is
38825 ** not updated more often than necessary.
38827 ** It is set to true when the change-counter field is updated, which
38828 ** can only happen if an exclusive lock is held on the database file.
38829 ** It is cleared (set to false) whenever an exclusive lock is
38830 ** relinquished on the database file. Each time a transaction is committed,
38831 ** The changeCountDone flag is inspected. If it is true, the work of
38832 ** updating the change-counter is omitted for the current transaction.
38834 ** This mechanism means that when running in exclusive mode, a connection
38835 ** need only update the change-counter once, for the first transaction
38836 ** committed.
38838 ** setMaster
38840 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
38841 ** (or may not) specify a master-journal name to be written into the
38842 ** journal file before it is synced to disk.
38844 ** Whether or not a journal file contains a master-journal pointer affects
38845 ** the way in which the journal file is finalized after the transaction is
38846 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
38847 ** If a journal file does not contain a master-journal pointer, it is
38848 ** finalized by overwriting the first journal header with zeroes. If
38849 ** it does contain a master-journal pointer the journal file is finalized
38850 ** by truncating it to zero bytes, just as if the connection were
38851 ** running in "journal_mode=truncate" mode.
38853 ** Journal files that contain master journal pointers cannot be finalized
38854 ** simply by overwriting the first journal-header with zeroes, as the
38855 ** master journal pointer could interfere with hot-journal rollback of any
38856 ** subsequently interrupted transaction that reuses the journal file.
38858 ** The flag is cleared as soon as the journal file is finalized (either
38859 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
38860 ** journal file from being successfully finalized, the setMaster flag
38861 ** is cleared anyway (and the pager will move to ERROR state).
38863 ** doNotSpill
38865 ** This variables control the behavior of cache-spills (calls made by
38866 ** the pcache module to the pagerStress() routine to write cached data
38867 ** to the file-system in order to free up memory).
38869 ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
38870 ** writing to the database from pagerStress() is disabled altogether.
38871 ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
38872 ** comes up during savepoint rollback that requires the pcache module
38873 ** to allocate a new page to prevent the journal file from being written
38874 ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
38875 ** case is a user preference.
38877 ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
38878 ** is permitted, but syncing the journal file is not. This flag is set
38879 ** by sqlite3PagerWrite() when the file-system sector-size is larger than
38880 ** the database page-size in order to prevent a journal sync from happening
38881 ** in between the journalling of two pages on the same sector.
38883 ** subjInMemory
38885 ** This is a boolean variable. If true, then any required sub-journal
38886 ** is opened as an in-memory journal file. If false, then in-memory
38887 ** sub-journals are only used for in-memory pager files.
38889 ** This variable is updated by the upper layer each time a new
38890 ** write-transaction is opened.
38892 ** dbSize, dbOrigSize, dbFileSize
38894 ** Variable dbSize is set to the number of pages in the database file.
38895 ** It is valid in PAGER_READER and higher states (all states except for
38896 ** OPEN and ERROR).
38898 ** dbSize is set based on the size of the database file, which may be
38899 ** larger than the size of the database (the value stored at offset
38900 ** 28 of the database header by the btree). If the size of the file
38901 ** is not an integer multiple of the page-size, the value stored in
38902 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
38903 ** Except, any file that is greater than 0 bytes in size is considered
38904 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
38905 ** to dbSize==1).
38907 ** During a write-transaction, if pages with page-numbers greater than
38908 ** dbSize are modified in the cache, dbSize is updated accordingly.
38909 ** Similarly, if the database is truncated using PagerTruncateImage(),
38910 ** dbSize is updated.
38912 ** Variables dbOrigSize and dbFileSize are valid in states
38913 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
38914 ** variable at the start of the transaction. It is used during rollback,
38915 ** and to determine whether or not pages need to be journalled before
38916 ** being modified.
38918 ** Throughout a write-transaction, dbFileSize contains the size of
38919 ** the file on disk in pages. It is set to a copy of dbSize when the
38920 ** write-transaction is first opened, and updated when VFS calls are made
38921 ** to write or truncate the database file on disk.
38923 ** The only reason the dbFileSize variable is required is to suppress
38924 ** unnecessary calls to xTruncate() after committing a transaction. If,
38925 ** when a transaction is committed, the dbFileSize variable indicates
38926 ** that the database file is larger than the database image (Pager.dbSize),
38927 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
38928 ** to measure the database file on disk, and then truncates it if required.
38929 ** dbFileSize is not used when rolling back a transaction. In this case
38930 ** pager_truncate() is called unconditionally (which means there may be
38931 ** a call to xFilesize() that is not strictly required). In either case,
38932 ** pager_truncate() may cause the file to become smaller or larger.
38934 ** dbHintSize
38936 ** The dbHintSize variable is used to limit the number of calls made to
38937 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
38939 ** dbHintSize is set to a copy of the dbSize variable when a
38940 ** write-transaction is opened (at the same time as dbFileSize and
38941 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
38942 ** dbHintSize is increased to the number of pages that correspond to the
38943 ** size-hint passed to the method call. See pager_write_pagelist() for
38944 ** details.
38946 ** errCode
38948 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
38949 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
38950 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
38951 ** sub-codes.
38953 struct Pager {
38954 sqlite3_vfs *pVfs; /* OS functions to use for IO */
38955 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
38956 u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
38957 u8 useJournal; /* Use a rollback journal on this file */
38958 u8 noSync; /* Do not sync the journal if true */
38959 u8 fullSync; /* Do extra syncs of the journal for robustness */
38960 u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
38961 u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
38962 u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
38963 u8 tempFile; /* zFilename is a temporary file */
38964 u8 readOnly; /* True for a read-only database */
38965 u8 memDb; /* True to inhibit all file I/O */
38967 /**************************************************************************
38968 ** The following block contains those class members that change during
38969 ** routine opertion. Class members not in this block are either fixed
38970 ** when the pager is first created or else only change when there is a
38971 ** significant mode change (such as changing the page_size, locking_mode,
38972 ** or the journal_mode). From another view, these class members describe
38973 ** the "state" of the pager, while other class members describe the
38974 ** "configuration" of the pager.
38976 u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
38977 u8 eLock; /* Current lock held on database file */
38978 u8 changeCountDone; /* Set after incrementing the change-counter */
38979 u8 setMaster; /* True if a m-j name has been written to jrnl */
38980 u8 doNotSpill; /* Do not spill the cache when non-zero */
38981 u8 subjInMemory; /* True to use in-memory sub-journals */
38982 Pgno dbSize; /* Number of pages in the database */
38983 Pgno dbOrigSize; /* dbSize before the current transaction */
38984 Pgno dbFileSize; /* Number of pages in the database file */
38985 Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
38986 int errCode; /* One of several kinds of errors */
38987 int nRec; /* Pages journalled since last j-header written */
38988 u32 cksumInit; /* Quasi-random value added to every checksum */
38989 u32 nSubRec; /* Number of records written to sub-journal */
38990 Bitvec *pInJournal; /* One bit for each page in the database file */
38991 sqlite3_file *fd; /* File descriptor for database */
38992 sqlite3_file *jfd; /* File descriptor for main journal */
38993 sqlite3_file *sjfd; /* File descriptor for sub-journal */
38994 i64 journalOff; /* Current write offset in the journal file */
38995 i64 journalHdr; /* Byte offset to previous journal header */
38996 sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
38997 PagerSavepoint *aSavepoint; /* Array of active savepoints */
38998 int nSavepoint; /* Number of elements in aSavepoint[] */
38999 char dbFileVers[16]; /* Changes whenever database file changes */
39001 u8 bUseFetch; /* True to use xFetch() */
39002 int nMmapOut; /* Number of mmap pages currently outstanding */
39003 sqlite3_int64 szMmap; /* Desired maximum mmap size */
39004 PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
39006 ** End of the routinely-changing class members
39007 ***************************************************************************/
39009 u16 nExtra; /* Add this many bytes to each in-memory page */
39010 i16 nReserve; /* Number of unused bytes at end of each page */
39011 u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
39012 u32 sectorSize; /* Assumed sector size during rollback */
39013 int pageSize; /* Number of bytes in a page */
39014 Pgno mxPgno; /* Maximum allowed size of the database */
39015 i64 journalSizeLimit; /* Size limit for persistent journal files */
39016 char *zFilename; /* Name of the database file */
39017 char *zJournal; /* Name of the journal file */
39018 int (*xBusyHandler)(void*); /* Function to call when busy */
39019 void *pBusyHandlerArg; /* Context argument for xBusyHandler */
39020 int aStat[3]; /* Total cache hits, misses and writes */
39021 #ifdef SQLITE_TEST
39022 int nRead; /* Database pages read */
39023 #endif
39024 void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
39025 #ifdef SQLITE_HAS_CODEC
39026 void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
39027 void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
39028 void (*xCodecFree)(void*); /* Destructor for the codec */
39029 void *pCodec; /* First argument to xCodec... methods */
39030 #endif
39031 char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
39032 PCache *pPCache; /* Pointer to page cache object */
39033 #ifndef SQLITE_OMIT_WAL
39034 Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
39035 char *zWal; /* File name for write-ahead log */
39036 #endif
39040 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
39041 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
39042 ** or CACHE_WRITE to sqlite3_db_status().
39044 #define PAGER_STAT_HIT 0
39045 #define PAGER_STAT_MISS 1
39046 #define PAGER_STAT_WRITE 2
39049 ** The following global variables hold counters used for
39050 ** testing purposes only. These variables do not exist in
39051 ** a non-testing build. These variables are not thread-safe.
39053 #ifdef SQLITE_TEST
39054 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
39055 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
39056 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
39057 # define PAGER_INCR(v) v++
39058 #else
39059 # define PAGER_INCR(v)
39060 #endif
39065 ** Journal files begin with the following magic string. The data
39066 ** was obtained from /dev/random. It is used only as a sanity check.
39068 ** Since version 2.8.0, the journal format contains additional sanity
39069 ** checking information. If the power fails while the journal is being
39070 ** written, semi-random garbage data might appear in the journal
39071 ** file after power is restored. If an attempt is then made
39072 ** to roll the journal back, the database could be corrupted. The additional
39073 ** sanity checking data is an attempt to discover the garbage in the
39074 ** journal and ignore it.
39076 ** The sanity checking information for the new journal format consists
39077 ** of a 32-bit checksum on each page of data. The checksum covers both
39078 ** the page number and the pPager->pageSize bytes of data for the page.
39079 ** This cksum is initialized to a 32-bit random value that appears in the
39080 ** journal file right after the header. The random initializer is important,
39081 ** because garbage data that appears at the end of a journal is likely
39082 ** data that was once in other files that have now been deleted. If the
39083 ** garbage data came from an obsolete journal file, the checksums might
39084 ** be correct. But by initializing the checksum to random value which
39085 ** is different for every journal, we minimize that risk.
39087 static const unsigned char aJournalMagic[] = {
39088 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
39092 ** The size of the of each page record in the journal is given by
39093 ** the following macro.
39095 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
39098 ** The journal header size for this pager. This is usually the same
39099 ** size as a single disk sector. See also setSectorSize().
39101 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
39104 ** The macro MEMDB is true if we are dealing with an in-memory database.
39105 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
39106 ** the value of MEMDB will be a constant and the compiler will optimize
39107 ** out code that would never execute.
39109 #ifdef SQLITE_OMIT_MEMORYDB
39110 # define MEMDB 0
39111 #else
39112 # define MEMDB pPager->memDb
39113 #endif
39116 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
39117 ** interfaces to access the database using memory-mapped I/O.
39119 #if SQLITE_MAX_MMAP_SIZE>0
39120 # define USEFETCH(x) ((x)->bUseFetch)
39121 #else
39122 # define USEFETCH(x) 0
39123 #endif
39126 ** The maximum legal page number is (2^31 - 1).
39128 #define PAGER_MAX_PGNO 2147483647
39131 ** The argument to this macro is a file descriptor (type sqlite3_file*).
39132 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
39134 ** This is so that expressions can be written as:
39136 ** if( isOpen(pPager->jfd) ){ ...
39138 ** instead of
39140 ** if( pPager->jfd->pMethods ){ ...
39142 #define isOpen(pFd) ((pFd)->pMethods)
39145 ** Return true if this pager uses a write-ahead log instead of the usual
39146 ** rollback journal. Otherwise false.
39148 #ifndef SQLITE_OMIT_WAL
39149 static int pagerUseWal(Pager *pPager){
39150 return (pPager->pWal!=0);
39152 #else
39153 # define pagerUseWal(x) 0
39154 # define pagerRollbackWal(x) 0
39155 # define pagerWalFrames(v,w,x,y) 0
39156 # define pagerOpenWalIfPresent(z) SQLITE_OK
39157 # define pagerBeginReadTransaction(z) SQLITE_OK
39158 #endif
39160 #ifndef NDEBUG
39162 ** Usage:
39164 ** assert( assert_pager_state(pPager) );
39166 ** This function runs many asserts to try to find inconsistencies in
39167 ** the internal state of the Pager object.
39169 static int assert_pager_state(Pager *p){
39170 Pager *pPager = p;
39172 /* State must be valid. */
39173 assert( p->eState==PAGER_OPEN
39174 || p->eState==PAGER_READER
39175 || p->eState==PAGER_WRITER_LOCKED
39176 || p->eState==PAGER_WRITER_CACHEMOD
39177 || p->eState==PAGER_WRITER_DBMOD
39178 || p->eState==PAGER_WRITER_FINISHED
39179 || p->eState==PAGER_ERROR
39182 /* Regardless of the current state, a temp-file connection always behaves
39183 ** as if it has an exclusive lock on the database file. It never updates
39184 ** the change-counter field, so the changeCountDone flag is always set.
39186 assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
39187 assert( p->tempFile==0 || pPager->changeCountDone );
39189 /* If the useJournal flag is clear, the journal-mode must be "OFF".
39190 ** And if the journal-mode is "OFF", the journal file must not be open.
39192 assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
39193 assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
39195 /* Check that MEMDB implies noSync. And an in-memory journal. Since
39196 ** this means an in-memory pager performs no IO at all, it cannot encounter
39197 ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
39198 ** a journal file. (although the in-memory journal implementation may
39199 ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
39200 ** is therefore not possible for an in-memory pager to enter the ERROR
39201 ** state.
39203 if( MEMDB ){
39204 assert( p->noSync );
39205 assert( p->journalMode==PAGER_JOURNALMODE_OFF
39206 || p->journalMode==PAGER_JOURNALMODE_MEMORY
39208 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
39209 assert( pagerUseWal(p)==0 );
39212 /* If changeCountDone is set, a RESERVED lock or greater must be held
39213 ** on the file.
39215 assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
39216 assert( p->eLock!=PENDING_LOCK );
39218 switch( p->eState ){
39219 case PAGER_OPEN:
39220 assert( !MEMDB );
39221 assert( pPager->errCode==SQLITE_OK );
39222 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
39223 break;
39225 case PAGER_READER:
39226 assert( pPager->errCode==SQLITE_OK );
39227 assert( p->eLock!=UNKNOWN_LOCK );
39228 assert( p->eLock>=SHARED_LOCK );
39229 break;
39231 case PAGER_WRITER_LOCKED:
39232 assert( p->eLock!=UNKNOWN_LOCK );
39233 assert( pPager->errCode==SQLITE_OK );
39234 if( !pagerUseWal(pPager) ){
39235 assert( p->eLock>=RESERVED_LOCK );
39237 assert( pPager->dbSize==pPager->dbOrigSize );
39238 assert( pPager->dbOrigSize==pPager->dbFileSize );
39239 assert( pPager->dbOrigSize==pPager->dbHintSize );
39240 assert( pPager->setMaster==0 );
39241 break;
39243 case PAGER_WRITER_CACHEMOD:
39244 assert( p->eLock!=UNKNOWN_LOCK );
39245 assert( pPager->errCode==SQLITE_OK );
39246 if( !pagerUseWal(pPager) ){
39247 /* It is possible that if journal_mode=wal here that neither the
39248 ** journal file nor the WAL file are open. This happens during
39249 ** a rollback transaction that switches from journal_mode=off
39250 ** to journal_mode=wal.
39252 assert( p->eLock>=RESERVED_LOCK );
39253 assert( isOpen(p->jfd)
39254 || p->journalMode==PAGER_JOURNALMODE_OFF
39255 || p->journalMode==PAGER_JOURNALMODE_WAL
39258 assert( pPager->dbOrigSize==pPager->dbFileSize );
39259 assert( pPager->dbOrigSize==pPager->dbHintSize );
39260 break;
39262 case PAGER_WRITER_DBMOD:
39263 assert( p->eLock==EXCLUSIVE_LOCK );
39264 assert( pPager->errCode==SQLITE_OK );
39265 assert( !pagerUseWal(pPager) );
39266 assert( p->eLock>=EXCLUSIVE_LOCK );
39267 assert( isOpen(p->jfd)
39268 || p->journalMode==PAGER_JOURNALMODE_OFF
39269 || p->journalMode==PAGER_JOURNALMODE_WAL
39271 assert( pPager->dbOrigSize<=pPager->dbHintSize );
39272 break;
39274 case PAGER_WRITER_FINISHED:
39275 assert( p->eLock==EXCLUSIVE_LOCK );
39276 assert( pPager->errCode==SQLITE_OK );
39277 assert( !pagerUseWal(pPager) );
39278 assert( isOpen(p->jfd)
39279 || p->journalMode==PAGER_JOURNALMODE_OFF
39280 || p->journalMode==PAGER_JOURNALMODE_WAL
39282 break;
39284 case PAGER_ERROR:
39285 /* There must be at least one outstanding reference to the pager if
39286 ** in ERROR state. Otherwise the pager should have already dropped
39287 ** back to OPEN state.
39289 assert( pPager->errCode!=SQLITE_OK );
39290 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
39291 break;
39294 return 1;
39296 #endif /* ifndef NDEBUG */
39298 #ifdef SQLITE_DEBUG
39300 ** Return a pointer to a human readable string in a static buffer
39301 ** containing the state of the Pager object passed as an argument. This
39302 ** is intended to be used within debuggers. For example, as an alternative
39303 ** to "print *pPager" in gdb:
39305 ** (gdb) printf "%s", print_pager_state(pPager)
39307 static char *print_pager_state(Pager *p){
39308 static char zRet[1024];
39310 sqlite3_snprintf(1024, zRet,
39311 "Filename: %s\n"
39312 "State: %s errCode=%d\n"
39313 "Lock: %s\n"
39314 "Locking mode: locking_mode=%s\n"
39315 "Journal mode: journal_mode=%s\n"
39316 "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
39317 "Journal: journalOff=%lld journalHdr=%lld\n"
39318 "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
39319 , p->zFilename
39320 , p->eState==PAGER_OPEN ? "OPEN" :
39321 p->eState==PAGER_READER ? "READER" :
39322 p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
39323 p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
39324 p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
39325 p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
39326 p->eState==PAGER_ERROR ? "ERROR" : "?error?"
39327 , (int)p->errCode
39328 , p->eLock==NO_LOCK ? "NO_LOCK" :
39329 p->eLock==RESERVED_LOCK ? "RESERVED" :
39330 p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
39331 p->eLock==SHARED_LOCK ? "SHARED" :
39332 p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
39333 , p->exclusiveMode ? "exclusive" : "normal"
39334 , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
39335 p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
39336 p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
39337 p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
39338 p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
39339 p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
39340 , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
39341 , p->journalOff, p->journalHdr
39342 , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
39345 return zRet;
39347 #endif
39350 ** Return true if it is necessary to write page *pPg into the sub-journal.
39351 ** A page needs to be written into the sub-journal if there exists one
39352 ** or more open savepoints for which:
39354 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
39355 ** * The bit corresponding to the page-number is not set in
39356 ** PagerSavepoint.pInSavepoint.
39358 static int subjRequiresPage(PgHdr *pPg){
39359 Pager *pPager = pPg->pPager;
39360 PagerSavepoint *p;
39361 Pgno pgno;
39362 int i;
39363 if( pPager->nSavepoint ){
39364 pgno = pPg->pgno;
39365 for(i=0; i<pPager->nSavepoint; i++){
39366 p = &pPager->aSavepoint[i];
39367 if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
39368 return 1;
39372 return 0;
39376 ** Return true if the page is already in the journal file.
39378 static int pageInJournal(PgHdr *pPg){
39379 return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
39383 ** Read a 32-bit integer from the given file descriptor. Store the integer
39384 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
39385 ** error code is something goes wrong.
39387 ** All values are stored on disk as big-endian.
39389 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
39390 unsigned char ac[4];
39391 int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
39392 if( rc==SQLITE_OK ){
39393 *pRes = sqlite3Get4byte(ac);
39395 return rc;
39399 ** Write a 32-bit integer into a string buffer in big-endian byte order.
39401 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
39405 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
39406 ** on success or an error code is something goes wrong.
39408 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
39409 char ac[4];
39410 put32bits(ac, val);
39411 return sqlite3OsWrite(fd, ac, 4, offset);
39415 ** Unlock the database file to level eLock, which must be either NO_LOCK
39416 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
39417 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
39419 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
39420 ** called, do not modify it. See the comment above the #define of
39421 ** UNKNOWN_LOCK for an explanation of this.
39423 static int pagerUnlockDb(Pager *pPager, int eLock){
39424 int rc = SQLITE_OK;
39426 assert( !pPager->exclusiveMode || pPager->eLock==eLock );
39427 assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
39428 assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
39429 if( isOpen(pPager->fd) ){
39430 assert( pPager->eLock>=eLock );
39431 rc = sqlite3OsUnlock(pPager->fd, eLock);
39432 if( pPager->eLock!=UNKNOWN_LOCK ){
39433 pPager->eLock = (u8)eLock;
39435 IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
39437 return rc;
39441 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
39442 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
39443 ** Pager.eLock variable to the new locking state.
39445 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
39446 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
39447 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
39448 ** of this.
39450 static int pagerLockDb(Pager *pPager, int eLock){
39451 int rc = SQLITE_OK;
39453 assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
39454 if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
39455 rc = sqlite3OsLock(pPager->fd, eLock);
39456 if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
39457 pPager->eLock = (u8)eLock;
39458 IOTRACE(("LOCK %p %d\n", pPager, eLock))
39461 return rc;
39465 ** This function determines whether or not the atomic-write optimization
39466 ** can be used with this pager. The optimization can be used if:
39468 ** (a) the value returned by OsDeviceCharacteristics() indicates that
39469 ** a database page may be written atomically, and
39470 ** (b) the value returned by OsSectorSize() is less than or equal
39471 ** to the page size.
39473 ** The optimization is also always enabled for temporary files. It is
39474 ** an error to call this function if pPager is opened on an in-memory
39475 ** database.
39477 ** If the optimization cannot be used, 0 is returned. If it can be used,
39478 ** then the value returned is the size of the journal file when it
39479 ** contains rollback data for exactly one page.
39481 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
39482 static int jrnlBufferSize(Pager *pPager){
39483 assert( !MEMDB );
39484 if( !pPager->tempFile ){
39485 int dc; /* Device characteristics */
39486 int nSector; /* Sector size */
39487 int szPage; /* Page size */
39489 assert( isOpen(pPager->fd) );
39490 dc = sqlite3OsDeviceCharacteristics(pPager->fd);
39491 nSector = pPager->sectorSize;
39492 szPage = pPager->pageSize;
39494 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
39495 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
39496 if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
39497 return 0;
39501 return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
39503 #endif
39506 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
39507 ** on the cache using a hash function. This is used for testing
39508 ** and debugging only.
39510 #ifdef SQLITE_CHECK_PAGES
39512 ** Return a 32-bit hash of the page data for pPage.
39514 static u32 pager_datahash(int nByte, unsigned char *pData){
39515 u32 hash = 0;
39516 int i;
39517 for(i=0; i<nByte; i++){
39518 hash = (hash*1039) + pData[i];
39520 return hash;
39522 static u32 pager_pagehash(PgHdr *pPage){
39523 return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
39525 static void pager_set_pagehash(PgHdr *pPage){
39526 pPage->pageHash = pager_pagehash(pPage);
39530 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
39531 ** is defined, and NDEBUG is not defined, an assert() statement checks
39532 ** that the page is either dirty or still matches the calculated page-hash.
39534 #define CHECK_PAGE(x) checkPage(x)
39535 static void checkPage(PgHdr *pPg){
39536 Pager *pPager = pPg->pPager;
39537 assert( pPager->eState!=PAGER_ERROR );
39538 assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
39541 #else
39542 #define pager_datahash(X,Y) 0
39543 #define pager_pagehash(X) 0
39544 #define pager_set_pagehash(X)
39545 #define CHECK_PAGE(x)
39546 #endif /* SQLITE_CHECK_PAGES */
39549 ** When this is called the journal file for pager pPager must be open.
39550 ** This function attempts to read a master journal file name from the
39551 ** end of the file and, if successful, copies it into memory supplied
39552 ** by the caller. See comments above writeMasterJournal() for the format
39553 ** used to store a master journal file name at the end of a journal file.
39555 ** zMaster must point to a buffer of at least nMaster bytes allocated by
39556 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
39557 ** enough space to write the master journal name). If the master journal
39558 ** name in the journal is longer than nMaster bytes (including a
39559 ** nul-terminator), then this is handled as if no master journal name
39560 ** were present in the journal.
39562 ** If a master journal file name is present at the end of the journal
39563 ** file, then it is copied into the buffer pointed to by zMaster. A
39564 ** nul-terminator byte is appended to the buffer following the master
39565 ** journal file name.
39567 ** If it is determined that no master journal file name is present
39568 ** zMaster[0] is set to 0 and SQLITE_OK returned.
39570 ** If an error occurs while reading from the journal file, an SQLite
39571 ** error code is returned.
39573 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
39574 int rc; /* Return code */
39575 u32 len; /* Length in bytes of master journal name */
39576 i64 szJ; /* Total size in bytes of journal file pJrnl */
39577 u32 cksum; /* MJ checksum value read from journal */
39578 u32 u; /* Unsigned loop counter */
39579 unsigned char aMagic[8]; /* A buffer to hold the magic header */
39580 zMaster[0] = '\0';
39582 if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
39583 || szJ<16
39584 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
39585 || len>=nMaster
39586 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
39587 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
39588 || memcmp(aMagic, aJournalMagic, 8)
39589 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
39591 return rc;
39594 /* See if the checksum matches the master journal name */
39595 for(u=0; u<len; u++){
39596 cksum -= zMaster[u];
39598 if( cksum ){
39599 /* If the checksum doesn't add up, then one or more of the disk sectors
39600 ** containing the master journal filename is corrupted. This means
39601 ** definitely roll back, so just return SQLITE_OK and report a (nul)
39602 ** master-journal filename.
39604 len = 0;
39606 zMaster[len] = '\0';
39608 return SQLITE_OK;
39612 ** Return the offset of the sector boundary at or immediately
39613 ** following the value in pPager->journalOff, assuming a sector
39614 ** size of pPager->sectorSize bytes.
39616 ** i.e for a sector size of 512:
39618 ** Pager.journalOff Return value
39619 ** ---------------------------------------
39620 ** 0 0
39621 ** 512 512
39622 ** 100 512
39623 ** 2000 2048
39626 static i64 journalHdrOffset(Pager *pPager){
39627 i64 offset = 0;
39628 i64 c = pPager->journalOff;
39629 if( c ){
39630 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
39632 assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
39633 assert( offset>=c );
39634 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
39635 return offset;
39639 ** The journal file must be open when this function is called.
39641 ** This function is a no-op if the journal file has not been written to
39642 ** within the current transaction (i.e. if Pager.journalOff==0).
39644 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
39645 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
39646 ** zero the 28-byte header at the start of the journal file. In either case,
39647 ** if the pager is not in no-sync mode, sync the journal file immediately
39648 ** after writing or truncating it.
39650 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
39651 ** following the truncation or zeroing described above the size of the
39652 ** journal file in bytes is larger than this value, then truncate the
39653 ** journal file to Pager.journalSizeLimit bytes. The journal file does
39654 ** not need to be synced following this operation.
39656 ** If an IO error occurs, abandon processing and return the IO error code.
39657 ** Otherwise, return SQLITE_OK.
39659 static int zeroJournalHdr(Pager *pPager, int doTruncate){
39660 int rc = SQLITE_OK; /* Return code */
39661 assert( isOpen(pPager->jfd) );
39662 if( pPager->journalOff ){
39663 const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
39665 IOTRACE(("JZEROHDR %p\n", pPager))
39666 if( doTruncate || iLimit==0 ){
39667 rc = sqlite3OsTruncate(pPager->jfd, 0);
39668 }else{
39669 static const char zeroHdr[28] = {0};
39670 rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
39672 if( rc==SQLITE_OK && !pPager->noSync ){
39673 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
39676 /* At this point the transaction is committed but the write lock
39677 ** is still held on the file. If there is a size limit configured for
39678 ** the persistent journal and the journal file currently consumes more
39679 ** space than that limit allows for, truncate it now. There is no need
39680 ** to sync the file following this operation.
39682 if( rc==SQLITE_OK && iLimit>0 ){
39683 i64 sz;
39684 rc = sqlite3OsFileSize(pPager->jfd, &sz);
39685 if( rc==SQLITE_OK && sz>iLimit ){
39686 rc = sqlite3OsTruncate(pPager->jfd, iLimit);
39690 return rc;
39694 ** The journal file must be open when this routine is called. A journal
39695 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
39696 ** current location.
39698 ** The format for the journal header is as follows:
39699 ** - 8 bytes: Magic identifying journal format.
39700 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
39701 ** - 4 bytes: Random number used for page hash.
39702 ** - 4 bytes: Initial database page count.
39703 ** - 4 bytes: Sector size used by the process that wrote this journal.
39704 ** - 4 bytes: Database page size.
39706 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
39708 static int writeJournalHdr(Pager *pPager){
39709 int rc = SQLITE_OK; /* Return code */
39710 char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
39711 u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
39712 u32 nWrite; /* Bytes of header sector written */
39713 int ii; /* Loop counter */
39715 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
39717 if( nHeader>JOURNAL_HDR_SZ(pPager) ){
39718 nHeader = JOURNAL_HDR_SZ(pPager);
39721 /* If there are active savepoints and any of them were created
39722 ** since the most recent journal header was written, update the
39723 ** PagerSavepoint.iHdrOffset fields now.
39725 for(ii=0; ii<pPager->nSavepoint; ii++){
39726 if( pPager->aSavepoint[ii].iHdrOffset==0 ){
39727 pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
39731 pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
39734 ** Write the nRec Field - the number of page records that follow this
39735 ** journal header. Normally, zero is written to this value at this time.
39736 ** After the records are added to the journal (and the journal synced,
39737 ** if in full-sync mode), the zero is overwritten with the true number
39738 ** of records (see syncJournal()).
39740 ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
39741 ** reading the journal this value tells SQLite to assume that the
39742 ** rest of the journal file contains valid page records. This assumption
39743 ** is dangerous, as if a failure occurred whilst writing to the journal
39744 ** file it may contain some garbage data. There are two scenarios
39745 ** where this risk can be ignored:
39747 ** * When the pager is in no-sync mode. Corruption can follow a
39748 ** power failure in this case anyway.
39750 ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
39751 ** that garbage data is never appended to the journal file.
39753 assert( isOpen(pPager->fd) || pPager->noSync );
39754 if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
39755 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
39757 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
39758 put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
39759 }else{
39760 memset(zHeader, 0, sizeof(aJournalMagic)+4);
39763 /* The random check-hash initializer */
39764 sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
39765 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
39766 /* The initial database size */
39767 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
39768 /* The assumed sector size for this process */
39769 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
39771 /* The page size */
39772 put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
39774 /* Initializing the tail of the buffer is not necessary. Everything
39775 ** works find if the following memset() is omitted. But initializing
39776 ** the memory prevents valgrind from complaining, so we are willing to
39777 ** take the performance hit.
39779 memset(&zHeader[sizeof(aJournalMagic)+20], 0,
39780 nHeader-(sizeof(aJournalMagic)+20));
39782 /* In theory, it is only necessary to write the 28 bytes that the
39783 ** journal header consumes to the journal file here. Then increment the
39784 ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
39785 ** record is written to the following sector (leaving a gap in the file
39786 ** that will be implicitly filled in by the OS).
39788 ** However it has been discovered that on some systems this pattern can
39789 ** be significantly slower than contiguously writing data to the file,
39790 ** even if that means explicitly writing data to the block of
39791 ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
39792 ** is done.
39794 ** The loop is required here in case the sector-size is larger than the
39795 ** database page size. Since the zHeader buffer is only Pager.pageSize
39796 ** bytes in size, more than one call to sqlite3OsWrite() may be required
39797 ** to populate the entire journal header sector.
39799 for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
39800 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
39801 rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
39802 assert( pPager->journalHdr <= pPager->journalOff );
39803 pPager->journalOff += nHeader;
39806 return rc;
39810 ** The journal file must be open when this is called. A journal header file
39811 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
39812 ** file. The current location in the journal file is given by
39813 ** pPager->journalOff. See comments above function writeJournalHdr() for
39814 ** a description of the journal header format.
39816 ** If the header is read successfully, *pNRec is set to the number of
39817 ** page records following this header and *pDbSize is set to the size of the
39818 ** database before the transaction began, in pages. Also, pPager->cksumInit
39819 ** is set to the value read from the journal header. SQLITE_OK is returned
39820 ** in this case.
39822 ** If the journal header file appears to be corrupted, SQLITE_DONE is
39823 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
39824 ** cannot be read from the journal file an error code is returned.
39826 static int readJournalHdr(
39827 Pager *pPager, /* Pager object */
39828 int isHot,
39829 i64 journalSize, /* Size of the open journal file in bytes */
39830 u32 *pNRec, /* OUT: Value read from the nRec field */
39831 u32 *pDbSize /* OUT: Value of original database size field */
39833 int rc; /* Return code */
39834 unsigned char aMagic[8]; /* A buffer to hold the magic header */
39835 i64 iHdrOff; /* Offset of journal header being read */
39837 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
39839 /* Advance Pager.journalOff to the start of the next sector. If the
39840 ** journal file is too small for there to be a header stored at this
39841 ** point, return SQLITE_DONE.
39843 pPager->journalOff = journalHdrOffset(pPager);
39844 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
39845 return SQLITE_DONE;
39847 iHdrOff = pPager->journalOff;
39849 /* Read in the first 8 bytes of the journal header. If they do not match
39850 ** the magic string found at the start of each journal header, return
39851 ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
39852 ** proceed.
39854 if( isHot || iHdrOff!=pPager->journalHdr ){
39855 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
39856 if( rc ){
39857 return rc;
39859 if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
39860 return SQLITE_DONE;
39864 /* Read the first three 32-bit fields of the journal header: The nRec
39865 ** field, the checksum-initializer and the database size at the start
39866 ** of the transaction. Return an error code if anything goes wrong.
39868 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
39869 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
39870 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
39872 return rc;
39875 if( pPager->journalOff==0 ){
39876 u32 iPageSize; /* Page-size field of journal header */
39877 u32 iSectorSize; /* Sector-size field of journal header */
39879 /* Read the page-size and sector-size journal header fields. */
39880 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
39881 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
39883 return rc;
39886 /* Versions of SQLite prior to 3.5.8 set the page-size field of the
39887 ** journal header to zero. In this case, assume that the Pager.pageSize
39888 ** variable is already set to the correct page size.
39890 if( iPageSize==0 ){
39891 iPageSize = pPager->pageSize;
39894 /* Check that the values read from the page-size and sector-size fields
39895 ** are within range. To be 'in range', both values need to be a power
39896 ** of two greater than or equal to 512 or 32, and not greater than their
39897 ** respective compile time maximum limits.
39899 if( iPageSize<512 || iSectorSize<32
39900 || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
39901 || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
39903 /* If the either the page-size or sector-size in the journal-header is
39904 ** invalid, then the process that wrote the journal-header must have
39905 ** crashed before the header was synced. In this case stop reading
39906 ** the journal file here.
39908 return SQLITE_DONE;
39911 /* Update the page-size to match the value read from the journal.
39912 ** Use a testcase() macro to make sure that malloc failure within
39913 ** PagerSetPagesize() is tested.
39915 rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
39916 testcase( rc!=SQLITE_OK );
39918 /* Update the assumed sector-size to match the value used by
39919 ** the process that created this journal. If this journal was
39920 ** created by a process other than this one, then this routine
39921 ** is being called from within pager_playback(). The local value
39922 ** of Pager.sectorSize is restored at the end of that routine.
39924 pPager->sectorSize = iSectorSize;
39927 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
39928 return rc;
39933 ** Write the supplied master journal name into the journal file for pager
39934 ** pPager at the current location. The master journal name must be the last
39935 ** thing written to a journal file. If the pager is in full-sync mode, the
39936 ** journal file descriptor is advanced to the next sector boundary before
39937 ** anything is written. The format is:
39939 ** + 4 bytes: PAGER_MJ_PGNO.
39940 ** + N bytes: Master journal filename in utf-8.
39941 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
39942 ** + 4 bytes: Master journal name checksum.
39943 ** + 8 bytes: aJournalMagic[].
39945 ** The master journal page checksum is the sum of the bytes in the master
39946 ** journal name, where each byte is interpreted as a signed 8-bit integer.
39948 ** If zMaster is a NULL pointer (occurs for a single database transaction),
39949 ** this call is a no-op.
39951 static int writeMasterJournal(Pager *pPager, const char *zMaster){
39952 int rc; /* Return code */
39953 int nMaster; /* Length of string zMaster */
39954 i64 iHdrOff; /* Offset of header in journal file */
39955 i64 jrnlSize; /* Size of journal file on disk */
39956 u32 cksum = 0; /* Checksum of string zMaster */
39958 assert( pPager->setMaster==0 );
39959 assert( !pagerUseWal(pPager) );
39961 if( !zMaster
39962 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
39963 || pPager->journalMode==PAGER_JOURNALMODE_OFF
39965 return SQLITE_OK;
39967 pPager->setMaster = 1;
39968 assert( isOpen(pPager->jfd) );
39969 assert( pPager->journalHdr <= pPager->journalOff );
39971 /* Calculate the length in bytes and the checksum of zMaster */
39972 for(nMaster=0; zMaster[nMaster]; nMaster++){
39973 cksum += zMaster[nMaster];
39976 /* If in full-sync mode, advance to the next disk sector before writing
39977 ** the master journal name. This is in case the previous page written to
39978 ** the journal has already been synced.
39980 if( pPager->fullSync ){
39981 pPager->journalOff = journalHdrOffset(pPager);
39983 iHdrOff = pPager->journalOff;
39985 /* Write the master journal data to the end of the journal file. If
39986 ** an error occurs, return the error code to the caller.
39988 if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
39989 || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
39990 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
39991 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
39992 || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
39994 return rc;
39996 pPager->journalOff += (nMaster+20);
39998 /* If the pager is in peristent-journal mode, then the physical
39999 ** journal-file may extend past the end of the master-journal name
40000 ** and 8 bytes of magic data just written to the file. This is
40001 ** dangerous because the code to rollback a hot-journal file
40002 ** will not be able to find the master-journal name to determine
40003 ** whether or not the journal is hot.
40005 ** Easiest thing to do in this scenario is to truncate the journal
40006 ** file to the required size.
40008 if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
40009 && jrnlSize>pPager->journalOff
40011 rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
40013 return rc;
40017 ** Find a page in the hash table given its page number. Return
40018 ** a pointer to the page or NULL if the requested page is not
40019 ** already in memory.
40021 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
40022 PgHdr *p; /* Return value */
40024 /* It is not possible for a call to PcacheFetch() with createFlag==0 to
40025 ** fail, since no attempt to allocate dynamic memory will be made.
40027 (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
40028 return p;
40032 ** Discard the entire contents of the in-memory page-cache.
40034 static void pager_reset(Pager *pPager){
40035 sqlite3BackupRestart(pPager->pBackup);
40036 sqlite3PcacheClear(pPager->pPCache);
40040 ** Free all structures in the Pager.aSavepoint[] array and set both
40041 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
40042 ** if it is open and the pager is not in exclusive mode.
40044 static void releaseAllSavepoints(Pager *pPager){
40045 int ii; /* Iterator for looping through Pager.aSavepoint */
40046 for(ii=0; ii<pPager->nSavepoint; ii++){
40047 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
40049 if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
40050 sqlite3OsClose(pPager->sjfd);
40052 sqlite3_free(pPager->aSavepoint);
40053 pPager->aSavepoint = 0;
40054 pPager->nSavepoint = 0;
40055 pPager->nSubRec = 0;
40059 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
40060 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
40061 ** or SQLITE_NOMEM if a malloc failure occurs.
40063 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
40064 int ii; /* Loop counter */
40065 int rc = SQLITE_OK; /* Result code */
40067 for(ii=0; ii<pPager->nSavepoint; ii++){
40068 PagerSavepoint *p = &pPager->aSavepoint[ii];
40069 if( pgno<=p->nOrig ){
40070 rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
40071 testcase( rc==SQLITE_NOMEM );
40072 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
40075 return rc;
40079 ** This function is a no-op if the pager is in exclusive mode and not
40080 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
40081 ** state.
40083 ** If the pager is not in exclusive-access mode, the database file is
40084 ** completely unlocked. If the file is unlocked and the file-system does
40085 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
40086 ** closed (if it is open).
40088 ** If the pager is in ERROR state when this function is called, the
40089 ** contents of the pager cache are discarded before switching back to
40090 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
40091 ** or not, any journal file left in the file-system will be treated
40092 ** as a hot-journal and rolled back the next time a read-transaction
40093 ** is opened (by this or by any other connection).
40095 static void pager_unlock(Pager *pPager){
40097 assert( pPager->eState==PAGER_READER
40098 || pPager->eState==PAGER_OPEN
40099 || pPager->eState==PAGER_ERROR
40102 sqlite3BitvecDestroy(pPager->pInJournal);
40103 pPager->pInJournal = 0;
40104 releaseAllSavepoints(pPager);
40106 if( pagerUseWal(pPager) ){
40107 assert( !isOpen(pPager->jfd) );
40108 sqlite3WalEndReadTransaction(pPager->pWal);
40109 pPager->eState = PAGER_OPEN;
40110 }else if( !pPager->exclusiveMode ){
40111 int rc; /* Error code returned by pagerUnlockDb() */
40112 int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
40114 /* If the operating system support deletion of open files, then
40115 ** close the journal file when dropping the database lock. Otherwise
40116 ** another connection with journal_mode=delete might delete the file
40117 ** out from under us.
40119 assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
40120 assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
40121 assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
40122 assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
40123 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
40124 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
40125 if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
40126 || 1!=(pPager->journalMode & 5)
40128 sqlite3OsClose(pPager->jfd);
40131 /* If the pager is in the ERROR state and the call to unlock the database
40132 ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
40133 ** above the #define for UNKNOWN_LOCK for an explanation of why this
40134 ** is necessary.
40136 rc = pagerUnlockDb(pPager, NO_LOCK);
40137 if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
40138 pPager->eLock = UNKNOWN_LOCK;
40141 /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
40142 ** without clearing the error code. This is intentional - the error
40143 ** code is cleared and the cache reset in the block below.
40145 assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
40146 pPager->changeCountDone = 0;
40147 pPager->eState = PAGER_OPEN;
40150 /* If Pager.errCode is set, the contents of the pager cache cannot be
40151 ** trusted. Now that there are no outstanding references to the pager,
40152 ** it can safely move back to PAGER_OPEN state. This happens in both
40153 ** normal and exclusive-locking mode.
40155 if( pPager->errCode ){
40156 assert( !MEMDB );
40157 pager_reset(pPager);
40158 pPager->changeCountDone = pPager->tempFile;
40159 pPager->eState = PAGER_OPEN;
40160 pPager->errCode = SQLITE_OK;
40161 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
40164 pPager->journalOff = 0;
40165 pPager->journalHdr = 0;
40166 pPager->setMaster = 0;
40170 ** This function is called whenever an IOERR or FULL error that requires
40171 ** the pager to transition into the ERROR state may ahve occurred.
40172 ** The first argument is a pointer to the pager structure, the second
40173 ** the error-code about to be returned by a pager API function. The
40174 ** value returned is a copy of the second argument to this function.
40176 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
40177 ** IOERR sub-codes, the pager enters the ERROR state and the error code
40178 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
40179 ** all major API calls on the Pager will immediately return Pager.errCode.
40181 ** The ERROR state indicates that the contents of the pager-cache
40182 ** cannot be trusted. This state can be cleared by completely discarding
40183 ** the contents of the pager-cache. If a transaction was active when
40184 ** the persistent error occurred, then the rollback journal may need
40185 ** to be replayed to restore the contents of the database file (as if
40186 ** it were a hot-journal).
40188 static int pager_error(Pager *pPager, int rc){
40189 int rc2 = rc & 0xff;
40190 assert( rc==SQLITE_OK || !MEMDB );
40191 assert(
40192 pPager->errCode==SQLITE_FULL ||
40193 pPager->errCode==SQLITE_OK ||
40194 (pPager->errCode & 0xff)==SQLITE_IOERR
40196 if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
40197 pPager->errCode = rc;
40198 pPager->eState = PAGER_ERROR;
40200 return rc;
40203 static int pager_truncate(Pager *pPager, Pgno nPage);
40206 ** This routine ends a transaction. A transaction is usually ended by
40207 ** either a COMMIT or a ROLLBACK operation. This routine may be called
40208 ** after rollback of a hot-journal, or if an error occurs while opening
40209 ** the journal file or writing the very first journal-header of a
40210 ** database transaction.
40212 ** This routine is never called in PAGER_ERROR state. If it is called
40213 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
40214 ** exclusive than a RESERVED lock, it is a no-op.
40216 ** Otherwise, any active savepoints are released.
40218 ** If the journal file is open, then it is "finalized". Once a journal
40219 ** file has been finalized it is not possible to use it to roll back a
40220 ** transaction. Nor will it be considered to be a hot-journal by this
40221 ** or any other database connection. Exactly how a journal is finalized
40222 ** depends on whether or not the pager is running in exclusive mode and
40223 ** the current journal-mode (Pager.journalMode value), as follows:
40225 ** journalMode==MEMORY
40226 ** Journal file descriptor is simply closed. This destroys an
40227 ** in-memory journal.
40229 ** journalMode==TRUNCATE
40230 ** Journal file is truncated to zero bytes in size.
40232 ** journalMode==PERSIST
40233 ** The first 28 bytes of the journal file are zeroed. This invalidates
40234 ** the first journal header in the file, and hence the entire journal
40235 ** file. An invalid journal file cannot be rolled back.
40237 ** journalMode==DELETE
40238 ** The journal file is closed and deleted using sqlite3OsDelete().
40240 ** If the pager is running in exclusive mode, this method of finalizing
40241 ** the journal file is never used. Instead, if the journalMode is
40242 ** DELETE and the pager is in exclusive mode, the method described under
40243 ** journalMode==PERSIST is used instead.
40245 ** After the journal is finalized, the pager moves to PAGER_READER state.
40246 ** If running in non-exclusive rollback mode, the lock on the file is
40247 ** downgraded to a SHARED_LOCK.
40249 ** SQLITE_OK is returned if no error occurs. If an error occurs during
40250 ** any of the IO operations to finalize the journal file or unlock the
40251 ** database then the IO error code is returned to the user. If the
40252 ** operation to finalize the journal file fails, then the code still
40253 ** tries to unlock the database file if not in exclusive mode. If the
40254 ** unlock operation fails as well, then the first error code related
40255 ** to the first error encountered (the journal finalization one) is
40256 ** returned.
40258 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
40259 int rc = SQLITE_OK; /* Error code from journal finalization operation */
40260 int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
40262 /* Do nothing if the pager does not have an open write transaction
40263 ** or at least a RESERVED lock. This function may be called when there
40264 ** is no write-transaction active but a RESERVED or greater lock is
40265 ** held under two circumstances:
40267 ** 1. After a successful hot-journal rollback, it is called with
40268 ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
40270 ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
40271 ** lock switches back to locking_mode=normal and then executes a
40272 ** read-transaction, this function is called with eState==PAGER_READER
40273 ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
40275 assert( assert_pager_state(pPager) );
40276 assert( pPager->eState!=PAGER_ERROR );
40277 if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
40278 return SQLITE_OK;
40281 releaseAllSavepoints(pPager);
40282 assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
40283 if( isOpen(pPager->jfd) ){
40284 assert( !pagerUseWal(pPager) );
40286 /* Finalize the journal file. */
40287 if( sqlite3IsMemJournal(pPager->jfd) ){
40288 assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
40289 sqlite3OsClose(pPager->jfd);
40290 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
40291 if( pPager->journalOff==0 ){
40292 rc = SQLITE_OK;
40293 }else{
40294 rc = sqlite3OsTruncate(pPager->jfd, 0);
40296 pPager->journalOff = 0;
40297 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
40298 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
40300 rc = zeroJournalHdr(pPager, hasMaster);
40301 pPager->journalOff = 0;
40302 }else{
40303 /* This branch may be executed with Pager.journalMode==MEMORY if
40304 ** a hot-journal was just rolled back. In this case the journal
40305 ** file should be closed and deleted. If this connection writes to
40306 ** the database file, it will do so using an in-memory journal.
40308 int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
40309 assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
40310 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
40311 || pPager->journalMode==PAGER_JOURNALMODE_WAL
40313 sqlite3OsClose(pPager->jfd);
40314 if( bDelete ){
40315 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
40320 #ifdef SQLITE_CHECK_PAGES
40321 sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
40322 if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
40323 PgHdr *p = pager_lookup(pPager, 1);
40324 if( p ){
40325 p->pageHash = 0;
40326 sqlite3PagerUnref(p);
40329 #endif
40331 sqlite3BitvecDestroy(pPager->pInJournal);
40332 pPager->pInJournal = 0;
40333 pPager->nRec = 0;
40334 sqlite3PcacheCleanAll(pPager->pPCache);
40335 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
40337 if( pagerUseWal(pPager) ){
40338 /* Drop the WAL write-lock, if any. Also, if the connection was in
40339 ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
40340 ** lock held on the database file.
40342 rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
40343 assert( rc2==SQLITE_OK );
40344 }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
40345 /* This branch is taken when committing a transaction in rollback-journal
40346 ** mode if the database file on disk is larger than the database image.
40347 ** At this point the journal has been finalized and the transaction
40348 ** successfully committed, but the EXCLUSIVE lock is still held on the
40349 ** file. So it is safe to truncate the database file to its minimum
40350 ** required size. */
40351 assert( pPager->eLock==EXCLUSIVE_LOCK );
40352 rc = pager_truncate(pPager, pPager->dbSize);
40355 if( !pPager->exclusiveMode
40356 && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
40358 rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
40359 pPager->changeCountDone = 0;
40361 pPager->eState = PAGER_READER;
40362 pPager->setMaster = 0;
40364 return (rc==SQLITE_OK?rc2:rc);
40368 ** Execute a rollback if a transaction is active and unlock the
40369 ** database file.
40371 ** If the pager has already entered the ERROR state, do not attempt
40372 ** the rollback at this time. Instead, pager_unlock() is called. The
40373 ** call to pager_unlock() will discard all in-memory pages, unlock
40374 ** the database file and move the pager back to OPEN state. If this
40375 ** means that there is a hot-journal left in the file-system, the next
40376 ** connection to obtain a shared lock on the pager (which may be this one)
40377 ** will roll it back.
40379 ** If the pager has not already entered the ERROR state, but an IO or
40380 ** malloc error occurs during a rollback, then this will itself cause
40381 ** the pager to enter the ERROR state. Which will be cleared by the
40382 ** call to pager_unlock(), as described above.
40384 static void pagerUnlockAndRollback(Pager *pPager){
40385 if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
40386 assert( assert_pager_state(pPager) );
40387 if( pPager->eState>=PAGER_WRITER_LOCKED ){
40388 sqlite3BeginBenignMalloc();
40389 sqlite3PagerRollback(pPager);
40390 sqlite3EndBenignMalloc();
40391 }else if( !pPager->exclusiveMode ){
40392 assert( pPager->eState==PAGER_READER );
40393 pager_end_transaction(pPager, 0, 0);
40396 pager_unlock(pPager);
40400 ** Parameter aData must point to a buffer of pPager->pageSize bytes
40401 ** of data. Compute and return a checksum based ont the contents of the
40402 ** page of data and the current value of pPager->cksumInit.
40404 ** This is not a real checksum. It is really just the sum of the
40405 ** random initial value (pPager->cksumInit) and every 200th byte
40406 ** of the page data, starting with byte offset (pPager->pageSize%200).
40407 ** Each byte is interpreted as an 8-bit unsigned integer.
40409 ** Changing the formula used to compute this checksum results in an
40410 ** incompatible journal file format.
40412 ** If journal corruption occurs due to a power failure, the most likely
40413 ** scenario is that one end or the other of the record will be changed.
40414 ** It is much less likely that the two ends of the journal record will be
40415 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
40416 ** though fast and simple, catches the mostly likely kind of corruption.
40418 static u32 pager_cksum(Pager *pPager, const u8 *aData){
40419 u32 cksum = pPager->cksumInit; /* Checksum value to return */
40420 int i = pPager->pageSize-200; /* Loop counter */
40421 while( i>0 ){
40422 cksum += aData[i];
40423 i -= 200;
40425 return cksum;
40429 ** Report the current page size and number of reserved bytes back
40430 ** to the codec.
40432 #ifdef SQLITE_HAS_CODEC
40433 static void pagerReportSize(Pager *pPager){
40434 if( pPager->xCodecSizeChng ){
40435 pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
40436 (int)pPager->nReserve);
40439 #else
40440 # define pagerReportSize(X) /* No-op if we do not support a codec */
40441 #endif
40444 ** Read a single page from either the journal file (if isMainJrnl==1) or
40445 ** from the sub-journal (if isMainJrnl==0) and playback that page.
40446 ** The page begins at offset *pOffset into the file. The *pOffset
40447 ** value is increased to the start of the next page in the journal.
40449 ** The main rollback journal uses checksums - the statement journal does
40450 ** not.
40452 ** If the page number of the page record read from the (sub-)journal file
40453 ** is greater than the current value of Pager.dbSize, then playback is
40454 ** skipped and SQLITE_OK is returned.
40456 ** If pDone is not NULL, then it is a record of pages that have already
40457 ** been played back. If the page at *pOffset has already been played back
40458 ** (if the corresponding pDone bit is set) then skip the playback.
40459 ** Make sure the pDone bit corresponding to the *pOffset page is set
40460 ** prior to returning.
40462 ** If the page record is successfully read from the (sub-)journal file
40463 ** and played back, then SQLITE_OK is returned. If an IO error occurs
40464 ** while reading the record from the (sub-)journal file or while writing
40465 ** to the database file, then the IO error code is returned. If data
40466 ** is successfully read from the (sub-)journal file but appears to be
40467 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
40468 ** two circumstances:
40470 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
40471 ** * If the record is being rolled back from the main journal file
40472 ** and the checksum field does not match the record content.
40474 ** Neither of these two scenarios are possible during a savepoint rollback.
40476 ** If this is a savepoint rollback, then memory may have to be dynamically
40477 ** allocated by this function. If this is the case and an allocation fails,
40478 ** SQLITE_NOMEM is returned.
40480 static int pager_playback_one_page(
40481 Pager *pPager, /* The pager being played back */
40482 i64 *pOffset, /* Offset of record to playback */
40483 Bitvec *pDone, /* Bitvec of pages already played back */
40484 int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
40485 int isSavepnt /* True for a savepoint rollback */
40487 int rc;
40488 PgHdr *pPg; /* An existing page in the cache */
40489 Pgno pgno; /* The page number of a page in journal */
40490 u32 cksum; /* Checksum used for sanity checking */
40491 char *aData; /* Temporary storage for the page */
40492 sqlite3_file *jfd; /* The file descriptor for the journal file */
40493 int isSynced; /* True if journal page is synced */
40495 assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
40496 assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
40497 assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
40498 assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
40500 aData = pPager->pTmpSpace;
40501 assert( aData ); /* Temp storage must have already been allocated */
40502 assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
40504 /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
40505 ** or savepoint rollback done at the request of the caller) or this is
40506 ** a hot-journal rollback. If it is a hot-journal rollback, the pager
40507 ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
40508 ** only reads from the main journal, not the sub-journal.
40510 assert( pPager->eState>=PAGER_WRITER_CACHEMOD
40511 || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
40513 assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
40515 /* Read the page number and page data from the journal or sub-journal
40516 ** file. Return an error code to the caller if an IO error occurs.
40518 jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
40519 rc = read32bits(jfd, *pOffset, &pgno);
40520 if( rc!=SQLITE_OK ) return rc;
40521 rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
40522 if( rc!=SQLITE_OK ) return rc;
40523 *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
40525 /* Sanity checking on the page. This is more important that I originally
40526 ** thought. If a power failure occurs while the journal is being written,
40527 ** it could cause invalid data to be written into the journal. We need to
40528 ** detect this invalid data (with high probability) and ignore it.
40530 if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
40531 assert( !isSavepnt );
40532 return SQLITE_DONE;
40534 if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
40535 return SQLITE_OK;
40537 if( isMainJrnl ){
40538 rc = read32bits(jfd, (*pOffset)-4, &cksum);
40539 if( rc ) return rc;
40540 if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
40541 return SQLITE_DONE;
40545 /* If this page has already been played by before during the current
40546 ** rollback, then don't bother to play it back again.
40548 if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
40549 return rc;
40552 /* When playing back page 1, restore the nReserve setting
40554 if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
40555 pPager->nReserve = ((u8*)aData)[20];
40556 pagerReportSize(pPager);
40559 /* If the pager is in CACHEMOD state, then there must be a copy of this
40560 ** page in the pager cache. In this case just update the pager cache,
40561 ** not the database file. The page is left marked dirty in this case.
40563 ** An exception to the above rule: If the database is in no-sync mode
40564 ** and a page is moved during an incremental vacuum then the page may
40565 ** not be in the pager cache. Later: if a malloc() or IO error occurs
40566 ** during a Movepage() call, then the page may not be in the cache
40567 ** either. So the condition described in the above paragraph is not
40568 ** assert()able.
40570 ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
40571 ** pager cache if it exists and the main file. The page is then marked
40572 ** not dirty. Since this code is only executed in PAGER_OPEN state for
40573 ** a hot-journal rollback, it is guaranteed that the page-cache is empty
40574 ** if the pager is in OPEN state.
40576 ** Ticket #1171: The statement journal might contain page content that is
40577 ** different from the page content at the start of the transaction.
40578 ** This occurs when a page is changed prior to the start of a statement
40579 ** then changed again within the statement. When rolling back such a
40580 ** statement we must not write to the original database unless we know
40581 ** for certain that original page contents are synced into the main rollback
40582 ** journal. Otherwise, a power loss might leave modified data in the
40583 ** database file without an entry in the rollback journal that can
40584 ** restore the database to its original form. Two conditions must be
40585 ** met before writing to the database files. (1) the database must be
40586 ** locked. (2) we know that the original page content is fully synced
40587 ** in the main journal either because the page is not in cache or else
40588 ** the page is marked as needSync==0.
40590 ** 2008-04-14: When attempting to vacuum a corrupt database file, it
40591 ** is possible to fail a statement on a database that does not yet exist.
40592 ** Do not attempt to write if database file has never been opened.
40594 if( pagerUseWal(pPager) ){
40595 pPg = 0;
40596 }else{
40597 pPg = pager_lookup(pPager, pgno);
40599 assert( pPg || !MEMDB );
40600 assert( pPager->eState!=PAGER_OPEN || pPg==0 );
40601 PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
40602 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
40603 (isMainJrnl?"main-journal":"sub-journal")
40605 if( isMainJrnl ){
40606 isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
40607 }else{
40608 isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
40610 if( isOpen(pPager->fd)
40611 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40612 && isSynced
40614 i64 ofst = (pgno-1)*(i64)pPager->pageSize;
40615 testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
40616 assert( !pagerUseWal(pPager) );
40617 rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
40618 if( pgno>pPager->dbFileSize ){
40619 pPager->dbFileSize = pgno;
40621 if( pPager->pBackup ){
40622 CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
40623 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
40624 CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
40626 }else if( !isMainJrnl && pPg==0 ){
40627 /* If this is a rollback of a savepoint and data was not written to
40628 ** the database and the page is not in-memory, there is a potential
40629 ** problem. When the page is next fetched by the b-tree layer, it
40630 ** will be read from the database file, which may or may not be
40631 ** current.
40633 ** There are a couple of different ways this can happen. All are quite
40634 ** obscure. When running in synchronous mode, this can only happen
40635 ** if the page is on the free-list at the start of the transaction, then
40636 ** populated, then moved using sqlite3PagerMovepage().
40638 ** The solution is to add an in-memory page to the cache containing
40639 ** the data just read from the sub-journal. Mark the page as dirty
40640 ** and if the pager requires a journal-sync, then mark the page as
40641 ** requiring a journal-sync before it is written.
40643 assert( isSavepnt );
40644 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
40645 pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
40646 rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
40647 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
40648 pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
40649 if( rc!=SQLITE_OK ) return rc;
40650 pPg->flags &= ~PGHDR_NEED_READ;
40651 sqlite3PcacheMakeDirty(pPg);
40653 if( pPg ){
40654 /* No page should ever be explicitly rolled back that is in use, except
40655 ** for page 1 which is held in use in order to keep the lock on the
40656 ** database active. However such a page may be rolled back as a result
40657 ** of an internal error resulting in an automatic call to
40658 ** sqlite3PagerRollback().
40660 void *pData;
40661 pData = pPg->pData;
40662 memcpy(pData, (u8*)aData, pPager->pageSize);
40663 pPager->xReiniter(pPg);
40664 if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
40665 /* If the contents of this page were just restored from the main
40666 ** journal file, then its content must be as they were when the
40667 ** transaction was first opened. In this case we can mark the page
40668 ** as clean, since there will be no need to write it out to the
40669 ** database.
40671 ** There is one exception to this rule. If the page is being rolled
40672 ** back as part of a savepoint (or statement) rollback from an
40673 ** unsynced portion of the main journal file, then it is not safe
40674 ** to mark the page as clean. This is because marking the page as
40675 ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
40676 ** already in the journal file (recorded in Pager.pInJournal) and
40677 ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
40678 ** again within this transaction, it will be marked as dirty but
40679 ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
40680 ** be written out into the database file before its journal file
40681 ** segment is synced. If a crash occurs during or following this,
40682 ** database corruption may ensue.
40684 assert( !pagerUseWal(pPager) );
40685 sqlite3PcacheMakeClean(pPg);
40687 pager_set_pagehash(pPg);
40689 /* If this was page 1, then restore the value of Pager.dbFileVers.
40690 ** Do this before any decoding. */
40691 if( pgno==1 ){
40692 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
40695 /* Decode the page just read from disk */
40696 CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
40697 sqlite3PcacheRelease(pPg);
40699 return rc;
40703 ** Parameter zMaster is the name of a master journal file. A single journal
40704 ** file that referred to the master journal file has just been rolled back.
40705 ** This routine checks if it is possible to delete the master journal file,
40706 ** and does so if it is.
40708 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
40709 ** available for use within this function.
40711 ** When a master journal file is created, it is populated with the names
40712 ** of all of its child journals, one after another, formatted as utf-8
40713 ** encoded text. The end of each child journal file is marked with a
40714 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
40715 ** file for a transaction involving two databases might be:
40717 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
40719 ** A master journal file may only be deleted once all of its child
40720 ** journals have been rolled back.
40722 ** This function reads the contents of the master-journal file into
40723 ** memory and loops through each of the child journal names. For
40724 ** each child journal, it checks if:
40726 ** * if the child journal exists, and if so
40727 ** * if the child journal contains a reference to master journal
40728 ** file zMaster
40730 ** If a child journal can be found that matches both of the criteria
40731 ** above, this function returns without doing anything. Otherwise, if
40732 ** no such child journal can be found, file zMaster is deleted from
40733 ** the file-system using sqlite3OsDelete().
40735 ** If an IO error within this function, an error code is returned. This
40736 ** function allocates memory by calling sqlite3Malloc(). If an allocation
40737 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
40738 ** occur, SQLITE_OK is returned.
40740 ** TODO: This function allocates a single block of memory to load
40741 ** the entire contents of the master journal file. This could be
40742 ** a couple of kilobytes or so - potentially larger than the page
40743 ** size.
40745 static int pager_delmaster(Pager *pPager, const char *zMaster){
40746 sqlite3_vfs *pVfs = pPager->pVfs;
40747 int rc; /* Return code */
40748 sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
40749 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
40750 char *zMasterJournal = 0; /* Contents of master journal file */
40751 i64 nMasterJournal; /* Size of master journal file */
40752 char *zJournal; /* Pointer to one journal within MJ file */
40753 char *zMasterPtr; /* Space to hold MJ filename from a journal file */
40754 int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
40756 /* Allocate space for both the pJournal and pMaster file descriptors.
40757 ** If successful, open the master journal file for reading.
40759 pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
40760 pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
40761 if( !pMaster ){
40762 rc = SQLITE_NOMEM;
40763 }else{
40764 const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
40765 rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
40767 if( rc!=SQLITE_OK ) goto delmaster_out;
40769 /* Load the entire master journal file into space obtained from
40770 ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
40771 ** sufficient space (in zMasterPtr) to hold the names of master
40772 ** journal files extracted from regular rollback-journals.
40774 rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
40775 if( rc!=SQLITE_OK ) goto delmaster_out;
40776 nMasterPtr = pVfs->mxPathname+1;
40777 zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
40778 if( !zMasterJournal ){
40779 rc = SQLITE_NOMEM;
40780 goto delmaster_out;
40782 zMasterPtr = &zMasterJournal[nMasterJournal+1];
40783 rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
40784 if( rc!=SQLITE_OK ) goto delmaster_out;
40785 zMasterJournal[nMasterJournal] = 0;
40787 zJournal = zMasterJournal;
40788 while( (zJournal-zMasterJournal)<nMasterJournal ){
40789 int exists;
40790 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
40791 if( rc!=SQLITE_OK ){
40792 goto delmaster_out;
40794 if( exists ){
40795 /* One of the journals pointed to by the master journal exists.
40796 ** Open it and check if it points at the master journal. If
40797 ** so, return without deleting the master journal file.
40799 int c;
40800 int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
40801 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
40802 if( rc!=SQLITE_OK ){
40803 goto delmaster_out;
40806 rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
40807 sqlite3OsClose(pJournal);
40808 if( rc!=SQLITE_OK ){
40809 goto delmaster_out;
40812 c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
40813 if( c ){
40814 /* We have a match. Do not delete the master journal file. */
40815 goto delmaster_out;
40818 zJournal += (sqlite3Strlen30(zJournal)+1);
40821 sqlite3OsClose(pMaster);
40822 rc = sqlite3OsDelete(pVfs, zMaster, 0);
40824 delmaster_out:
40825 sqlite3_free(zMasterJournal);
40826 if( pMaster ){
40827 sqlite3OsClose(pMaster);
40828 assert( !isOpen(pJournal) );
40829 sqlite3_free(pMaster);
40831 return rc;
40836 ** This function is used to change the actual size of the database
40837 ** file in the file-system. This only happens when committing a transaction,
40838 ** or rolling back a transaction (including rolling back a hot-journal).
40840 ** If the main database file is not open, or the pager is not in either
40841 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
40842 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
40843 ** If the file on disk is currently larger than nPage pages, then use the VFS
40844 ** xTruncate() method to truncate it.
40846 ** Or, it might might be the case that the file on disk is smaller than
40847 ** nPage pages. Some operating system implementations can get confused if
40848 ** you try to truncate a file to some size that is larger than it
40849 ** currently is, so detect this case and write a single zero byte to
40850 ** the end of the new file instead.
40852 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
40853 ** the database file, return the error code to the caller.
40855 static int pager_truncate(Pager *pPager, Pgno nPage){
40856 int rc = SQLITE_OK;
40857 assert( pPager->eState!=PAGER_ERROR );
40858 assert( pPager->eState!=PAGER_READER );
40860 if( isOpen(pPager->fd)
40861 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40863 i64 currentSize, newSize;
40864 int szPage = pPager->pageSize;
40865 assert( pPager->eLock==EXCLUSIVE_LOCK );
40866 /* TODO: Is it safe to use Pager.dbFileSize here? */
40867 rc = sqlite3OsFileSize(pPager->fd, &currentSize);
40868 newSize = szPage*(i64)nPage;
40869 if( rc==SQLITE_OK && currentSize!=newSize ){
40870 if( currentSize>newSize ){
40871 rc = sqlite3OsTruncate(pPager->fd, newSize);
40872 }else if( (currentSize+szPage)<=newSize ){
40873 char *pTmp = pPager->pTmpSpace;
40874 memset(pTmp, 0, szPage);
40875 testcase( (newSize-szPage) == currentSize );
40876 testcase( (newSize-szPage) > currentSize );
40877 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
40879 if( rc==SQLITE_OK ){
40880 pPager->dbFileSize = nPage;
40884 return rc;
40888 ** Return a sanitized version of the sector-size of OS file pFile. The
40889 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
40891 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
40892 int iRet = sqlite3OsSectorSize(pFile);
40893 if( iRet<32 ){
40894 iRet = 512;
40895 }else if( iRet>MAX_SECTOR_SIZE ){
40896 assert( MAX_SECTOR_SIZE>=512 );
40897 iRet = MAX_SECTOR_SIZE;
40899 return iRet;
40903 ** Set the value of the Pager.sectorSize variable for the given
40904 ** pager based on the value returned by the xSectorSize method
40905 ** of the open database file. The sector size will be used used
40906 ** to determine the size and alignment of journal header and
40907 ** master journal pointers within created journal files.
40909 ** For temporary files the effective sector size is always 512 bytes.
40911 ** Otherwise, for non-temporary files, the effective sector size is
40912 ** the value returned by the xSectorSize() method rounded up to 32 if
40913 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
40914 ** is greater than MAX_SECTOR_SIZE.
40916 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
40917 ** the effective sector size to its minimum value (512). The purpose of
40918 ** pPager->sectorSize is to define the "blast radius" of bytes that
40919 ** might change if a crash occurs while writing to a single byte in
40920 ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
40921 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
40922 ** size. For backwards compatibility of the rollback journal file format,
40923 ** we cannot reduce the effective sector size below 512.
40925 static void setSectorSize(Pager *pPager){
40926 assert( isOpen(pPager->fd) || pPager->tempFile );
40928 if( pPager->tempFile
40929 || (sqlite3OsDeviceCharacteristics(pPager->fd) &
40930 SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
40932 /* Sector size doesn't matter for temporary files. Also, the file
40933 ** may not have been opened yet, in which case the OsSectorSize()
40934 ** call will segfault. */
40935 pPager->sectorSize = 512;
40936 }else{
40937 pPager->sectorSize = sqlite3SectorSize(pPager->fd);
40942 ** Playback the journal and thus restore the database file to
40943 ** the state it was in before we started making changes.
40945 ** The journal file format is as follows:
40947 ** (1) 8 byte prefix. A copy of aJournalMagic[].
40948 ** (2) 4 byte big-endian integer which is the number of valid page records
40949 ** in the journal. If this value is 0xffffffff, then compute the
40950 ** number of page records from the journal size.
40951 ** (3) 4 byte big-endian integer which is the initial value for the
40952 ** sanity checksum.
40953 ** (4) 4 byte integer which is the number of pages to truncate the
40954 ** database to during a rollback.
40955 ** (5) 4 byte big-endian integer which is the sector size. The header
40956 ** is this many bytes in size.
40957 ** (6) 4 byte big-endian integer which is the page size.
40958 ** (7) zero padding out to the next sector size.
40959 ** (8) Zero or more pages instances, each as follows:
40960 ** + 4 byte page number.
40961 ** + pPager->pageSize bytes of data.
40962 ** + 4 byte checksum
40964 ** When we speak of the journal header, we mean the first 7 items above.
40965 ** Each entry in the journal is an instance of the 8th item.
40967 ** Call the value from the second bullet "nRec". nRec is the number of
40968 ** valid page entries in the journal. In most cases, you can compute the
40969 ** value of nRec from the size of the journal file. But if a power
40970 ** failure occurred while the journal was being written, it could be the
40971 ** case that the size of the journal file had already been increased but
40972 ** the extra entries had not yet made it safely to disk. In such a case,
40973 ** the value of nRec computed from the file size would be too large. For
40974 ** that reason, we always use the nRec value in the header.
40976 ** If the nRec value is 0xffffffff it means that nRec should be computed
40977 ** from the file size. This value is used when the user selects the
40978 ** no-sync option for the journal. A power failure could lead to corruption
40979 ** in this case. But for things like temporary table (which will be
40980 ** deleted when the power is restored) we don't care.
40982 ** If the file opened as the journal file is not a well-formed
40983 ** journal file then all pages up to the first corrupted page are rolled
40984 ** back (or no pages if the journal header is corrupted). The journal file
40985 ** is then deleted and SQLITE_OK returned, just as if no corruption had
40986 ** been encountered.
40988 ** If an I/O or malloc() error occurs, the journal-file is not deleted
40989 ** and an error code is returned.
40991 ** The isHot parameter indicates that we are trying to rollback a journal
40992 ** that might be a hot journal. Or, it could be that the journal is
40993 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
40994 ** If the journal really is hot, reset the pager cache prior rolling
40995 ** back any content. If the journal is merely persistent, no reset is
40996 ** needed.
40998 static int pager_playback(Pager *pPager, int isHot){
40999 sqlite3_vfs *pVfs = pPager->pVfs;
41000 i64 szJ; /* Size of the journal file in bytes */
41001 u32 nRec; /* Number of Records in the journal */
41002 u32 u; /* Unsigned loop counter */
41003 Pgno mxPg = 0; /* Size of the original file in pages */
41004 int rc; /* Result code of a subroutine */
41005 int res = 1; /* Value returned by sqlite3OsAccess() */
41006 char *zMaster = 0; /* Name of master journal file if any */
41007 int needPagerReset; /* True to reset page prior to first page rollback */
41008 int nPlayback = 0; /* Total number of pages restored from journal */
41010 /* Figure out how many records are in the journal. Abort early if
41011 ** the journal is empty.
41013 assert( isOpen(pPager->jfd) );
41014 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
41015 if( rc!=SQLITE_OK ){
41016 goto end_playback;
41019 /* Read the master journal name from the journal, if it is present.
41020 ** If a master journal file name is specified, but the file is not
41021 ** present on disk, then the journal is not hot and does not need to be
41022 ** played back.
41024 ** TODO: Technically the following is an error because it assumes that
41025 ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
41026 ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
41027 ** mxPathname is 512, which is the same as the minimum allowable value
41028 ** for pageSize.
41030 zMaster = pPager->pTmpSpace;
41031 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41032 if( rc==SQLITE_OK && zMaster[0] ){
41033 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
41035 zMaster = 0;
41036 if( rc!=SQLITE_OK || !res ){
41037 goto end_playback;
41039 pPager->journalOff = 0;
41040 needPagerReset = isHot;
41042 /* This loop terminates either when a readJournalHdr() or
41043 ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
41044 ** occurs.
41046 while( 1 ){
41047 /* Read the next journal header from the journal file. If there are
41048 ** not enough bytes left in the journal file for a complete header, or
41049 ** it is corrupted, then a process must have failed while writing it.
41050 ** This indicates nothing more needs to be rolled back.
41052 rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
41053 if( rc!=SQLITE_OK ){
41054 if( rc==SQLITE_DONE ){
41055 rc = SQLITE_OK;
41057 goto end_playback;
41060 /* If nRec is 0xffffffff, then this journal was created by a process
41061 ** working in no-sync mode. This means that the rest of the journal
41062 ** file consists of pages, there are no more journal headers. Compute
41063 ** the value of nRec based on this assumption.
41065 if( nRec==0xffffffff ){
41066 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
41067 nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
41070 /* If nRec is 0 and this rollback is of a transaction created by this
41071 ** process and if this is the final header in the journal, then it means
41072 ** that this part of the journal was being filled but has not yet been
41073 ** synced to disk. Compute the number of pages based on the remaining
41074 ** size of the file.
41076 ** The third term of the test was added to fix ticket #2565.
41077 ** When rolling back a hot journal, nRec==0 always means that the next
41078 ** chunk of the journal contains zero pages to be rolled back. But
41079 ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
41080 ** the journal, it means that the journal might contain additional
41081 ** pages that need to be rolled back and that the number of pages
41082 ** should be computed based on the journal file size.
41084 if( nRec==0 && !isHot &&
41085 pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
41086 nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
41089 /* If this is the first header read from the journal, truncate the
41090 ** database file back to its original size.
41092 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
41093 rc = pager_truncate(pPager, mxPg);
41094 if( rc!=SQLITE_OK ){
41095 goto end_playback;
41097 pPager->dbSize = mxPg;
41100 /* Copy original pages out of the journal and back into the
41101 ** database file and/or page cache.
41103 for(u=0; u<nRec; u++){
41104 if( needPagerReset ){
41105 pager_reset(pPager);
41106 needPagerReset = 0;
41108 rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
41109 if( rc==SQLITE_OK ){
41110 nPlayback++;
41111 }else{
41112 if( rc==SQLITE_DONE ){
41113 pPager->journalOff = szJ;
41114 break;
41115 }else if( rc==SQLITE_IOERR_SHORT_READ ){
41116 /* If the journal has been truncated, simply stop reading and
41117 ** processing the journal. This might happen if the journal was
41118 ** not completely written and synced prior to a crash. In that
41119 ** case, the database should have never been written in the
41120 ** first place so it is OK to simply abandon the rollback. */
41121 rc = SQLITE_OK;
41122 goto end_playback;
41123 }else{
41124 /* If we are unable to rollback, quit and return the error
41125 ** code. This will cause the pager to enter the error state
41126 ** so that no further harm will be done. Perhaps the next
41127 ** process to come along will be able to rollback the database.
41129 goto end_playback;
41134 /*NOTREACHED*/
41135 assert( 0 );
41137 end_playback:
41138 /* Following a rollback, the database file should be back in its original
41139 ** state prior to the start of the transaction, so invoke the
41140 ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
41141 ** assertion that the transaction counter was modified.
41143 #ifdef SQLITE_DEBUG
41144 if( pPager->fd->pMethods ){
41145 sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
41147 #endif
41149 /* If this playback is happening automatically as a result of an IO or
41150 ** malloc error that occurred after the change-counter was updated but
41151 ** before the transaction was committed, then the change-counter
41152 ** modification may just have been reverted. If this happens in exclusive
41153 ** mode, then subsequent transactions performed by the connection will not
41154 ** update the change-counter at all. This may lead to cache inconsistency
41155 ** problems for other processes at some point in the future. So, just
41156 ** in case this has happened, clear the changeCountDone flag now.
41158 pPager->changeCountDone = pPager->tempFile;
41160 if( rc==SQLITE_OK ){
41161 zMaster = pPager->pTmpSpace;
41162 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41163 testcase( rc!=SQLITE_OK );
41165 if( rc==SQLITE_OK
41166 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41168 rc = sqlite3PagerSync(pPager);
41170 if( rc==SQLITE_OK ){
41171 rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
41172 testcase( rc!=SQLITE_OK );
41174 if( rc==SQLITE_OK && zMaster[0] && res ){
41175 /* If there was a master journal and this routine will return success,
41176 ** see if it is possible to delete the master journal.
41178 rc = pager_delmaster(pPager, zMaster);
41179 testcase( rc!=SQLITE_OK );
41181 if( isHot && nPlayback ){
41182 sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
41183 nPlayback, pPager->zJournal);
41186 /* The Pager.sectorSize variable may have been updated while rolling
41187 ** back a journal created by a process with a different sector size
41188 ** value. Reset it to the correct value for this process.
41190 setSectorSize(pPager);
41191 return rc;
41196 ** Read the content for page pPg out of the database file and into
41197 ** pPg->pData. A shared lock or greater must be held on the database
41198 ** file before this function is called.
41200 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
41201 ** the value read from the database file.
41203 ** If an IO error occurs, then the IO error is returned to the caller.
41204 ** Otherwise, SQLITE_OK is returned.
41206 static int readDbPage(PgHdr *pPg, u32 iFrame){
41207 Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
41208 Pgno pgno = pPg->pgno; /* Page number to read */
41209 int rc = SQLITE_OK; /* Return code */
41210 int pgsz = pPager->pageSize; /* Number of bytes to read */
41212 assert( pPager->eState>=PAGER_READER && !MEMDB );
41213 assert( isOpen(pPager->fd) );
41215 #ifndef SQLITE_OMIT_WAL
41216 if( iFrame ){
41217 /* Try to pull the page from the write-ahead log. */
41218 rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
41219 }else
41220 #endif
41222 i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
41223 rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
41224 if( rc==SQLITE_IOERR_SHORT_READ ){
41225 rc = SQLITE_OK;
41229 if( pgno==1 ){
41230 if( rc ){
41231 /* If the read is unsuccessful, set the dbFileVers[] to something
41232 ** that will never be a valid file version. dbFileVers[] is a copy
41233 ** of bytes 24..39 of the database. Bytes 28..31 should always be
41234 ** zero or the size of the database in page. Bytes 32..35 and 35..39
41235 ** should be page numbers which are never 0xffffffff. So filling
41236 ** pPager->dbFileVers[] with all 0xff bytes should suffice.
41238 ** For an encrypted database, the situation is more complex: bytes
41239 ** 24..39 of the database are white noise. But the probability of
41240 ** white noising equaling 16 bytes of 0xff is vanishingly small so
41241 ** we should still be ok.
41243 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
41244 }else{
41245 u8 *dbFileVers = &((u8*)pPg->pData)[24];
41246 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
41249 CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
41251 PAGER_INCR(sqlite3_pager_readdb_count);
41252 PAGER_INCR(pPager->nRead);
41253 IOTRACE(("PGIN %p %d\n", pPager, pgno));
41254 PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
41255 PAGERID(pPager), pgno, pager_pagehash(pPg)));
41257 return rc;
41261 ** Update the value of the change-counter at offsets 24 and 92 in
41262 ** the header and the sqlite version number at offset 96.
41264 ** This is an unconditional update. See also the pager_incr_changecounter()
41265 ** routine which only updates the change-counter if the update is actually
41266 ** needed, as determined by the pPager->changeCountDone state variable.
41268 static void pager_write_changecounter(PgHdr *pPg){
41269 u32 change_counter;
41271 /* Increment the value just read and write it back to byte 24. */
41272 change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
41273 put32bits(((char*)pPg->pData)+24, change_counter);
41275 /* Also store the SQLite version number in bytes 96..99 and in
41276 ** bytes 92..95 store the change counter for which the version number
41277 ** is valid. */
41278 put32bits(((char*)pPg->pData)+92, change_counter);
41279 put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
41282 #ifndef SQLITE_OMIT_WAL
41284 ** This function is invoked once for each page that has already been
41285 ** written into the log file when a WAL transaction is rolled back.
41286 ** Parameter iPg is the page number of said page. The pCtx argument
41287 ** is actually a pointer to the Pager structure.
41289 ** If page iPg is present in the cache, and has no outstanding references,
41290 ** it is discarded. Otherwise, if there are one or more outstanding
41291 ** references, the page content is reloaded from the database. If the
41292 ** attempt to reload content from the database is required and fails,
41293 ** return an SQLite error code. Otherwise, SQLITE_OK.
41295 static int pagerUndoCallback(void *pCtx, Pgno iPg){
41296 int rc = SQLITE_OK;
41297 Pager *pPager = (Pager *)pCtx;
41298 PgHdr *pPg;
41300 assert( pagerUseWal(pPager) );
41301 pPg = sqlite3PagerLookup(pPager, iPg);
41302 if( pPg ){
41303 if( sqlite3PcachePageRefcount(pPg)==1 ){
41304 sqlite3PcacheDrop(pPg);
41305 }else{
41306 u32 iFrame = 0;
41307 rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
41308 if( rc==SQLITE_OK ){
41309 rc = readDbPage(pPg, iFrame);
41311 if( rc==SQLITE_OK ){
41312 pPager->xReiniter(pPg);
41314 sqlite3PagerUnref(pPg);
41318 /* Normally, if a transaction is rolled back, any backup processes are
41319 ** updated as data is copied out of the rollback journal and into the
41320 ** database. This is not generally possible with a WAL database, as
41321 ** rollback involves simply truncating the log file. Therefore, if one
41322 ** or more frames have already been written to the log (and therefore
41323 ** also copied into the backup databases) as part of this transaction,
41324 ** the backups must be restarted.
41326 sqlite3BackupRestart(pPager->pBackup);
41328 return rc;
41332 ** This function is called to rollback a transaction on a WAL database.
41334 static int pagerRollbackWal(Pager *pPager){
41335 int rc; /* Return Code */
41336 PgHdr *pList; /* List of dirty pages to revert */
41338 /* For all pages in the cache that are currently dirty or have already
41339 ** been written (but not committed) to the log file, do one of the
41340 ** following:
41342 ** + Discard the cached page (if refcount==0), or
41343 ** + Reload page content from the database (if refcount>0).
41345 pPager->dbSize = pPager->dbOrigSize;
41346 rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
41347 pList = sqlite3PcacheDirtyList(pPager->pPCache);
41348 while( pList && rc==SQLITE_OK ){
41349 PgHdr *pNext = pList->pDirty;
41350 rc = pagerUndoCallback((void *)pPager, pList->pgno);
41351 pList = pNext;
41354 return rc;
41358 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
41359 ** the contents of the list of pages headed by pList (connected by pDirty),
41360 ** this function notifies any active backup processes that the pages have
41361 ** changed.
41363 ** The list of pages passed into this routine is always sorted by page number.
41364 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
41366 static int pagerWalFrames(
41367 Pager *pPager, /* Pager object */
41368 PgHdr *pList, /* List of frames to log */
41369 Pgno nTruncate, /* Database size after this commit */
41370 int isCommit /* True if this is a commit */
41372 int rc; /* Return code */
41373 int nList; /* Number of pages in pList */
41374 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
41375 PgHdr *p; /* For looping over pages */
41376 #endif
41378 assert( pPager->pWal );
41379 assert( pList );
41380 #ifdef SQLITE_DEBUG
41381 /* Verify that the page list is in accending order */
41382 for(p=pList; p && p->pDirty; p=p->pDirty){
41383 assert( p->pgno < p->pDirty->pgno );
41385 #endif
41387 assert( pList->pDirty==0 || isCommit );
41388 if( isCommit ){
41389 /* If a WAL transaction is being committed, there is no point in writing
41390 ** any pages with page numbers greater than nTruncate into the WAL file.
41391 ** They will never be read by any client. So remove them from the pDirty
41392 ** list here. */
41393 PgHdr *p;
41394 PgHdr **ppNext = &pList;
41395 nList = 0;
41396 for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
41397 if( p->pgno<=nTruncate ){
41398 ppNext = &p->pDirty;
41399 nList++;
41402 assert( pList );
41403 }else{
41404 nList = 1;
41406 pPager->aStat[PAGER_STAT_WRITE] += nList;
41408 if( pList->pgno==1 ) pager_write_changecounter(pList);
41409 rc = sqlite3WalFrames(pPager->pWal,
41410 pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
41412 if( rc==SQLITE_OK && pPager->pBackup ){
41413 PgHdr *p;
41414 for(p=pList; p; p=p->pDirty){
41415 sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
41419 #ifdef SQLITE_CHECK_PAGES
41420 pList = sqlite3PcacheDirtyList(pPager->pPCache);
41421 for(p=pList; p; p=p->pDirty){
41422 pager_set_pagehash(p);
41424 #endif
41426 return rc;
41430 ** Begin a read transaction on the WAL.
41432 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
41433 ** makes a snapshot of the database at the current point in time and preserves
41434 ** that snapshot for use by the reader in spite of concurrently changes by
41435 ** other writers or checkpointers.
41437 static int pagerBeginReadTransaction(Pager *pPager){
41438 int rc; /* Return code */
41439 int changed = 0; /* True if cache must be reset */
41441 assert( pagerUseWal(pPager) );
41442 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41444 /* sqlite3WalEndReadTransaction() was not called for the previous
41445 ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
41446 ** are in locking_mode=NORMAL and EndRead() was previously called,
41447 ** the duplicate call is harmless.
41449 sqlite3WalEndReadTransaction(pPager->pWal);
41451 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
41452 if( rc!=SQLITE_OK || changed ){
41453 pager_reset(pPager);
41454 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
41457 return rc;
41459 #endif
41462 ** This function is called as part of the transition from PAGER_OPEN
41463 ** to PAGER_READER state to determine the size of the database file
41464 ** in pages (assuming the page size currently stored in Pager.pageSize).
41466 ** If no error occurs, SQLITE_OK is returned and the size of the database
41467 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
41468 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
41470 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
41471 Pgno nPage; /* Value to return via *pnPage */
41473 /* Query the WAL sub-system for the database size. The WalDbsize()
41474 ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
41475 ** if the database size is not available. The database size is not
41476 ** available from the WAL sub-system if the log file is empty or
41477 ** contains no valid committed transactions.
41479 assert( pPager->eState==PAGER_OPEN );
41480 assert( pPager->eLock>=SHARED_LOCK );
41481 nPage = sqlite3WalDbsize(pPager->pWal);
41483 /* If the database size was not available from the WAL sub-system,
41484 ** determine it based on the size of the database file. If the size
41485 ** of the database file is not an integer multiple of the page-size,
41486 ** round down to the nearest page. Except, any file larger than 0
41487 ** bytes in size is considered to contain at least one page.
41489 if( nPage==0 ){
41490 i64 n = 0; /* Size of db file in bytes */
41491 assert( isOpen(pPager->fd) || pPager->tempFile );
41492 if( isOpen(pPager->fd) ){
41493 int rc = sqlite3OsFileSize(pPager->fd, &n);
41494 if( rc!=SQLITE_OK ){
41495 return rc;
41498 nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
41501 /* If the current number of pages in the file is greater than the
41502 ** configured maximum pager number, increase the allowed limit so
41503 ** that the file can be read.
41505 if( nPage>pPager->mxPgno ){
41506 pPager->mxPgno = (Pgno)nPage;
41509 *pnPage = nPage;
41510 return SQLITE_OK;
41513 #ifndef SQLITE_OMIT_WAL
41515 ** Check if the *-wal file that corresponds to the database opened by pPager
41516 ** exists if the database is not empy, or verify that the *-wal file does
41517 ** not exist (by deleting it) if the database file is empty.
41519 ** If the database is not empty and the *-wal file exists, open the pager
41520 ** in WAL mode. If the database is empty or if no *-wal file exists and
41521 ** if no error occurs, make sure Pager.journalMode is not set to
41522 ** PAGER_JOURNALMODE_WAL.
41524 ** Return SQLITE_OK or an error code.
41526 ** The caller must hold a SHARED lock on the database file to call this
41527 ** function. Because an EXCLUSIVE lock on the db file is required to delete
41528 ** a WAL on a none-empty database, this ensures there is no race condition
41529 ** between the xAccess() below and an xDelete() being executed by some
41530 ** other connection.
41532 static int pagerOpenWalIfPresent(Pager *pPager){
41533 int rc = SQLITE_OK;
41534 assert( pPager->eState==PAGER_OPEN );
41535 assert( pPager->eLock>=SHARED_LOCK );
41537 if( !pPager->tempFile ){
41538 int isWal; /* True if WAL file exists */
41539 Pgno nPage; /* Size of the database file */
41541 rc = pagerPagecount(pPager, &nPage);
41542 if( rc ) return rc;
41543 if( nPage==0 ){
41544 rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
41545 if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
41546 isWal = 0;
41547 }else{
41548 rc = sqlite3OsAccess(
41549 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
41552 if( rc==SQLITE_OK ){
41553 if( isWal ){
41554 testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
41555 rc = sqlite3PagerOpenWal(pPager, 0);
41556 }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
41557 pPager->journalMode = PAGER_JOURNALMODE_DELETE;
41561 return rc;
41563 #endif
41566 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
41567 ** the entire master journal file. The case pSavepoint==NULL occurs when
41568 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
41569 ** savepoint.
41571 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
41572 ** being rolled back), then the rollback consists of up to three stages,
41573 ** performed in the order specified:
41575 ** * Pages are played back from the main journal starting at byte
41576 ** offset PagerSavepoint.iOffset and continuing to
41577 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
41578 ** file if PagerSavepoint.iHdrOffset is zero.
41580 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
41581 ** back starting from the journal header immediately following
41582 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
41584 ** * Pages are then played back from the sub-journal file, starting
41585 ** with the PagerSavepoint.iSubRec and continuing to the end of
41586 ** the journal file.
41588 ** Throughout the rollback process, each time a page is rolled back, the
41589 ** corresponding bit is set in a bitvec structure (variable pDone in the
41590 ** implementation below). This is used to ensure that a page is only
41591 ** rolled back the first time it is encountered in either journal.
41593 ** If pSavepoint is NULL, then pages are only played back from the main
41594 ** journal file. There is no need for a bitvec in this case.
41596 ** In either case, before playback commences the Pager.dbSize variable
41597 ** is reset to the value that it held at the start of the savepoint
41598 ** (or transaction). No page with a page-number greater than this value
41599 ** is played back. If one is encountered it is simply skipped.
41601 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
41602 i64 szJ; /* Effective size of the main journal */
41603 i64 iHdrOff; /* End of first segment of main-journal records */
41604 int rc = SQLITE_OK; /* Return code */
41605 Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
41607 assert( pPager->eState!=PAGER_ERROR );
41608 assert( pPager->eState>=PAGER_WRITER_LOCKED );
41610 /* Allocate a bitvec to use to store the set of pages rolled back */
41611 if( pSavepoint ){
41612 pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
41613 if( !pDone ){
41614 return SQLITE_NOMEM;
41618 /* Set the database size back to the value it was before the savepoint
41619 ** being reverted was opened.
41621 pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
41622 pPager->changeCountDone = pPager->tempFile;
41624 if( !pSavepoint && pagerUseWal(pPager) ){
41625 return pagerRollbackWal(pPager);
41628 /* Use pPager->journalOff as the effective size of the main rollback
41629 ** journal. The actual file might be larger than this in
41630 ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
41631 ** past pPager->journalOff is off-limits to us.
41633 szJ = pPager->journalOff;
41634 assert( pagerUseWal(pPager)==0 || szJ==0 );
41636 /* Begin by rolling back records from the main journal starting at
41637 ** PagerSavepoint.iOffset and continuing to the next journal header.
41638 ** There might be records in the main journal that have a page number
41639 ** greater than the current database size (pPager->dbSize) but those
41640 ** will be skipped automatically. Pages are added to pDone as they
41641 ** are played back.
41643 if( pSavepoint && !pagerUseWal(pPager) ){
41644 iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
41645 pPager->journalOff = pSavepoint->iOffset;
41646 while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
41647 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
41649 assert( rc!=SQLITE_DONE );
41650 }else{
41651 pPager->journalOff = 0;
41654 /* Continue rolling back records out of the main journal starting at
41655 ** the first journal header seen and continuing until the effective end
41656 ** of the main journal file. Continue to skip out-of-range pages and
41657 ** continue adding pages rolled back to pDone.
41659 while( rc==SQLITE_OK && pPager->journalOff<szJ ){
41660 u32 ii; /* Loop counter */
41661 u32 nJRec = 0; /* Number of Journal Records */
41662 u32 dummy;
41663 rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
41664 assert( rc!=SQLITE_DONE );
41667 ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
41668 ** test is related to ticket #2565. See the discussion in the
41669 ** pager_playback() function for additional information.
41671 if( nJRec==0
41672 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
41674 nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
41676 for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
41677 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
41679 assert( rc!=SQLITE_DONE );
41681 assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
41683 /* Finally, rollback pages from the sub-journal. Page that were
41684 ** previously rolled back out of the main journal (and are hence in pDone)
41685 ** will be skipped. Out-of-range pages are also skipped.
41687 if( pSavepoint ){
41688 u32 ii; /* Loop counter */
41689 i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
41691 if( pagerUseWal(pPager) ){
41692 rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
41694 for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
41695 assert( offset==(i64)ii*(4+pPager->pageSize) );
41696 rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
41698 assert( rc!=SQLITE_DONE );
41701 sqlite3BitvecDestroy(pDone);
41702 if( rc==SQLITE_OK ){
41703 pPager->journalOff = szJ;
41706 return rc;
41710 ** Change the maximum number of in-memory pages that are allowed.
41712 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
41713 sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
41717 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
41719 static void pagerFixMaplimit(Pager *pPager){
41720 #if SQLITE_MAX_MMAP_SIZE>0
41721 sqlite3_file *fd = pPager->fd;
41722 if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
41723 sqlite3_int64 sz;
41724 sz = pPager->szMmap;
41725 pPager->bUseFetch = (sz>0);
41726 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
41728 #endif
41732 ** Change the maximum size of any memory mapping made of the database file.
41734 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
41735 pPager->szMmap = szMmap;
41736 pagerFixMaplimit(pPager);
41740 ** Free as much memory as possible from the pager.
41742 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
41743 sqlite3PcacheShrink(pPager->pPCache);
41747 ** Adjust settings of the pager to those specified in the pgFlags parameter.
41749 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
41750 ** of the database to damage due to OS crashes or power failures by
41751 ** changing the number of syncs()s when writing the journals.
41752 ** There are three levels:
41754 ** OFF sqlite3OsSync() is never called. This is the default
41755 ** for temporary and transient files.
41757 ** NORMAL The journal is synced once before writes begin on the
41758 ** database. This is normally adequate protection, but
41759 ** it is theoretically possible, though very unlikely,
41760 ** that an inopertune power failure could leave the journal
41761 ** in a state which would cause damage to the database
41762 ** when it is rolled back.
41764 ** FULL The journal is synced twice before writes begin on the
41765 ** database (with some additional information - the nRec field
41766 ** of the journal header - being written in between the two
41767 ** syncs). If we assume that writing a
41768 ** single disk sector is atomic, then this mode provides
41769 ** assurance that the journal will not be corrupted to the
41770 ** point of causing damage to the database during rollback.
41772 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
41773 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
41774 ** prior to the start of checkpoint and that the database file is synced
41775 ** at the conclusion of the checkpoint if the entire content of the WAL
41776 ** was written back into the database. But no sync operations occur for
41777 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
41778 ** file is synced following each commit operation, in addition to the
41779 ** syncs associated with NORMAL.
41781 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
41782 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
41783 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
41784 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
41785 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
41786 ** synchronous=FULL versus synchronous=NORMAL setting determines when
41787 ** the xSync primitive is called and is relevant to all platforms.
41789 ** Numeric values associated with these states are OFF==1, NORMAL=2,
41790 ** and FULL=3.
41792 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
41793 SQLITE_PRIVATE void sqlite3PagerSetFlags(
41794 Pager *pPager, /* The pager to set safety level for */
41795 unsigned pgFlags /* Various flags */
41797 unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
41798 assert( level>=1 && level<=3 );
41799 pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
41800 pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
41801 if( pPager->noSync ){
41802 pPager->syncFlags = 0;
41803 pPager->ckptSyncFlags = 0;
41804 }else if( pgFlags & PAGER_FULLFSYNC ){
41805 pPager->syncFlags = SQLITE_SYNC_FULL;
41806 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
41807 }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
41808 pPager->syncFlags = SQLITE_SYNC_NORMAL;
41809 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
41810 }else{
41811 pPager->syncFlags = SQLITE_SYNC_NORMAL;
41812 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
41814 pPager->walSyncFlags = pPager->syncFlags;
41815 if( pPager->fullSync ){
41816 pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
41818 if( pgFlags & PAGER_CACHESPILL ){
41819 pPager->doNotSpill &= ~SPILLFLAG_OFF;
41820 }else{
41821 pPager->doNotSpill |= SPILLFLAG_OFF;
41824 #endif
41827 ** The following global variable is incremented whenever the library
41828 ** attempts to open a temporary file. This information is used for
41829 ** testing and analysis only.
41831 #ifdef SQLITE_TEST
41832 SQLITE_API int sqlite3_opentemp_count = 0;
41833 #endif
41836 ** Open a temporary file.
41838 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
41839 ** or some other error code if we fail. The OS will automatically
41840 ** delete the temporary file when it is closed.
41842 ** The flags passed to the VFS layer xOpen() call are those specified
41843 ** by parameter vfsFlags ORed with the following:
41845 ** SQLITE_OPEN_READWRITE
41846 ** SQLITE_OPEN_CREATE
41847 ** SQLITE_OPEN_EXCLUSIVE
41848 ** SQLITE_OPEN_DELETEONCLOSE
41850 static int pagerOpentemp(
41851 Pager *pPager, /* The pager object */
41852 sqlite3_file *pFile, /* Write the file descriptor here */
41853 int vfsFlags /* Flags passed through to the VFS */
41855 int rc; /* Return code */
41857 #ifdef SQLITE_TEST
41858 sqlite3_opentemp_count++; /* Used for testing and analysis only */
41859 #endif
41861 vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
41862 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
41863 rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
41864 assert( rc!=SQLITE_OK || isOpen(pFile) );
41865 return rc;
41869 ** Set the busy handler function.
41871 ** The pager invokes the busy-handler if sqlite3OsLock() returns
41872 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
41873 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
41874 ** lock. It does *not* invoke the busy handler when upgrading from
41875 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
41876 ** (which occurs during hot-journal rollback). Summary:
41878 ** Transition | Invokes xBusyHandler
41879 ** --------------------------------------------------------
41880 ** NO_LOCK -> SHARED_LOCK | Yes
41881 ** SHARED_LOCK -> RESERVED_LOCK | No
41882 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
41883 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
41885 ** If the busy-handler callback returns non-zero, the lock is
41886 ** retried. If it returns zero, then the SQLITE_BUSY error is
41887 ** returned to the caller of the pager API function.
41889 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
41890 Pager *pPager, /* Pager object */
41891 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
41892 void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
41894 pPager->xBusyHandler = xBusyHandler;
41895 pPager->pBusyHandlerArg = pBusyHandlerArg;
41897 if( isOpen(pPager->fd) ){
41898 void **ap = (void **)&pPager->xBusyHandler;
41899 assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
41900 assert( ap[1]==pBusyHandlerArg );
41901 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
41906 ** Change the page size used by the Pager object. The new page size
41907 ** is passed in *pPageSize.
41909 ** If the pager is in the error state when this function is called, it
41910 ** is a no-op. The value returned is the error state error code (i.e.
41911 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
41913 ** Otherwise, if all of the following are true:
41915 ** * the new page size (value of *pPageSize) is valid (a power
41916 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
41918 ** * there are no outstanding page references, and
41920 ** * the database is either not an in-memory database or it is
41921 ** an in-memory database that currently consists of zero pages.
41923 ** then the pager object page size is set to *pPageSize.
41925 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
41926 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
41927 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
41928 ** In all other cases, SQLITE_OK is returned.
41930 ** If the page size is not changed, either because one of the enumerated
41931 ** conditions above is not true, the pager was in error state when this
41932 ** function was called, or because the memory allocation attempt failed,
41933 ** then *pPageSize is set to the old, retained page size before returning.
41935 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
41936 int rc = SQLITE_OK;
41938 /* It is not possible to do a full assert_pager_state() here, as this
41939 ** function may be called from within PagerOpen(), before the state
41940 ** of the Pager object is internally consistent.
41942 ** At one point this function returned an error if the pager was in
41943 ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
41944 ** there is at least one outstanding page reference, this function
41945 ** is a no-op for that case anyhow.
41948 u32 pageSize = *pPageSize;
41949 assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
41950 if( (pPager->memDb==0 || pPager->dbSize==0)
41951 && sqlite3PcacheRefCount(pPager->pPCache)==0
41952 && pageSize && pageSize!=(u32)pPager->pageSize
41954 char *pNew = NULL; /* New temp space */
41955 i64 nByte = 0;
41957 if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
41958 rc = sqlite3OsFileSize(pPager->fd, &nByte);
41960 if( rc==SQLITE_OK ){
41961 pNew = (char *)sqlite3PageMalloc(pageSize);
41962 if( !pNew ) rc = SQLITE_NOMEM;
41965 if( rc==SQLITE_OK ){
41966 pager_reset(pPager);
41967 pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
41968 pPager->pageSize = pageSize;
41969 sqlite3PageFree(pPager->pTmpSpace);
41970 pPager->pTmpSpace = pNew;
41971 sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
41975 *pPageSize = pPager->pageSize;
41976 if( rc==SQLITE_OK ){
41977 if( nReserve<0 ) nReserve = pPager->nReserve;
41978 assert( nReserve>=0 && nReserve<1000 );
41979 pPager->nReserve = (i16)nReserve;
41980 pagerReportSize(pPager);
41981 pagerFixMaplimit(pPager);
41983 return rc;
41987 ** Return a pointer to the "temporary page" buffer held internally
41988 ** by the pager. This is a buffer that is big enough to hold the
41989 ** entire content of a database page. This buffer is used internally
41990 ** during rollback and will be overwritten whenever a rollback
41991 ** occurs. But other modules are free to use it too, as long as
41992 ** no rollbacks are happening.
41994 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
41995 return pPager->pTmpSpace;
41999 ** Attempt to set the maximum database page count if mxPage is positive.
42000 ** Make no changes if mxPage is zero or negative. And never reduce the
42001 ** maximum page count below the current size of the database.
42003 ** Regardless of mxPage, return the current maximum page count.
42005 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
42006 if( mxPage>0 ){
42007 pPager->mxPgno = mxPage;
42009 assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
42010 assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
42011 return pPager->mxPgno;
42015 ** The following set of routines are used to disable the simulated
42016 ** I/O error mechanism. These routines are used to avoid simulated
42017 ** errors in places where we do not care about errors.
42019 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
42020 ** and generate no code.
42022 #ifdef SQLITE_TEST
42023 SQLITE_API extern int sqlite3_io_error_pending;
42024 SQLITE_API extern int sqlite3_io_error_hit;
42025 static int saved_cnt;
42026 void disable_simulated_io_errors(void){
42027 saved_cnt = sqlite3_io_error_pending;
42028 sqlite3_io_error_pending = -1;
42030 void enable_simulated_io_errors(void){
42031 sqlite3_io_error_pending = saved_cnt;
42033 #else
42034 # define disable_simulated_io_errors()
42035 # define enable_simulated_io_errors()
42036 #endif
42039 ** Read the first N bytes from the beginning of the file into memory
42040 ** that pDest points to.
42042 ** If the pager was opened on a transient file (zFilename==""), or
42043 ** opened on a file less than N bytes in size, the output buffer is
42044 ** zeroed and SQLITE_OK returned. The rationale for this is that this
42045 ** function is used to read database headers, and a new transient or
42046 ** zero sized database has a header than consists entirely of zeroes.
42048 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
42049 ** the error code is returned to the caller and the contents of the
42050 ** output buffer undefined.
42052 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
42053 int rc = SQLITE_OK;
42054 memset(pDest, 0, N);
42055 assert( isOpen(pPager->fd) || pPager->tempFile );
42057 /* This routine is only called by btree immediately after creating
42058 ** the Pager object. There has not been an opportunity to transition
42059 ** to WAL mode yet.
42061 assert( !pagerUseWal(pPager) );
42063 if( isOpen(pPager->fd) ){
42064 IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
42065 rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
42066 if( rc==SQLITE_IOERR_SHORT_READ ){
42067 rc = SQLITE_OK;
42070 return rc;
42074 ** This function may only be called when a read-transaction is open on
42075 ** the pager. It returns the total number of pages in the database.
42077 ** However, if the file is between 1 and <page-size> bytes in size, then
42078 ** this is considered a 1 page file.
42080 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
42081 assert( pPager->eState>=PAGER_READER );
42082 assert( pPager->eState!=PAGER_WRITER_FINISHED );
42083 *pnPage = (int)pPager->dbSize;
42088 ** Try to obtain a lock of type locktype on the database file. If
42089 ** a similar or greater lock is already held, this function is a no-op
42090 ** (returning SQLITE_OK immediately).
42092 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
42093 ** the busy callback if the lock is currently not available. Repeat
42094 ** until the busy callback returns false or until the attempt to
42095 ** obtain the lock succeeds.
42097 ** Return SQLITE_OK on success and an error code if we cannot obtain
42098 ** the lock. If the lock is obtained successfully, set the Pager.state
42099 ** variable to locktype before returning.
42101 static int pager_wait_on_lock(Pager *pPager, int locktype){
42102 int rc; /* Return code */
42104 /* Check that this is either a no-op (because the requested lock is
42105 ** already held, or one of the transistions that the busy-handler
42106 ** may be invoked during, according to the comment above
42107 ** sqlite3PagerSetBusyhandler().
42109 assert( (pPager->eLock>=locktype)
42110 || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
42111 || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
42114 do {
42115 rc = pagerLockDb(pPager, locktype);
42116 }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
42117 return rc;
42121 ** Function assertTruncateConstraint(pPager) checks that one of the
42122 ** following is true for all dirty pages currently in the page-cache:
42124 ** a) The page number is less than or equal to the size of the
42125 ** current database image, in pages, OR
42127 ** b) if the page content were written at this time, it would not
42128 ** be necessary to write the current content out to the sub-journal
42129 ** (as determined by function subjRequiresPage()).
42131 ** If the condition asserted by this function were not true, and the
42132 ** dirty page were to be discarded from the cache via the pagerStress()
42133 ** routine, pagerStress() would not write the current page content to
42134 ** the database file. If a savepoint transaction were rolled back after
42135 ** this happened, the correct behavior would be to restore the current
42136 ** content of the page. However, since this content is not present in either
42137 ** the database file or the portion of the rollback journal and
42138 ** sub-journal rolled back the content could not be restored and the
42139 ** database image would become corrupt. It is therefore fortunate that
42140 ** this circumstance cannot arise.
42142 #if defined(SQLITE_DEBUG)
42143 static void assertTruncateConstraintCb(PgHdr *pPg){
42144 assert( pPg->flags&PGHDR_DIRTY );
42145 assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
42147 static void assertTruncateConstraint(Pager *pPager){
42148 sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
42150 #else
42151 # define assertTruncateConstraint(pPager)
42152 #endif
42155 ** Truncate the in-memory database file image to nPage pages. This
42156 ** function does not actually modify the database file on disk. It
42157 ** just sets the internal state of the pager object so that the
42158 ** truncation will be done when the current transaction is committed.
42160 ** This function is only called right before committing a transaction.
42161 ** Once this function has been called, the transaction must either be
42162 ** rolled back or committed. It is not safe to call this function and
42163 ** then continue writing to the database.
42165 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
42166 assert( pPager->dbSize>=nPage );
42167 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42168 pPager->dbSize = nPage;
42170 /* At one point the code here called assertTruncateConstraint() to
42171 ** ensure that all pages being truncated away by this operation are,
42172 ** if one or more savepoints are open, present in the savepoint
42173 ** journal so that they can be restored if the savepoint is rolled
42174 ** back. This is no longer necessary as this function is now only
42175 ** called right before committing a transaction. So although the
42176 ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
42177 ** they cannot be rolled back. So the assertTruncateConstraint() call
42178 ** is no longer correct. */
42183 ** This function is called before attempting a hot-journal rollback. It
42184 ** syncs the journal file to disk, then sets pPager->journalHdr to the
42185 ** size of the journal file so that the pager_playback() routine knows
42186 ** that the entire journal file has been synced.
42188 ** Syncing a hot-journal to disk before attempting to roll it back ensures
42189 ** that if a power-failure occurs during the rollback, the process that
42190 ** attempts rollback following system recovery sees the same journal
42191 ** content as this process.
42193 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
42194 ** an SQLite error code.
42196 static int pagerSyncHotJournal(Pager *pPager){
42197 int rc = SQLITE_OK;
42198 if( !pPager->noSync ){
42199 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
42201 if( rc==SQLITE_OK ){
42202 rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
42204 return rc;
42208 ** Obtain a reference to a memory mapped page object for page number pgno.
42209 ** The new object will use the pointer pData, obtained from xFetch().
42210 ** If successful, set *ppPage to point to the new page reference
42211 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
42212 ** *ppPage to zero.
42214 ** Page references obtained by calling this function should be released
42215 ** by calling pagerReleaseMapPage().
42217 static int pagerAcquireMapPage(
42218 Pager *pPager, /* Pager object */
42219 Pgno pgno, /* Page number */
42220 void *pData, /* xFetch()'d data for this page */
42221 PgHdr **ppPage /* OUT: Acquired page object */
42223 PgHdr *p; /* Memory mapped page to return */
42225 if( pPager->pMmapFreelist ){
42226 *ppPage = p = pPager->pMmapFreelist;
42227 pPager->pMmapFreelist = p->pDirty;
42228 p->pDirty = 0;
42229 memset(p->pExtra, 0, pPager->nExtra);
42230 }else{
42231 *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
42232 if( p==0 ){
42233 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
42234 return SQLITE_NOMEM;
42236 p->pExtra = (void *)&p[1];
42237 p->flags = PGHDR_MMAP;
42238 p->nRef = 1;
42239 p->pPager = pPager;
42242 assert( p->pExtra==(void *)&p[1] );
42243 assert( p->pPage==0 );
42244 assert( p->flags==PGHDR_MMAP );
42245 assert( p->pPager==pPager );
42246 assert( p->nRef==1 );
42248 p->pgno = pgno;
42249 p->pData = pData;
42250 pPager->nMmapOut++;
42252 return SQLITE_OK;
42256 ** Release a reference to page pPg. pPg must have been returned by an
42257 ** earlier call to pagerAcquireMapPage().
42259 static void pagerReleaseMapPage(PgHdr *pPg){
42260 Pager *pPager = pPg->pPager;
42261 pPager->nMmapOut--;
42262 pPg->pDirty = pPager->pMmapFreelist;
42263 pPager->pMmapFreelist = pPg;
42265 assert( pPager->fd->pMethods->iVersion>=3 );
42266 sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
42270 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
42272 static void pagerFreeMapHdrs(Pager *pPager){
42273 PgHdr *p;
42274 PgHdr *pNext;
42275 for(p=pPager->pMmapFreelist; p; p=pNext){
42276 pNext = p->pDirty;
42277 sqlite3_free(p);
42283 ** Shutdown the page cache. Free all memory and close all files.
42285 ** If a transaction was in progress when this routine is called, that
42286 ** transaction is rolled back. All outstanding pages are invalidated
42287 ** and their memory is freed. Any attempt to use a page associated
42288 ** with this page cache after this function returns will likely
42289 ** result in a coredump.
42291 ** This function always succeeds. If a transaction is active an attempt
42292 ** is made to roll it back. If an error occurs during the rollback
42293 ** a hot journal may be left in the filesystem but no error is returned
42294 ** to the caller.
42296 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
42297 u8 *pTmp = (u8 *)pPager->pTmpSpace;
42299 assert( assert_pager_state(pPager) );
42300 disable_simulated_io_errors();
42301 sqlite3BeginBenignMalloc();
42302 pagerFreeMapHdrs(pPager);
42303 /* pPager->errCode = 0; */
42304 pPager->exclusiveMode = 0;
42305 #ifndef SQLITE_OMIT_WAL
42306 sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
42307 pPager->pWal = 0;
42308 #endif
42309 pager_reset(pPager);
42310 if( MEMDB ){
42311 pager_unlock(pPager);
42312 }else{
42313 /* If it is open, sync the journal file before calling UnlockAndRollback.
42314 ** If this is not done, then an unsynced portion of the open journal
42315 ** file may be played back into the database. If a power failure occurs
42316 ** while this is happening, the database could become corrupt.
42318 ** If an error occurs while trying to sync the journal, shift the pager
42319 ** into the ERROR state. This causes UnlockAndRollback to unlock the
42320 ** database and close the journal file without attempting to roll it
42321 ** back or finalize it. The next database user will have to do hot-journal
42322 ** rollback before accessing the database file.
42324 if( isOpen(pPager->jfd) ){
42325 pager_error(pPager, pagerSyncHotJournal(pPager));
42327 pagerUnlockAndRollback(pPager);
42329 sqlite3EndBenignMalloc();
42330 enable_simulated_io_errors();
42331 PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
42332 IOTRACE(("CLOSE %p\n", pPager))
42333 sqlite3OsClose(pPager->jfd);
42334 sqlite3OsClose(pPager->fd);
42335 sqlite3PageFree(pTmp);
42336 sqlite3PcacheClose(pPager->pPCache);
42338 #ifdef SQLITE_HAS_CODEC
42339 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
42340 #endif
42342 assert( !pPager->aSavepoint && !pPager->pInJournal );
42343 assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
42345 sqlite3_free(pPager);
42346 return SQLITE_OK;
42349 #if !defined(NDEBUG) || defined(SQLITE_TEST)
42351 ** Return the page number for page pPg.
42353 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
42354 return pPg->pgno;
42356 #endif
42359 ** Increment the reference count for page pPg.
42361 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
42362 sqlite3PcacheRef(pPg);
42366 ** Sync the journal. In other words, make sure all the pages that have
42367 ** been written to the journal have actually reached the surface of the
42368 ** disk and can be restored in the event of a hot-journal rollback.
42370 ** If the Pager.noSync flag is set, then this function is a no-op.
42371 ** Otherwise, the actions required depend on the journal-mode and the
42372 ** device characteristics of the file-system, as follows:
42374 ** * If the journal file is an in-memory journal file, no action need
42375 ** be taken.
42377 ** * Otherwise, if the device does not support the SAFE_APPEND property,
42378 ** then the nRec field of the most recently written journal header
42379 ** is updated to contain the number of journal records that have
42380 ** been written following it. If the pager is operating in full-sync
42381 ** mode, then the journal file is synced before this field is updated.
42383 ** * If the device does not support the SEQUENTIAL property, then
42384 ** journal file is synced.
42386 ** Or, in pseudo-code:
42388 ** if( NOT <in-memory journal> ){
42389 ** if( NOT SAFE_APPEND ){
42390 ** if( <full-sync mode> ) xSync(<journal file>);
42391 ** <update nRec field>
42392 ** }
42393 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
42394 ** }
42396 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
42397 ** page currently held in memory before returning SQLITE_OK. If an IO
42398 ** error is encountered, then the IO error code is returned to the caller.
42400 static int syncJournal(Pager *pPager, int newHdr){
42401 int rc; /* Return code */
42403 assert( pPager->eState==PAGER_WRITER_CACHEMOD
42404 || pPager->eState==PAGER_WRITER_DBMOD
42406 assert( assert_pager_state(pPager) );
42407 assert( !pagerUseWal(pPager) );
42409 rc = sqlite3PagerExclusiveLock(pPager);
42410 if( rc!=SQLITE_OK ) return rc;
42412 if( !pPager->noSync ){
42413 assert( !pPager->tempFile );
42414 if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
42415 const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
42416 assert( isOpen(pPager->jfd) );
42418 if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
42419 /* This block deals with an obscure problem. If the last connection
42420 ** that wrote to this database was operating in persistent-journal
42421 ** mode, then the journal file may at this point actually be larger
42422 ** than Pager.journalOff bytes. If the next thing in the journal
42423 ** file happens to be a journal-header (written as part of the
42424 ** previous connection's transaction), and a crash or power-failure
42425 ** occurs after nRec is updated but before this connection writes
42426 ** anything else to the journal file (or commits/rolls back its
42427 ** transaction), then SQLite may become confused when doing the
42428 ** hot-journal rollback following recovery. It may roll back all
42429 ** of this connections data, then proceed to rolling back the old,
42430 ** out-of-date data that follows it. Database corruption.
42432 ** To work around this, if the journal file does appear to contain
42433 ** a valid header following Pager.journalOff, then write a 0x00
42434 ** byte to the start of it to prevent it from being recognized.
42436 ** Variable iNextHdrOffset is set to the offset at which this
42437 ** problematic header will occur, if it exists. aMagic is used
42438 ** as a temporary buffer to inspect the first couple of bytes of
42439 ** the potential journal header.
42441 i64 iNextHdrOffset;
42442 u8 aMagic[8];
42443 u8 zHeader[sizeof(aJournalMagic)+4];
42445 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
42446 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
42448 iNextHdrOffset = journalHdrOffset(pPager);
42449 rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
42450 if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
42451 static const u8 zerobyte = 0;
42452 rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
42454 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
42455 return rc;
42458 /* Write the nRec value into the journal file header. If in
42459 ** full-synchronous mode, sync the journal first. This ensures that
42460 ** all data has really hit the disk before nRec is updated to mark
42461 ** it as a candidate for rollback.
42463 ** This is not required if the persistent media supports the
42464 ** SAFE_APPEND property. Because in this case it is not possible
42465 ** for garbage data to be appended to the file, the nRec field
42466 ** is populated with 0xFFFFFFFF when the journal header is written
42467 ** and never needs to be updated.
42469 if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
42470 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
42471 IOTRACE(("JSYNC %p\n", pPager))
42472 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
42473 if( rc!=SQLITE_OK ) return rc;
42475 IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
42476 rc = sqlite3OsWrite(
42477 pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
42479 if( rc!=SQLITE_OK ) return rc;
42481 if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
42482 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
42483 IOTRACE(("JSYNC %p\n", pPager))
42484 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
42485 (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
42487 if( rc!=SQLITE_OK ) return rc;
42490 pPager->journalHdr = pPager->journalOff;
42491 if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
42492 pPager->nRec = 0;
42493 rc = writeJournalHdr(pPager);
42494 if( rc!=SQLITE_OK ) return rc;
42496 }else{
42497 pPager->journalHdr = pPager->journalOff;
42501 /* Unless the pager is in noSync mode, the journal file was just
42502 ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
42503 ** all pages.
42505 sqlite3PcacheClearSyncFlags(pPager->pPCache);
42506 pPager->eState = PAGER_WRITER_DBMOD;
42507 assert( assert_pager_state(pPager) );
42508 return SQLITE_OK;
42512 ** The argument is the first in a linked list of dirty pages connected
42513 ** by the PgHdr.pDirty pointer. This function writes each one of the
42514 ** in-memory pages in the list to the database file. The argument may
42515 ** be NULL, representing an empty list. In this case this function is
42516 ** a no-op.
42518 ** The pager must hold at least a RESERVED lock when this function
42519 ** is called. Before writing anything to the database file, this lock
42520 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
42521 ** SQLITE_BUSY is returned and no data is written to the database file.
42523 ** If the pager is a temp-file pager and the actual file-system file
42524 ** is not yet open, it is created and opened before any data is
42525 ** written out.
42527 ** Once the lock has been upgraded and, if necessary, the file opened,
42528 ** the pages are written out to the database file in list order. Writing
42529 ** a page is skipped if it meets either of the following criteria:
42531 ** * The page number is greater than Pager.dbSize, or
42532 ** * The PGHDR_DONT_WRITE flag is set on the page.
42534 ** If writing out a page causes the database file to grow, Pager.dbFileSize
42535 ** is updated accordingly. If page 1 is written out, then the value cached
42536 ** in Pager.dbFileVers[] is updated to match the new value stored in
42537 ** the database file.
42539 ** If everything is successful, SQLITE_OK is returned. If an IO error
42540 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
42541 ** be obtained, SQLITE_BUSY is returned.
42543 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
42544 int rc = SQLITE_OK; /* Return code */
42546 /* This function is only called for rollback pagers in WRITER_DBMOD state. */
42547 assert( !pagerUseWal(pPager) );
42548 assert( pPager->eState==PAGER_WRITER_DBMOD );
42549 assert( pPager->eLock==EXCLUSIVE_LOCK );
42551 /* If the file is a temp-file has not yet been opened, open it now. It
42552 ** is not possible for rc to be other than SQLITE_OK if this branch
42553 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
42555 if( !isOpen(pPager->fd) ){
42556 assert( pPager->tempFile && rc==SQLITE_OK );
42557 rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
42560 /* Before the first write, give the VFS a hint of what the final
42561 ** file size will be.
42563 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
42564 if( rc==SQLITE_OK
42565 && pPager->dbHintSize<pPager->dbSize
42566 && (pList->pDirty || pList->pgno>pPager->dbHintSize)
42568 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
42569 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
42570 pPager->dbHintSize = pPager->dbSize;
42573 while( rc==SQLITE_OK && pList ){
42574 Pgno pgno = pList->pgno;
42576 /* If there are dirty pages in the page cache with page numbers greater
42577 ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
42578 ** make the file smaller (presumably by auto-vacuum code). Do not write
42579 ** any such pages to the file.
42581 ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
42582 ** set (set by sqlite3PagerDontWrite()).
42584 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
42585 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
42586 char *pData; /* Data to write */
42588 assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
42589 if( pList->pgno==1 ) pager_write_changecounter(pList);
42591 /* Encode the database */
42592 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
42594 /* Write out the page data. */
42595 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
42597 /* If page 1 was just written, update Pager.dbFileVers to match
42598 ** the value now stored in the database file. If writing this
42599 ** page caused the database file to grow, update dbFileSize.
42601 if( pgno==1 ){
42602 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
42604 if( pgno>pPager->dbFileSize ){
42605 pPager->dbFileSize = pgno;
42607 pPager->aStat[PAGER_STAT_WRITE]++;
42609 /* Update any backup objects copying the contents of this pager. */
42610 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
42612 PAGERTRACE(("STORE %d page %d hash(%08x)\n",
42613 PAGERID(pPager), pgno, pager_pagehash(pList)));
42614 IOTRACE(("PGOUT %p %d\n", pPager, pgno));
42615 PAGER_INCR(sqlite3_pager_writedb_count);
42616 }else{
42617 PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
42619 pager_set_pagehash(pList);
42620 pList = pList->pDirty;
42623 return rc;
42627 ** Ensure that the sub-journal file is open. If it is already open, this
42628 ** function is a no-op.
42630 ** SQLITE_OK is returned if everything goes according to plan. An
42631 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
42632 ** fails.
42634 static int openSubJournal(Pager *pPager){
42635 int rc = SQLITE_OK;
42636 if( !isOpen(pPager->sjfd) ){
42637 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
42638 sqlite3MemJournalOpen(pPager->sjfd);
42639 }else{
42640 rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
42643 return rc;
42647 ** Append a record of the current state of page pPg to the sub-journal.
42648 ** It is the callers responsibility to use subjRequiresPage() to check
42649 ** that it is really required before calling this function.
42651 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
42652 ** for all open savepoints before returning.
42654 ** This function returns SQLITE_OK if everything is successful, an IO
42655 ** error code if the attempt to write to the sub-journal fails, or
42656 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
42657 ** bitvec.
42659 static int subjournalPage(PgHdr *pPg){
42660 int rc = SQLITE_OK;
42661 Pager *pPager = pPg->pPager;
42662 if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42664 /* Open the sub-journal, if it has not already been opened */
42665 assert( pPager->useJournal );
42666 assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
42667 assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
42668 assert( pagerUseWal(pPager)
42669 || pageInJournal(pPg)
42670 || pPg->pgno>pPager->dbOrigSize
42672 rc = openSubJournal(pPager);
42674 /* If the sub-journal was opened successfully (or was already open),
42675 ** write the journal record into the file. */
42676 if( rc==SQLITE_OK ){
42677 void *pData = pPg->pData;
42678 i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
42679 char *pData2;
42681 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42682 PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
42683 rc = write32bits(pPager->sjfd, offset, pPg->pgno);
42684 if( rc==SQLITE_OK ){
42685 rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
42689 if( rc==SQLITE_OK ){
42690 pPager->nSubRec++;
42691 assert( pPager->nSavepoint>0 );
42692 rc = addToSavepointBitvecs(pPager, pPg->pgno);
42694 return rc;
42698 ** This function is called by the pcache layer when it has reached some
42699 ** soft memory limit. The first argument is a pointer to a Pager object
42700 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
42701 ** database). The second argument is a reference to a page that is
42702 ** currently dirty but has no outstanding references. The page
42703 ** is always associated with the Pager object passed as the first
42704 ** argument.
42706 ** The job of this function is to make pPg clean by writing its contents
42707 ** out to the database file, if possible. This may involve syncing the
42708 ** journal file.
42710 ** If successful, sqlite3PcacheMakeClean() is called on the page and
42711 ** SQLITE_OK returned. If an IO error occurs while trying to make the
42712 ** page clean, the IO error code is returned. If the page cannot be
42713 ** made clean for some other reason, but no error occurs, then SQLITE_OK
42714 ** is returned by sqlite3PcacheMakeClean() is not called.
42716 static int pagerStress(void *p, PgHdr *pPg){
42717 Pager *pPager = (Pager *)p;
42718 int rc = SQLITE_OK;
42720 assert( pPg->pPager==pPager );
42721 assert( pPg->flags&PGHDR_DIRTY );
42723 /* The doNotSpill NOSYNC bit is set during times when doing a sync of
42724 ** journal (and adding a new header) is not allowed. This occurs
42725 ** during calls to sqlite3PagerWrite() while trying to journal multiple
42726 ** pages belonging to the same sector.
42728 ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
42729 ** regardless of whether or not a sync is required. This is set during
42730 ** a rollback or by user request, respectively.
42732 ** Spilling is also prohibited when in an error state since that could
42733 ** lead to database corruption. In the current implementaton it
42734 ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
42735 ** while in the error state, hence it is impossible for this routine to
42736 ** be called in the error state. Nevertheless, we include a NEVER()
42737 ** test for the error state as a safeguard against future changes.
42739 if( NEVER(pPager->errCode) ) return SQLITE_OK;
42740 testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
42741 testcase( pPager->doNotSpill & SPILLFLAG_OFF );
42742 testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
42743 if( pPager->doNotSpill
42744 && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
42745 || (pPg->flags & PGHDR_NEED_SYNC)!=0)
42747 return SQLITE_OK;
42750 pPg->pDirty = 0;
42751 if( pagerUseWal(pPager) ){
42752 /* Write a single frame for this page to the log. */
42753 if( subjRequiresPage(pPg) ){
42754 rc = subjournalPage(pPg);
42756 if( rc==SQLITE_OK ){
42757 rc = pagerWalFrames(pPager, pPg, 0, 0);
42759 }else{
42761 /* Sync the journal file if required. */
42762 if( pPg->flags&PGHDR_NEED_SYNC
42763 || pPager->eState==PAGER_WRITER_CACHEMOD
42765 rc = syncJournal(pPager, 1);
42768 /* If the page number of this page is larger than the current size of
42769 ** the database image, it may need to be written to the sub-journal.
42770 ** This is because the call to pager_write_pagelist() below will not
42771 ** actually write data to the file in this case.
42773 ** Consider the following sequence of events:
42775 ** BEGIN;
42776 ** <journal page X>
42777 ** <modify page X>
42778 ** SAVEPOINT sp;
42779 ** <shrink database file to Y pages>
42780 ** pagerStress(page X)
42781 ** ROLLBACK TO sp;
42783 ** If (X>Y), then when pagerStress is called page X will not be written
42784 ** out to the database file, but will be dropped from the cache. Then,
42785 ** following the "ROLLBACK TO sp" statement, reading page X will read
42786 ** data from the database file. This will be the copy of page X as it
42787 ** was when the transaction started, not as it was when "SAVEPOINT sp"
42788 ** was executed.
42790 ** The solution is to write the current data for page X into the
42791 ** sub-journal file now (if it is not already there), so that it will
42792 ** be restored to its current value when the "ROLLBACK TO sp" is
42793 ** executed.
42795 if( NEVER(
42796 rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
42797 ) ){
42798 rc = subjournalPage(pPg);
42801 /* Write the contents of the page out to the database file. */
42802 if( rc==SQLITE_OK ){
42803 assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
42804 rc = pager_write_pagelist(pPager, pPg);
42808 /* Mark the page as clean. */
42809 if( rc==SQLITE_OK ){
42810 PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
42811 sqlite3PcacheMakeClean(pPg);
42814 return pager_error(pPager, rc);
42819 ** Allocate and initialize a new Pager object and put a pointer to it
42820 ** in *ppPager. The pager should eventually be freed by passing it
42821 ** to sqlite3PagerClose().
42823 ** The zFilename argument is the path to the database file to open.
42824 ** If zFilename is NULL then a randomly-named temporary file is created
42825 ** and used as the file to be cached. Temporary files are be deleted
42826 ** automatically when they are closed. If zFilename is ":memory:" then
42827 ** all information is held in cache. It is never written to disk.
42828 ** This can be used to implement an in-memory database.
42830 ** The nExtra parameter specifies the number of bytes of space allocated
42831 ** along with each page reference. This space is available to the user
42832 ** via the sqlite3PagerGetExtra() API.
42834 ** The flags argument is used to specify properties that affect the
42835 ** operation of the pager. It should be passed some bitwise combination
42836 ** of the PAGER_* flags.
42838 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
42839 ** of the xOpen() method of the supplied VFS when opening files.
42841 ** If the pager object is allocated and the specified file opened
42842 ** successfully, SQLITE_OK is returned and *ppPager set to point to
42843 ** the new pager object. If an error occurs, *ppPager is set to NULL
42844 ** and error code returned. This function may return SQLITE_NOMEM
42845 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
42846 ** various SQLITE_IO_XXX errors.
42848 SQLITE_PRIVATE int sqlite3PagerOpen(
42849 sqlite3_vfs *pVfs, /* The virtual file system to use */
42850 Pager **ppPager, /* OUT: Return the Pager structure here */
42851 const char *zFilename, /* Name of the database file to open */
42852 int nExtra, /* Extra bytes append to each in-memory page */
42853 int flags, /* flags controlling this file */
42854 int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
42855 void (*xReinit)(DbPage*) /* Function to reinitialize pages */
42857 u8 *pPtr;
42858 Pager *pPager = 0; /* Pager object to allocate and return */
42859 int rc = SQLITE_OK; /* Return code */
42860 int tempFile = 0; /* True for temp files (incl. in-memory files) */
42861 int memDb = 0; /* True if this is an in-memory file */
42862 int readOnly = 0; /* True if this is a read-only file */
42863 int journalFileSize; /* Bytes to allocate for each journal fd */
42864 char *zPathname = 0; /* Full path to database file */
42865 int nPathname = 0; /* Number of bytes in zPathname */
42866 int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
42867 int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
42868 u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
42869 const char *zUri = 0; /* URI args to copy */
42870 int nUri = 0; /* Number of bytes of URI args at *zUri */
42872 /* Figure out how much space is required for each journal file-handle
42873 ** (there are two of them, the main journal and the sub-journal). This
42874 ** is the maximum space required for an in-memory journal file handle
42875 ** and a regular journal file-handle. Note that a "regular journal-handle"
42876 ** may be a wrapper capable of caching the first portion of the journal
42877 ** file in memory to implement the atomic-write optimization (see
42878 ** source file journal.c).
42880 if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
42881 journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
42882 }else{
42883 journalFileSize = ROUND8(sqlite3MemJournalSize());
42886 /* Set the output variable to NULL in case an error occurs. */
42887 *ppPager = 0;
42889 #ifndef SQLITE_OMIT_MEMORYDB
42890 if( flags & PAGER_MEMORY ){
42891 memDb = 1;
42892 if( zFilename && zFilename[0] ){
42893 zPathname = sqlite3DbStrDup(0, zFilename);
42894 if( zPathname==0 ) return SQLITE_NOMEM;
42895 nPathname = sqlite3Strlen30(zPathname);
42896 zFilename = 0;
42899 #endif
42901 /* Compute and store the full pathname in an allocated buffer pointed
42902 ** to by zPathname, length nPathname. Or, if this is a temporary file,
42903 ** leave both nPathname and zPathname set to 0.
42905 if( zFilename && zFilename[0] ){
42906 const char *z;
42907 nPathname = pVfs->mxPathname+1;
42908 zPathname = sqlite3DbMallocRaw(0, nPathname*2);
42909 if( zPathname==0 ){
42910 return SQLITE_NOMEM;
42912 zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
42913 rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
42914 nPathname = sqlite3Strlen30(zPathname);
42915 z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
42916 while( *z ){
42917 z += sqlite3Strlen30(z)+1;
42918 z += sqlite3Strlen30(z)+1;
42920 nUri = (int)(&z[1] - zUri);
42921 assert( nUri>=0 );
42922 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
42923 /* This branch is taken when the journal path required by
42924 ** the database being opened will be more than pVfs->mxPathname
42925 ** bytes in length. This means the database cannot be opened,
42926 ** as it will not be possible to open the journal file or even
42927 ** check for a hot-journal before reading.
42929 rc = SQLITE_CANTOPEN_BKPT;
42931 if( rc!=SQLITE_OK ){
42932 sqlite3DbFree(0, zPathname);
42933 return rc;
42937 /* Allocate memory for the Pager structure, PCache object, the
42938 ** three file descriptors, the database file name and the journal
42939 ** file name. The layout in memory is as follows:
42941 ** Pager object (sizeof(Pager) bytes)
42942 ** PCache object (sqlite3PcacheSize() bytes)
42943 ** Database file handle (pVfs->szOsFile bytes)
42944 ** Sub-journal file handle (journalFileSize bytes)
42945 ** Main journal file handle (journalFileSize bytes)
42946 ** Database file name (nPathname+1 bytes)
42947 ** Journal file name (nPathname+8+1 bytes)
42949 pPtr = (u8 *)sqlite3MallocZero(
42950 ROUND8(sizeof(*pPager)) + /* Pager structure */
42951 ROUND8(pcacheSize) + /* PCache object */
42952 ROUND8(pVfs->szOsFile) + /* The main db file */
42953 journalFileSize * 2 + /* The two journal files */
42954 nPathname + 1 + nUri + /* zFilename */
42955 nPathname + 8 + 2 /* zJournal */
42956 #ifndef SQLITE_OMIT_WAL
42957 + nPathname + 4 + 2 /* zWal */
42958 #endif
42960 assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
42961 if( !pPtr ){
42962 sqlite3DbFree(0, zPathname);
42963 return SQLITE_NOMEM;
42965 pPager = (Pager*)(pPtr);
42966 pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
42967 pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
42968 pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
42969 pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
42970 pPager->zFilename = (char*)(pPtr += journalFileSize);
42971 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
42973 /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
42974 if( zPathname ){
42975 assert( nPathname>0 );
42976 pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
42977 memcpy(pPager->zFilename, zPathname, nPathname);
42978 if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
42979 memcpy(pPager->zJournal, zPathname, nPathname);
42980 memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
42981 sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
42982 #ifndef SQLITE_OMIT_WAL
42983 pPager->zWal = &pPager->zJournal[nPathname+8+1];
42984 memcpy(pPager->zWal, zPathname, nPathname);
42985 memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
42986 sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
42987 #endif
42988 sqlite3DbFree(0, zPathname);
42990 pPager->pVfs = pVfs;
42991 pPager->vfsFlags = vfsFlags;
42993 /* Open the pager file.
42995 if( zFilename && zFilename[0] ){
42996 int fout = 0; /* VFS flags returned by xOpen() */
42997 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
42998 assert( !memDb );
42999 readOnly = (fout&SQLITE_OPEN_READONLY);
43001 /* If the file was successfully opened for read/write access,
43002 ** choose a default page size in case we have to create the
43003 ** database file. The default page size is the maximum of:
43005 ** + SQLITE_DEFAULT_PAGE_SIZE,
43006 ** + The value returned by sqlite3OsSectorSize()
43007 ** + The largest page size that can be written atomically.
43009 if( rc==SQLITE_OK && !readOnly ){
43010 setSectorSize(pPager);
43011 assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
43012 if( szPageDflt<pPager->sectorSize ){
43013 if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
43014 szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
43015 }else{
43016 szPageDflt = (u32)pPager->sectorSize;
43019 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43021 int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
43022 int ii;
43023 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
43024 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
43025 assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
43026 for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
43027 if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
43028 szPageDflt = ii;
43032 #endif
43034 }else{
43035 /* If a temporary file is requested, it is not opened immediately.
43036 ** In this case we accept the default page size and delay actually
43037 ** opening the file until the first call to OsWrite().
43039 ** This branch is also run for an in-memory database. An in-memory
43040 ** database is the same as a temp-file that is never written out to
43041 ** disk and uses an in-memory rollback journal.
43043 tempFile = 1;
43044 pPager->eState = PAGER_READER;
43045 pPager->eLock = EXCLUSIVE_LOCK;
43046 readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
43049 /* The following call to PagerSetPagesize() serves to set the value of
43050 ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
43052 if( rc==SQLITE_OK ){
43053 assert( pPager->memDb==0 );
43054 rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
43055 testcase( rc!=SQLITE_OK );
43058 /* If an error occurred in either of the blocks above, free the
43059 ** Pager structure and close the file.
43061 if( rc!=SQLITE_OK ){
43062 assert( !pPager->pTmpSpace );
43063 sqlite3OsClose(pPager->fd);
43064 sqlite3_free(pPager);
43065 return rc;
43068 /* Initialize the PCache object. */
43069 assert( nExtra<1000 );
43070 nExtra = ROUND8(nExtra);
43071 sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
43072 !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
43074 PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
43075 IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
43077 pPager->useJournal = (u8)useJournal;
43078 /* pPager->stmtOpen = 0; */
43079 /* pPager->stmtInUse = 0; */
43080 /* pPager->nRef = 0; */
43081 /* pPager->stmtSize = 0; */
43082 /* pPager->stmtJSize = 0; */
43083 /* pPager->nPage = 0; */
43084 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
43085 /* pPager->state = PAGER_UNLOCK; */
43086 #if 0
43087 assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
43088 #endif
43089 /* pPager->errMask = 0; */
43090 pPager->tempFile = (u8)tempFile;
43091 assert( tempFile==PAGER_LOCKINGMODE_NORMAL
43092 || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
43093 assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
43094 pPager->exclusiveMode = (u8)tempFile;
43095 pPager->changeCountDone = pPager->tempFile;
43096 pPager->memDb = (u8)memDb;
43097 pPager->readOnly = (u8)readOnly;
43098 assert( useJournal || pPager->tempFile );
43099 pPager->noSync = pPager->tempFile;
43100 if( pPager->noSync ){
43101 assert( pPager->fullSync==0 );
43102 assert( pPager->syncFlags==0 );
43103 assert( pPager->walSyncFlags==0 );
43104 assert( pPager->ckptSyncFlags==0 );
43105 }else{
43106 pPager->fullSync = 1;
43107 pPager->syncFlags = SQLITE_SYNC_NORMAL;
43108 pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
43109 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
43111 /* pPager->pFirst = 0; */
43112 /* pPager->pFirstSynced = 0; */
43113 /* pPager->pLast = 0; */
43114 pPager->nExtra = (u16)nExtra;
43115 pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
43116 assert( isOpen(pPager->fd) || tempFile );
43117 setSectorSize(pPager);
43118 if( !useJournal ){
43119 pPager->journalMode = PAGER_JOURNALMODE_OFF;
43120 }else if( memDb ){
43121 pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
43123 /* pPager->xBusyHandler = 0; */
43124 /* pPager->pBusyHandlerArg = 0; */
43125 pPager->xReiniter = xReinit;
43126 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
43127 /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
43129 *ppPager = pPager;
43130 return SQLITE_OK;
43136 ** This function is called after transitioning from PAGER_UNLOCK to
43137 ** PAGER_SHARED state. It tests if there is a hot journal present in
43138 ** the file-system for the given pager. A hot journal is one that
43139 ** needs to be played back. According to this function, a hot-journal
43140 ** file exists if the following criteria are met:
43142 ** * The journal file exists in the file system, and
43143 ** * No process holds a RESERVED or greater lock on the database file, and
43144 ** * The database file itself is greater than 0 bytes in size, and
43145 ** * The first byte of the journal file exists and is not 0x00.
43147 ** If the current size of the database file is 0 but a journal file
43148 ** exists, that is probably an old journal left over from a prior
43149 ** database with the same name. In this case the journal file is
43150 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
43151 ** is returned.
43153 ** This routine does not check if there is a master journal filename
43154 ** at the end of the file. If there is, and that master journal file
43155 ** does not exist, then the journal file is not really hot. In this
43156 ** case this routine will return a false-positive. The pager_playback()
43157 ** routine will discover that the journal file is not really hot and
43158 ** will not roll it back.
43160 ** If a hot-journal file is found to exist, *pExists is set to 1 and
43161 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
43162 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
43163 ** to determine whether or not a hot-journal file exists, the IO error
43164 ** code is returned and the value of *pExists is undefined.
43166 static int hasHotJournal(Pager *pPager, int *pExists){
43167 sqlite3_vfs * const pVfs = pPager->pVfs;
43168 int rc = SQLITE_OK; /* Return code */
43169 int exists = 1; /* True if a journal file is present */
43170 int jrnlOpen = !!isOpen(pPager->jfd);
43172 assert( pPager->useJournal );
43173 assert( isOpen(pPager->fd) );
43174 assert( pPager->eState==PAGER_OPEN );
43176 assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
43177 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
43180 *pExists = 0;
43181 if( !jrnlOpen ){
43182 rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
43184 if( rc==SQLITE_OK && exists ){
43185 int locked = 0; /* True if some process holds a RESERVED lock */
43187 /* Race condition here: Another process might have been holding the
43188 ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
43189 ** call above, but then delete the journal and drop the lock before
43190 ** we get to the following sqlite3OsCheckReservedLock() call. If that
43191 ** is the case, this routine might think there is a hot journal when
43192 ** in fact there is none. This results in a false-positive which will
43193 ** be dealt with by the playback routine. Ticket #3883.
43195 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
43196 if( rc==SQLITE_OK && !locked ){
43197 Pgno nPage; /* Number of pages in database file */
43199 /* Check the size of the database file. If it consists of 0 pages,
43200 ** then delete the journal file. See the header comment above for
43201 ** the reasoning here. Delete the obsolete journal file under
43202 ** a RESERVED lock to avoid race conditions and to avoid violating
43203 ** [H33020].
43205 rc = pagerPagecount(pPager, &nPage);
43206 if( rc==SQLITE_OK ){
43207 if( nPage==0 ){
43208 sqlite3BeginBenignMalloc();
43209 if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
43210 sqlite3OsDelete(pVfs, pPager->zJournal, 0);
43211 if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
43213 sqlite3EndBenignMalloc();
43214 }else{
43215 /* The journal file exists and no other connection has a reserved
43216 ** or greater lock on the database file. Now check that there is
43217 ** at least one non-zero bytes at the start of the journal file.
43218 ** If there is, then we consider this journal to be hot. If not,
43219 ** it can be ignored.
43221 if( !jrnlOpen ){
43222 int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
43223 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
43225 if( rc==SQLITE_OK ){
43226 u8 first = 0;
43227 rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
43228 if( rc==SQLITE_IOERR_SHORT_READ ){
43229 rc = SQLITE_OK;
43231 if( !jrnlOpen ){
43232 sqlite3OsClose(pPager->jfd);
43234 *pExists = (first!=0);
43235 }else if( rc==SQLITE_CANTOPEN ){
43236 /* If we cannot open the rollback journal file in order to see if
43237 ** its has a zero header, that might be due to an I/O error, or
43238 ** it might be due to the race condition described above and in
43239 ** ticket #3883. Either way, assume that the journal is hot.
43240 ** This might be a false positive. But if it is, then the
43241 ** automatic journal playback and recovery mechanism will deal
43242 ** with it under an EXCLUSIVE lock where we do not need to
43243 ** worry so much with race conditions.
43245 *pExists = 1;
43246 rc = SQLITE_OK;
43253 return rc;
43257 ** This function is called to obtain a shared lock on the database file.
43258 ** It is illegal to call sqlite3PagerAcquire() until after this function
43259 ** has been successfully called. If a shared-lock is already held when
43260 ** this function is called, it is a no-op.
43262 ** The following operations are also performed by this function.
43264 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
43265 ** on the database file), then an attempt is made to obtain a
43266 ** SHARED lock on the database file. Immediately after obtaining
43267 ** the SHARED lock, the file-system is checked for a hot-journal,
43268 ** which is played back if present. Following any hot-journal
43269 ** rollback, the contents of the cache are validated by checking
43270 ** the 'change-counter' field of the database file header and
43271 ** discarded if they are found to be invalid.
43273 ** 2) If the pager is running in exclusive-mode, and there are currently
43274 ** no outstanding references to any pages, and is in the error state,
43275 ** then an attempt is made to clear the error state by discarding
43276 ** the contents of the page cache and rolling back any open journal
43277 ** file.
43279 ** If everything is successful, SQLITE_OK is returned. If an IO error
43280 ** occurs while locking the database, checking for a hot-journal file or
43281 ** rolling back a journal file, the IO error code is returned.
43283 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
43284 int rc = SQLITE_OK; /* Return code */
43286 /* This routine is only called from b-tree and only when there are no
43287 ** outstanding pages. This implies that the pager state should either
43288 ** be OPEN or READER. READER is only possible if the pager is or was in
43289 ** exclusive access mode.
43291 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
43292 assert( assert_pager_state(pPager) );
43293 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
43294 if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
43296 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
43297 int bHotJournal = 1; /* True if there exists a hot journal-file */
43299 assert( !MEMDB );
43301 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
43302 if( rc!=SQLITE_OK ){
43303 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
43304 goto failed;
43307 /* If a journal file exists, and there is no RESERVED lock on the
43308 ** database file, then it either needs to be played back or deleted.
43310 if( pPager->eLock<=SHARED_LOCK ){
43311 rc = hasHotJournal(pPager, &bHotJournal);
43313 if( rc!=SQLITE_OK ){
43314 goto failed;
43316 if( bHotJournal ){
43317 if( pPager->readOnly ){
43318 rc = SQLITE_READONLY_ROLLBACK;
43319 goto failed;
43322 /* Get an EXCLUSIVE lock on the database file. At this point it is
43323 ** important that a RESERVED lock is not obtained on the way to the
43324 ** EXCLUSIVE lock. If it were, another process might open the
43325 ** database file, detect the RESERVED lock, and conclude that the
43326 ** database is safe to read while this process is still rolling the
43327 ** hot-journal back.
43329 ** Because the intermediate RESERVED lock is not requested, any
43330 ** other process attempting to access the database file will get to
43331 ** this point in the code and fail to obtain its own EXCLUSIVE lock
43332 ** on the database file.
43334 ** Unless the pager is in locking_mode=exclusive mode, the lock is
43335 ** downgraded to SHARED_LOCK before this function returns.
43337 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43338 if( rc!=SQLITE_OK ){
43339 goto failed;
43342 /* If it is not already open and the file exists on disk, open the
43343 ** journal for read/write access. Write access is required because
43344 ** in exclusive-access mode the file descriptor will be kept open
43345 ** and possibly used for a transaction later on. Also, write-access
43346 ** is usually required to finalize the journal in journal_mode=persist
43347 ** mode (and also for journal_mode=truncate on some systems).
43349 ** If the journal does not exist, it usually means that some
43350 ** other connection managed to get in and roll it back before
43351 ** this connection obtained the exclusive lock above. Or, it
43352 ** may mean that the pager was in the error-state when this
43353 ** function was called and the journal file does not exist.
43355 if( !isOpen(pPager->jfd) ){
43356 sqlite3_vfs * const pVfs = pPager->pVfs;
43357 int bExists; /* True if journal file exists */
43358 rc = sqlite3OsAccess(
43359 pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
43360 if( rc==SQLITE_OK && bExists ){
43361 int fout = 0;
43362 int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
43363 assert( !pPager->tempFile );
43364 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
43365 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
43366 if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
43367 rc = SQLITE_CANTOPEN_BKPT;
43368 sqlite3OsClose(pPager->jfd);
43373 /* Playback and delete the journal. Drop the database write
43374 ** lock and reacquire the read lock. Purge the cache before
43375 ** playing back the hot-journal so that we don't end up with
43376 ** an inconsistent cache. Sync the hot journal before playing
43377 ** it back since the process that crashed and left the hot journal
43378 ** probably did not sync it and we are required to always sync
43379 ** the journal before playing it back.
43381 if( isOpen(pPager->jfd) ){
43382 assert( rc==SQLITE_OK );
43383 rc = pagerSyncHotJournal(pPager);
43384 if( rc==SQLITE_OK ){
43385 rc = pager_playback(pPager, 1);
43386 pPager->eState = PAGER_OPEN;
43388 }else if( !pPager->exclusiveMode ){
43389 pagerUnlockDb(pPager, SHARED_LOCK);
43392 if( rc!=SQLITE_OK ){
43393 /* This branch is taken if an error occurs while trying to open
43394 ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
43395 ** pager_unlock() routine will be called before returning to unlock
43396 ** the file. If the unlock attempt fails, then Pager.eLock must be
43397 ** set to UNKNOWN_LOCK (see the comment above the #define for
43398 ** UNKNOWN_LOCK above for an explanation).
43400 ** In order to get pager_unlock() to do this, set Pager.eState to
43401 ** PAGER_ERROR now. This is not actually counted as a transition
43402 ** to ERROR state in the state diagram at the top of this file,
43403 ** since we know that the same call to pager_unlock() will very
43404 ** shortly transition the pager object to the OPEN state. Calling
43405 ** assert_pager_state() would fail now, as it should not be possible
43406 ** to be in ERROR state when there are zero outstanding page
43407 ** references.
43409 pager_error(pPager, rc);
43410 goto failed;
43413 assert( pPager->eState==PAGER_OPEN );
43414 assert( (pPager->eLock==SHARED_LOCK)
43415 || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
43419 if( !pPager->tempFile && (
43420 pPager->pBackup
43421 || sqlite3PcachePagecount(pPager->pPCache)>0
43422 || USEFETCH(pPager)
43424 /* The shared-lock has just been acquired on the database file
43425 ** and there are already pages in the cache (from a previous
43426 ** read or write transaction). Check to see if the database
43427 ** has been modified. If the database has changed, flush the
43428 ** cache.
43430 ** Database changes is detected by looking at 15 bytes beginning
43431 ** at offset 24 into the file. The first 4 of these 16 bytes are
43432 ** a 32-bit counter that is incremented with each change. The
43433 ** other bytes change randomly with each file change when
43434 ** a codec is in use.
43436 ** There is a vanishingly small chance that a change will not be
43437 ** detected. The chance of an undetected change is so small that
43438 ** it can be neglected.
43440 Pgno nPage = 0;
43441 char dbFileVers[sizeof(pPager->dbFileVers)];
43443 rc = pagerPagecount(pPager, &nPage);
43444 if( rc ) goto failed;
43446 if( nPage>0 ){
43447 IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
43448 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
43449 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
43450 goto failed;
43452 }else{
43453 memset(dbFileVers, 0, sizeof(dbFileVers));
43456 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
43457 pager_reset(pPager);
43459 /* Unmap the database file. It is possible that external processes
43460 ** may have truncated the database file and then extended it back
43461 ** to its original size while this process was not holding a lock.
43462 ** In this case there may exist a Pager.pMap mapping that appears
43463 ** to be the right size but is not actually valid. Avoid this
43464 ** possibility by unmapping the db here. */
43465 if( USEFETCH(pPager) ){
43466 sqlite3OsUnfetch(pPager->fd, 0, 0);
43471 /* If there is a WAL file in the file-system, open this database in WAL
43472 ** mode. Otherwise, the following function call is a no-op.
43474 rc = pagerOpenWalIfPresent(pPager);
43475 #ifndef SQLITE_OMIT_WAL
43476 assert( pPager->pWal==0 || rc==SQLITE_OK );
43477 #endif
43480 if( pagerUseWal(pPager) ){
43481 assert( rc==SQLITE_OK );
43482 rc = pagerBeginReadTransaction(pPager);
43485 if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
43486 rc = pagerPagecount(pPager, &pPager->dbSize);
43489 failed:
43490 if( rc!=SQLITE_OK ){
43491 assert( !MEMDB );
43492 pager_unlock(pPager);
43493 assert( pPager->eState==PAGER_OPEN );
43494 }else{
43495 pPager->eState = PAGER_READER;
43497 return rc;
43501 ** If the reference count has reached zero, rollback any active
43502 ** transaction and unlock the pager.
43504 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
43505 ** the rollback journal, the unlock is not performed and there is
43506 ** nothing to rollback, so this routine is a no-op.
43508 static void pagerUnlockIfUnused(Pager *pPager){
43509 if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
43510 pagerUnlockAndRollback(pPager);
43515 ** Acquire a reference to page number pgno in pager pPager (a page
43516 ** reference has type DbPage*). If the requested reference is
43517 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
43519 ** If the requested page is already in the cache, it is returned.
43520 ** Otherwise, a new page object is allocated and populated with data
43521 ** read from the database file. In some cases, the pcache module may
43522 ** choose not to allocate a new page object and may reuse an existing
43523 ** object with no outstanding references.
43525 ** The extra data appended to a page is always initialized to zeros the
43526 ** first time a page is loaded into memory. If the page requested is
43527 ** already in the cache when this function is called, then the extra
43528 ** data is left as it was when the page object was last used.
43530 ** If the database image is smaller than the requested page or if a
43531 ** non-zero value is passed as the noContent parameter and the
43532 ** requested page is not already stored in the cache, then no
43533 ** actual disk read occurs. In this case the memory image of the
43534 ** page is initialized to all zeros.
43536 ** If noContent is true, it means that we do not care about the contents
43537 ** of the page. This occurs in two scenarios:
43539 ** a) When reading a free-list leaf page from the database, and
43541 ** b) When a savepoint is being rolled back and we need to load
43542 ** a new page into the cache to be filled with the data read
43543 ** from the savepoint journal.
43545 ** If noContent is true, then the data returned is zeroed instead of
43546 ** being read from the database. Additionally, the bits corresponding
43547 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
43548 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
43549 ** savepoints are set. This means if the page is made writable at any
43550 ** point in the future, using a call to sqlite3PagerWrite(), its contents
43551 ** will not be journaled. This saves IO.
43553 ** The acquisition might fail for several reasons. In all cases,
43554 ** an appropriate error code is returned and *ppPage is set to NULL.
43556 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
43557 ** to find a page in the in-memory cache first. If the page is not already
43558 ** in memory, this routine goes to disk to read it in whereas Lookup()
43559 ** just returns 0. This routine acquires a read-lock the first time it
43560 ** has to go to disk, and could also playback an old journal if necessary.
43561 ** Since Lookup() never goes to disk, it never has to deal with locks
43562 ** or journal files.
43564 SQLITE_PRIVATE int sqlite3PagerAcquire(
43565 Pager *pPager, /* The pager open on the database file */
43566 Pgno pgno, /* Page number to fetch */
43567 DbPage **ppPage, /* Write a pointer to the page here */
43568 int flags /* PAGER_GET_XXX flags */
43570 int rc = SQLITE_OK;
43571 PgHdr *pPg = 0;
43572 u32 iFrame = 0; /* Frame to read from WAL file */
43573 const int noContent = (flags & PAGER_GET_NOCONTENT);
43575 /* It is acceptable to use a read-only (mmap) page for any page except
43576 ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
43577 ** flag was specified by the caller. And so long as the db is not a
43578 ** temporary or in-memory database. */
43579 const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
43580 && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
43581 #ifdef SQLITE_HAS_CODEC
43582 && pPager->xCodec==0
43583 #endif
43586 assert( pPager->eState>=PAGER_READER );
43587 assert( assert_pager_state(pPager) );
43588 assert( noContent==0 || bMmapOk==0 );
43590 if( pgno==0 ){
43591 return SQLITE_CORRUPT_BKPT;
43594 /* If the pager is in the error state, return an error immediately.
43595 ** Otherwise, request the page from the PCache layer. */
43596 if( pPager->errCode!=SQLITE_OK ){
43597 rc = pPager->errCode;
43598 }else{
43600 if( bMmapOk && pagerUseWal(pPager) ){
43601 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
43602 if( rc!=SQLITE_OK ) goto pager_acquire_err;
43605 if( iFrame==0 && bMmapOk ){
43606 void *pData = 0;
43608 rc = sqlite3OsFetch(pPager->fd,
43609 (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
43612 if( rc==SQLITE_OK && pData ){
43613 if( pPager->eState>PAGER_READER ){
43614 (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
43616 if( pPg==0 ){
43617 rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
43618 }else{
43619 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
43621 if( pPg ){
43622 assert( rc==SQLITE_OK );
43623 *ppPage = pPg;
43624 return SQLITE_OK;
43627 if( rc!=SQLITE_OK ){
43628 goto pager_acquire_err;
43632 rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
43635 if( rc!=SQLITE_OK ){
43636 /* Either the call to sqlite3PcacheFetch() returned an error or the
43637 ** pager was already in the error-state when this function was called.
43638 ** Set pPg to 0 and jump to the exception handler. */
43639 pPg = 0;
43640 goto pager_acquire_err;
43642 assert( (*ppPage)->pgno==pgno );
43643 assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
43645 if( (*ppPage)->pPager && !noContent ){
43646 /* In this case the pcache already contains an initialized copy of
43647 ** the page. Return without further ado. */
43648 assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
43649 pPager->aStat[PAGER_STAT_HIT]++;
43650 return SQLITE_OK;
43652 }else{
43653 /* The pager cache has created a new page. Its content needs to
43654 ** be initialized. */
43656 pPg = *ppPage;
43657 pPg->pPager = pPager;
43659 /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
43660 ** number greater than this, or the unused locking-page, is requested. */
43661 if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
43662 rc = SQLITE_CORRUPT_BKPT;
43663 goto pager_acquire_err;
43666 if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
43667 if( pgno>pPager->mxPgno ){
43668 rc = SQLITE_FULL;
43669 goto pager_acquire_err;
43671 if( noContent ){
43672 /* Failure to set the bits in the InJournal bit-vectors is benign.
43673 ** It merely means that we might do some extra work to journal a
43674 ** page that does not need to be journaled. Nevertheless, be sure
43675 ** to test the case where a malloc error occurs while trying to set
43676 ** a bit in a bit vector.
43678 sqlite3BeginBenignMalloc();
43679 if( pgno<=pPager->dbOrigSize ){
43680 TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
43681 testcase( rc==SQLITE_NOMEM );
43683 TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
43684 testcase( rc==SQLITE_NOMEM );
43685 sqlite3EndBenignMalloc();
43687 memset(pPg->pData, 0, pPager->pageSize);
43688 IOTRACE(("ZERO %p %d\n", pPager, pgno));
43689 }else{
43690 if( pagerUseWal(pPager) && bMmapOk==0 ){
43691 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
43692 if( rc!=SQLITE_OK ) goto pager_acquire_err;
43694 assert( pPg->pPager==pPager );
43695 pPager->aStat[PAGER_STAT_MISS]++;
43696 rc = readDbPage(pPg, iFrame);
43697 if( rc!=SQLITE_OK ){
43698 goto pager_acquire_err;
43701 pager_set_pagehash(pPg);
43704 return SQLITE_OK;
43706 pager_acquire_err:
43707 assert( rc!=SQLITE_OK );
43708 if( pPg ){
43709 sqlite3PcacheDrop(pPg);
43711 pagerUnlockIfUnused(pPager);
43713 *ppPage = 0;
43714 return rc;
43718 ** Acquire a page if it is already in the in-memory cache. Do
43719 ** not read the page from disk. Return a pointer to the page,
43720 ** or 0 if the page is not in cache.
43722 ** See also sqlite3PagerGet(). The difference between this routine
43723 ** and sqlite3PagerGet() is that _get() will go to the disk and read
43724 ** in the page if the page is not already in cache. This routine
43725 ** returns NULL if the page is not in cache or if a disk I/O error
43726 ** has ever happened.
43728 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
43729 PgHdr *pPg = 0;
43730 assert( pPager!=0 );
43731 assert( pgno!=0 );
43732 assert( pPager->pPCache!=0 );
43733 assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
43734 sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
43735 return pPg;
43739 ** Release a page reference.
43741 ** If the number of references to the page drop to zero, then the
43742 ** page is added to the LRU list. When all references to all pages
43743 ** are released, a rollback occurs and the lock on the database is
43744 ** removed.
43746 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
43747 if( pPg ){
43748 Pager *pPager = pPg->pPager;
43749 if( pPg->flags & PGHDR_MMAP ){
43750 pagerReleaseMapPage(pPg);
43751 }else{
43752 sqlite3PcacheRelease(pPg);
43754 pagerUnlockIfUnused(pPager);
43759 ** This function is called at the start of every write transaction.
43760 ** There must already be a RESERVED or EXCLUSIVE lock on the database
43761 ** file when this routine is called.
43763 ** Open the journal file for pager pPager and write a journal header
43764 ** to the start of it. If there are active savepoints, open the sub-journal
43765 ** as well. This function is only used when the journal file is being
43766 ** opened to write a rollback log for a transaction. It is not used
43767 ** when opening a hot journal file to roll it back.
43769 ** If the journal file is already open (as it may be in exclusive mode),
43770 ** then this function just writes a journal header to the start of the
43771 ** already open file.
43773 ** Whether or not the journal file is opened by this function, the
43774 ** Pager.pInJournal bitvec structure is allocated.
43776 ** Return SQLITE_OK if everything is successful. Otherwise, return
43777 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
43778 ** an IO error code if opening or writing the journal file fails.
43780 static int pager_open_journal(Pager *pPager){
43781 int rc = SQLITE_OK; /* Return code */
43782 sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
43784 assert( pPager->eState==PAGER_WRITER_LOCKED );
43785 assert( assert_pager_state(pPager) );
43786 assert( pPager->pInJournal==0 );
43788 /* If already in the error state, this function is a no-op. But on
43789 ** the other hand, this routine is never called if we are already in
43790 ** an error state. */
43791 if( NEVER(pPager->errCode) ) return pPager->errCode;
43793 if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
43794 pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
43795 if( pPager->pInJournal==0 ){
43796 return SQLITE_NOMEM;
43799 /* Open the journal file if it is not already open. */
43800 if( !isOpen(pPager->jfd) ){
43801 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
43802 sqlite3MemJournalOpen(pPager->jfd);
43803 }else{
43804 const int flags = /* VFS flags to open journal file */
43805 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
43806 (pPager->tempFile ?
43807 (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
43808 (SQLITE_OPEN_MAIN_JOURNAL)
43810 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43811 rc = sqlite3JournalOpen(
43812 pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
43814 #else
43815 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
43816 #endif
43818 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
43822 /* Write the first journal header to the journal file and open
43823 ** the sub-journal if necessary.
43825 if( rc==SQLITE_OK ){
43826 /* TODO: Check if all of these are really required. */
43827 pPager->nRec = 0;
43828 pPager->journalOff = 0;
43829 pPager->setMaster = 0;
43830 pPager->journalHdr = 0;
43831 rc = writeJournalHdr(pPager);
43835 if( rc!=SQLITE_OK ){
43836 sqlite3BitvecDestroy(pPager->pInJournal);
43837 pPager->pInJournal = 0;
43838 }else{
43839 assert( pPager->eState==PAGER_WRITER_LOCKED );
43840 pPager->eState = PAGER_WRITER_CACHEMOD;
43843 return rc;
43847 ** Begin a write-transaction on the specified pager object. If a
43848 ** write-transaction has already been opened, this function is a no-op.
43850 ** If the exFlag argument is false, then acquire at least a RESERVED
43851 ** lock on the database file. If exFlag is true, then acquire at least
43852 ** an EXCLUSIVE lock. If such a lock is already held, no locking
43853 ** functions need be called.
43855 ** If the subjInMemory argument is non-zero, then any sub-journal opened
43856 ** within this transaction will be opened as an in-memory file. This
43857 ** has no effect if the sub-journal is already opened (as it may be when
43858 ** running in exclusive mode) or if the transaction does not require a
43859 ** sub-journal. If the subjInMemory argument is zero, then any required
43860 ** sub-journal is implemented in-memory if pPager is an in-memory database,
43861 ** or using a temporary file otherwise.
43863 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
43864 int rc = SQLITE_OK;
43866 if( pPager->errCode ) return pPager->errCode;
43867 assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
43868 pPager->subjInMemory = (u8)subjInMemory;
43870 if( ALWAYS(pPager->eState==PAGER_READER) ){
43871 assert( pPager->pInJournal==0 );
43873 if( pagerUseWal(pPager) ){
43874 /* If the pager is configured to use locking_mode=exclusive, and an
43875 ** exclusive lock on the database is not already held, obtain it now.
43877 if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
43878 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43879 if( rc!=SQLITE_OK ){
43880 return rc;
43882 sqlite3WalExclusiveMode(pPager->pWal, 1);
43885 /* Grab the write lock on the log file. If successful, upgrade to
43886 ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
43887 ** The busy-handler is not invoked if another connection already
43888 ** holds the write-lock. If possible, the upper layer will call it.
43890 rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
43891 }else{
43892 /* Obtain a RESERVED lock on the database file. If the exFlag parameter
43893 ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
43894 ** busy-handler callback can be used when upgrading to the EXCLUSIVE
43895 ** lock, but not when obtaining the RESERVED lock.
43897 rc = pagerLockDb(pPager, RESERVED_LOCK);
43898 if( rc==SQLITE_OK && exFlag ){
43899 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
43903 if( rc==SQLITE_OK ){
43904 /* Change to WRITER_LOCKED state.
43906 ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
43907 ** when it has an open transaction, but never to DBMOD or FINISHED.
43908 ** This is because in those states the code to roll back savepoint
43909 ** transactions may copy data from the sub-journal into the database
43910 ** file as well as into the page cache. Which would be incorrect in
43911 ** WAL mode.
43913 pPager->eState = PAGER_WRITER_LOCKED;
43914 pPager->dbHintSize = pPager->dbSize;
43915 pPager->dbFileSize = pPager->dbSize;
43916 pPager->dbOrigSize = pPager->dbSize;
43917 pPager->journalOff = 0;
43920 assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
43921 assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
43922 assert( assert_pager_state(pPager) );
43925 PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
43926 return rc;
43930 ** Mark a single data page as writeable. The page is written into the
43931 ** main journal or sub-journal as required. If the page is written into
43932 ** one of the journals, the corresponding bit is set in the
43933 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
43934 ** of any open savepoints as appropriate.
43936 static int pager_write(PgHdr *pPg){
43937 void *pData = pPg->pData;
43938 Pager *pPager = pPg->pPager;
43939 int rc = SQLITE_OK;
43941 /* This routine is not called unless a write-transaction has already
43942 ** been started. The journal file may or may not be open at this point.
43943 ** It is never called in the ERROR state.
43945 assert( pPager->eState==PAGER_WRITER_LOCKED
43946 || pPager->eState==PAGER_WRITER_CACHEMOD
43947 || pPager->eState==PAGER_WRITER_DBMOD
43949 assert( assert_pager_state(pPager) );
43951 /* If an error has been previously detected, report the same error
43952 ** again. This should not happen, but the check provides robustness. */
43953 if( NEVER(pPager->errCode) ) return pPager->errCode;
43955 /* Higher-level routines never call this function if database is not
43956 ** writable. But check anyway, just for robustness. */
43957 if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
43959 CHECK_PAGE(pPg);
43961 /* The journal file needs to be opened. Higher level routines have already
43962 ** obtained the necessary locks to begin the write-transaction, but the
43963 ** rollback journal might not yet be open. Open it now if this is the case.
43965 ** This is done before calling sqlite3PcacheMakeDirty() on the page.
43966 ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
43967 ** an error might occur and the pager would end up in WRITER_LOCKED state
43968 ** with pages marked as dirty in the cache.
43970 if( pPager->eState==PAGER_WRITER_LOCKED ){
43971 rc = pager_open_journal(pPager);
43972 if( rc!=SQLITE_OK ) return rc;
43974 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
43975 assert( assert_pager_state(pPager) );
43977 /* Mark the page as dirty. If the page has already been written
43978 ** to the journal then we can return right away.
43980 sqlite3PcacheMakeDirty(pPg);
43981 if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
43982 assert( !pagerUseWal(pPager) );
43983 }else{
43985 /* The transaction journal now exists and we have a RESERVED or an
43986 ** EXCLUSIVE lock on the main database file. Write the current page to
43987 ** the transaction journal if it is not there already.
43989 if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
43990 assert( pagerUseWal(pPager)==0 );
43991 if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
43992 u32 cksum;
43993 char *pData2;
43994 i64 iOff = pPager->journalOff;
43996 /* We should never write to the journal file the page that
43997 ** contains the database locks. The following assert verifies
43998 ** that we do not. */
43999 assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
44001 assert( pPager->journalHdr<=pPager->journalOff );
44002 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
44003 cksum = pager_cksum(pPager, (u8*)pData2);
44005 /* Even if an IO or diskfull error occurs while journalling the
44006 ** page in the block above, set the need-sync flag for the page.
44007 ** Otherwise, when the transaction is rolled back, the logic in
44008 ** playback_one_page() will think that the page needs to be restored
44009 ** in the database file. And if an IO error occurs while doing so,
44010 ** then corruption may follow.
44012 pPg->flags |= PGHDR_NEED_SYNC;
44014 rc = write32bits(pPager->jfd, iOff, pPg->pgno);
44015 if( rc!=SQLITE_OK ) return rc;
44016 rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
44017 if( rc!=SQLITE_OK ) return rc;
44018 rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
44019 if( rc!=SQLITE_OK ) return rc;
44021 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
44022 pPager->journalOff, pPager->pageSize));
44023 PAGER_INCR(sqlite3_pager_writej_count);
44024 PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
44025 PAGERID(pPager), pPg->pgno,
44026 ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
44028 pPager->journalOff += 8 + pPager->pageSize;
44029 pPager->nRec++;
44030 assert( pPager->pInJournal!=0 );
44031 rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
44032 testcase( rc==SQLITE_NOMEM );
44033 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
44034 rc |= addToSavepointBitvecs(pPager, pPg->pgno);
44035 if( rc!=SQLITE_OK ){
44036 assert( rc==SQLITE_NOMEM );
44037 return rc;
44039 }else{
44040 if( pPager->eState!=PAGER_WRITER_DBMOD ){
44041 pPg->flags |= PGHDR_NEED_SYNC;
44043 PAGERTRACE(("APPEND %d page %d needSync=%d\n",
44044 PAGERID(pPager), pPg->pgno,
44045 ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
44049 /* If the statement journal is open and the page is not in it,
44050 ** then write the current page to the statement journal. Note that
44051 ** the statement journal format differs from the standard journal format
44052 ** in that it omits the checksums and the header.
44054 if( subjRequiresPage(pPg) ){
44055 rc = subjournalPage(pPg);
44059 /* Update the database size and return.
44061 if( pPager->dbSize<pPg->pgno ){
44062 pPager->dbSize = pPg->pgno;
44064 return rc;
44068 ** Mark a data page as writeable. This routine must be called before
44069 ** making changes to a page. The caller must check the return value
44070 ** of this function and be careful not to change any page data unless
44071 ** this routine returns SQLITE_OK.
44073 ** The difference between this function and pager_write() is that this
44074 ** function also deals with the special case where 2 or more pages
44075 ** fit on a single disk sector. In this case all co-resident pages
44076 ** must have been written to the journal file before returning.
44078 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
44079 ** as appropriate. Otherwise, SQLITE_OK.
44081 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
44082 int rc = SQLITE_OK;
44084 PgHdr *pPg = pDbPage;
44085 Pager *pPager = pPg->pPager;
44086 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
44088 assert( (pPg->flags & PGHDR_MMAP)==0 );
44089 assert( pPager->eState>=PAGER_WRITER_LOCKED );
44090 assert( pPager->eState!=PAGER_ERROR );
44091 assert( assert_pager_state(pPager) );
44093 if( nPagePerSector>1 ){
44094 Pgno nPageCount; /* Total number of pages in database file */
44095 Pgno pg1; /* First page of the sector pPg is located on. */
44096 int nPage = 0; /* Number of pages starting at pg1 to journal */
44097 int ii; /* Loop counter */
44098 int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
44100 /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
44101 ** a journal header to be written between the pages journaled by
44102 ** this function.
44104 assert( !MEMDB );
44105 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
44106 pPager->doNotSpill |= SPILLFLAG_NOSYNC;
44108 /* This trick assumes that both the page-size and sector-size are
44109 ** an integer power of 2. It sets variable pg1 to the identifier
44110 ** of the first page of the sector pPg is located on.
44112 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
44114 nPageCount = pPager->dbSize;
44115 if( pPg->pgno>nPageCount ){
44116 nPage = (pPg->pgno - pg1)+1;
44117 }else if( (pg1+nPagePerSector-1)>nPageCount ){
44118 nPage = nPageCount+1-pg1;
44119 }else{
44120 nPage = nPagePerSector;
44122 assert(nPage>0);
44123 assert(pg1<=pPg->pgno);
44124 assert((pg1+nPage)>pPg->pgno);
44126 for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
44127 Pgno pg = pg1+ii;
44128 PgHdr *pPage;
44129 if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
44130 if( pg!=PAGER_MJ_PGNO(pPager) ){
44131 rc = sqlite3PagerGet(pPager, pg, &pPage);
44132 if( rc==SQLITE_OK ){
44133 rc = pager_write(pPage);
44134 if( pPage->flags&PGHDR_NEED_SYNC ){
44135 needSync = 1;
44137 sqlite3PagerUnref(pPage);
44140 }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
44141 if( pPage->flags&PGHDR_NEED_SYNC ){
44142 needSync = 1;
44144 sqlite3PagerUnref(pPage);
44148 /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
44149 ** starting at pg1, then it needs to be set for all of them. Because
44150 ** writing to any of these nPage pages may damage the others, the
44151 ** journal file must contain sync()ed copies of all of them
44152 ** before any of them can be written out to the database file.
44154 if( rc==SQLITE_OK && needSync ){
44155 assert( !MEMDB );
44156 for(ii=0; ii<nPage; ii++){
44157 PgHdr *pPage = pager_lookup(pPager, pg1+ii);
44158 if( pPage ){
44159 pPage->flags |= PGHDR_NEED_SYNC;
44160 sqlite3PagerUnref(pPage);
44165 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
44166 pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
44167 }else{
44168 rc = pager_write(pDbPage);
44170 return rc;
44174 ** Return TRUE if the page given in the argument was previously passed
44175 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
44176 ** to change the content of the page.
44178 #ifndef NDEBUG
44179 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
44180 return pPg->flags&PGHDR_DIRTY;
44182 #endif
44185 ** A call to this routine tells the pager that it is not necessary to
44186 ** write the information on page pPg back to the disk, even though
44187 ** that page might be marked as dirty. This happens, for example, when
44188 ** the page has been added as a leaf of the freelist and so its
44189 ** content no longer matters.
44191 ** The overlying software layer calls this routine when all of the data
44192 ** on the given page is unused. The pager marks the page as clean so
44193 ** that it does not get written to disk.
44195 ** Tests show that this optimization can quadruple the speed of large
44196 ** DELETE operations.
44198 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
44199 Pager *pPager = pPg->pPager;
44200 if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
44201 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
44202 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
44203 pPg->flags |= PGHDR_DONT_WRITE;
44204 pager_set_pagehash(pPg);
44209 ** This routine is called to increment the value of the database file
44210 ** change-counter, stored as a 4-byte big-endian integer starting at
44211 ** byte offset 24 of the pager file. The secondary change counter at
44212 ** 92 is also updated, as is the SQLite version number at offset 96.
44214 ** But this only happens if the pPager->changeCountDone flag is false.
44215 ** To avoid excess churning of page 1, the update only happens once.
44216 ** See also the pager_write_changecounter() routine that does an
44217 ** unconditional update of the change counters.
44219 ** If the isDirectMode flag is zero, then this is done by calling
44220 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
44221 ** page data. In this case the file will be updated when the current
44222 ** transaction is committed.
44224 ** The isDirectMode flag may only be non-zero if the library was compiled
44225 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
44226 ** if isDirect is non-zero, then the database file is updated directly
44227 ** by writing an updated version of page 1 using a call to the
44228 ** sqlite3OsWrite() function.
44230 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
44231 int rc = SQLITE_OK;
44233 assert( pPager->eState==PAGER_WRITER_CACHEMOD
44234 || pPager->eState==PAGER_WRITER_DBMOD
44236 assert( assert_pager_state(pPager) );
44238 /* Declare and initialize constant integer 'isDirect'. If the
44239 ** atomic-write optimization is enabled in this build, then isDirect
44240 ** is initialized to the value passed as the isDirectMode parameter
44241 ** to this function. Otherwise, it is always set to zero.
44243 ** The idea is that if the atomic-write optimization is not
44244 ** enabled at compile time, the compiler can omit the tests of
44245 ** 'isDirect' below, as well as the block enclosed in the
44246 ** "if( isDirect )" condition.
44248 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
44249 # define DIRECT_MODE 0
44250 assert( isDirectMode==0 );
44251 UNUSED_PARAMETER(isDirectMode);
44252 #else
44253 # define DIRECT_MODE isDirectMode
44254 #endif
44256 if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
44257 PgHdr *pPgHdr; /* Reference to page 1 */
44259 assert( !pPager->tempFile && isOpen(pPager->fd) );
44261 /* Open page 1 of the file for writing. */
44262 rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
44263 assert( pPgHdr==0 || rc==SQLITE_OK );
44265 /* If page one was fetched successfully, and this function is not
44266 ** operating in direct-mode, make page 1 writable. When not in
44267 ** direct mode, page 1 is always held in cache and hence the PagerGet()
44268 ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
44270 if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
44271 rc = sqlite3PagerWrite(pPgHdr);
44274 if( rc==SQLITE_OK ){
44275 /* Actually do the update of the change counter */
44276 pager_write_changecounter(pPgHdr);
44278 /* If running in direct mode, write the contents of page 1 to the file. */
44279 if( DIRECT_MODE ){
44280 const void *zBuf;
44281 assert( pPager->dbFileSize>0 );
44282 CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
44283 if( rc==SQLITE_OK ){
44284 rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
44285 pPager->aStat[PAGER_STAT_WRITE]++;
44287 if( rc==SQLITE_OK ){
44288 /* Update the pager's copy of the change-counter. Otherwise, the
44289 ** next time a read transaction is opened the cache will be
44290 ** flushed (as the change-counter values will not match). */
44291 const void *pCopy = (const void *)&((const char *)zBuf)[24];
44292 memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
44293 pPager->changeCountDone = 1;
44295 }else{
44296 pPager->changeCountDone = 1;
44300 /* Release the page reference. */
44301 sqlite3PagerUnref(pPgHdr);
44303 return rc;
44307 ** Sync the database file to disk. This is a no-op for in-memory databases
44308 ** or pages with the Pager.noSync flag set.
44310 ** If successful, or if called on a pager for which it is a no-op, this
44311 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
44313 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
44314 int rc = SQLITE_OK;
44315 if( !pPager->noSync ){
44316 assert( !MEMDB );
44317 rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
44318 }else if( isOpen(pPager->fd) ){
44319 assert( !MEMDB );
44320 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
44321 if( rc==SQLITE_NOTFOUND ){
44322 rc = SQLITE_OK;
44325 return rc;
44329 ** This function may only be called while a write-transaction is active in
44330 ** rollback. If the connection is in WAL mode, this call is a no-op.
44331 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
44332 ** the database file, an attempt is made to obtain one.
44334 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
44335 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
44336 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
44337 ** returned.
44339 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
44340 int rc = SQLITE_OK;
44341 assert( pPager->eState==PAGER_WRITER_CACHEMOD
44342 || pPager->eState==PAGER_WRITER_DBMOD
44343 || pPager->eState==PAGER_WRITER_LOCKED
44345 assert( assert_pager_state(pPager) );
44346 if( 0==pagerUseWal(pPager) ){
44347 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
44349 return rc;
44353 ** Sync the database file for the pager pPager. zMaster points to the name
44354 ** of a master journal file that should be written into the individual
44355 ** journal file. zMaster may be NULL, which is interpreted as no master
44356 ** journal (a single database transaction).
44358 ** This routine ensures that:
44360 ** * The database file change-counter is updated,
44361 ** * the journal is synced (unless the atomic-write optimization is used),
44362 ** * all dirty pages are written to the database file,
44363 ** * the database file is truncated (if required), and
44364 ** * the database file synced.
44366 ** The only thing that remains to commit the transaction is to finalize
44367 ** (delete, truncate or zero the first part of) the journal file (or
44368 ** delete the master journal file if specified).
44370 ** Note that if zMaster==NULL, this does not overwrite a previous value
44371 ** passed to an sqlite3PagerCommitPhaseOne() call.
44373 ** If the final parameter - noSync - is true, then the database file itself
44374 ** is not synced. The caller must call sqlite3PagerSync() directly to
44375 ** sync the database file before calling CommitPhaseTwo() to delete the
44376 ** journal file in this case.
44378 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
44379 Pager *pPager, /* Pager object */
44380 const char *zMaster, /* If not NULL, the master journal name */
44381 int noSync /* True to omit the xSync on the db file */
44383 int rc = SQLITE_OK; /* Return code */
44385 assert( pPager->eState==PAGER_WRITER_LOCKED
44386 || pPager->eState==PAGER_WRITER_CACHEMOD
44387 || pPager->eState==PAGER_WRITER_DBMOD
44388 || pPager->eState==PAGER_ERROR
44390 assert( assert_pager_state(pPager) );
44392 /* If a prior error occurred, report that error again. */
44393 if( NEVER(pPager->errCode) ) return pPager->errCode;
44395 PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
44396 pPager->zFilename, zMaster, pPager->dbSize));
44398 /* If no database changes have been made, return early. */
44399 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
44401 if( MEMDB ){
44402 /* If this is an in-memory db, or no pages have been written to, or this
44403 ** function has already been called, it is mostly a no-op. However, any
44404 ** backup in progress needs to be restarted.
44406 sqlite3BackupRestart(pPager->pBackup);
44407 }else{
44408 if( pagerUseWal(pPager) ){
44409 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
44410 PgHdr *pPageOne = 0;
44411 if( pList==0 ){
44412 /* Must have at least one page for the WAL commit flag.
44413 ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
44414 rc = sqlite3PagerGet(pPager, 1, &pPageOne);
44415 pList = pPageOne;
44416 pList->pDirty = 0;
44418 assert( rc==SQLITE_OK );
44419 if( ALWAYS(pList) ){
44420 rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
44422 sqlite3PagerUnref(pPageOne);
44423 if( rc==SQLITE_OK ){
44424 sqlite3PcacheCleanAll(pPager->pPCache);
44426 }else{
44427 /* The following block updates the change-counter. Exactly how it
44428 ** does this depends on whether or not the atomic-update optimization
44429 ** was enabled at compile time, and if this transaction meets the
44430 ** runtime criteria to use the operation:
44432 ** * The file-system supports the atomic-write property for
44433 ** blocks of size page-size, and
44434 ** * This commit is not part of a multi-file transaction, and
44435 ** * Exactly one page has been modified and store in the journal file.
44437 ** If the optimization was not enabled at compile time, then the
44438 ** pager_incr_changecounter() function is called to update the change
44439 ** counter in 'indirect-mode'. If the optimization is compiled in but
44440 ** is not applicable to this transaction, call sqlite3JournalCreate()
44441 ** to make sure the journal file has actually been created, then call
44442 ** pager_incr_changecounter() to update the change-counter in indirect
44443 ** mode.
44445 ** Otherwise, if the optimization is both enabled and applicable,
44446 ** then call pager_incr_changecounter() to update the change-counter
44447 ** in 'direct' mode. In this case the journal file will never be
44448 ** created for this transaction.
44450 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
44451 PgHdr *pPg;
44452 assert( isOpen(pPager->jfd)
44453 || pPager->journalMode==PAGER_JOURNALMODE_OFF
44454 || pPager->journalMode==PAGER_JOURNALMODE_WAL
44456 if( !zMaster && isOpen(pPager->jfd)
44457 && pPager->journalOff==jrnlBufferSize(pPager)
44458 && pPager->dbSize>=pPager->dbOrigSize
44459 && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
44461 /* Update the db file change counter via the direct-write method. The
44462 ** following call will modify the in-memory representation of page 1
44463 ** to include the updated change counter and then write page 1
44464 ** directly to the database file. Because of the atomic-write
44465 ** property of the host file-system, this is safe.
44467 rc = pager_incr_changecounter(pPager, 1);
44468 }else{
44469 rc = sqlite3JournalCreate(pPager->jfd);
44470 if( rc==SQLITE_OK ){
44471 rc = pager_incr_changecounter(pPager, 0);
44474 #else
44475 rc = pager_incr_changecounter(pPager, 0);
44476 #endif
44477 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44479 /* Write the master journal name into the journal file. If a master
44480 ** journal file name has already been written to the journal file,
44481 ** or if zMaster is NULL (no master journal), then this call is a no-op.
44483 rc = writeMasterJournal(pPager, zMaster);
44484 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44486 /* Sync the journal file and write all dirty pages to the database.
44487 ** If the atomic-update optimization is being used, this sync will not
44488 ** create the journal file or perform any real IO.
44490 ** Because the change-counter page was just modified, unless the
44491 ** atomic-update optimization is used it is almost certain that the
44492 ** journal requires a sync here. However, in locking_mode=exclusive
44493 ** on a system under memory pressure it is just possible that this is
44494 ** not the case. In this case it is likely enough that the redundant
44495 ** xSync() call will be changed to a no-op by the OS anyhow.
44497 rc = syncJournal(pPager, 0);
44498 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44500 rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
44501 if( rc!=SQLITE_OK ){
44502 assert( rc!=SQLITE_IOERR_BLOCKED );
44503 goto commit_phase_one_exit;
44505 sqlite3PcacheCleanAll(pPager->pPCache);
44507 /* If the file on disk is smaller than the database image, use
44508 ** pager_truncate to grow the file here. This can happen if the database
44509 ** image was extended as part of the current transaction and then the
44510 ** last page in the db image moved to the free-list. In this case the
44511 ** last page is never written out to disk, leaving the database file
44512 ** undersized. Fix this now if it is the case. */
44513 if( pPager->dbSize>pPager->dbFileSize ){
44514 Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
44515 assert( pPager->eState==PAGER_WRITER_DBMOD );
44516 rc = pager_truncate(pPager, nNew);
44517 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44520 /* Finally, sync the database file. */
44521 if( !noSync ){
44522 rc = sqlite3PagerSync(pPager);
44524 IOTRACE(("DBSYNC %p\n", pPager))
44528 commit_phase_one_exit:
44529 if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
44530 pPager->eState = PAGER_WRITER_FINISHED;
44532 return rc;
44537 ** When this function is called, the database file has been completely
44538 ** updated to reflect the changes made by the current transaction and
44539 ** synced to disk. The journal file still exists in the file-system
44540 ** though, and if a failure occurs at this point it will eventually
44541 ** be used as a hot-journal and the current transaction rolled back.
44543 ** This function finalizes the journal file, either by deleting,
44544 ** truncating or partially zeroing it, so that it cannot be used
44545 ** for hot-journal rollback. Once this is done the transaction is
44546 ** irrevocably committed.
44548 ** If an error occurs, an IO error code is returned and the pager
44549 ** moves into the error state. Otherwise, SQLITE_OK is returned.
44551 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
44552 int rc = SQLITE_OK; /* Return code */
44554 /* This routine should not be called if a prior error has occurred.
44555 ** But if (due to a coding error elsewhere in the system) it does get
44556 ** called, just return the same error code without doing anything. */
44557 if( NEVER(pPager->errCode) ) return pPager->errCode;
44559 assert( pPager->eState==PAGER_WRITER_LOCKED
44560 || pPager->eState==PAGER_WRITER_FINISHED
44561 || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
44563 assert( assert_pager_state(pPager) );
44565 /* An optimization. If the database was not actually modified during
44566 ** this transaction, the pager is running in exclusive-mode and is
44567 ** using persistent journals, then this function is a no-op.
44569 ** The start of the journal file currently contains a single journal
44570 ** header with the nRec field set to 0. If such a journal is used as
44571 ** a hot-journal during hot-journal rollback, 0 changes will be made
44572 ** to the database file. So there is no need to zero the journal
44573 ** header. Since the pager is in exclusive mode, there is no need
44574 ** to drop any locks either.
44576 if( pPager->eState==PAGER_WRITER_LOCKED
44577 && pPager->exclusiveMode
44578 && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
44580 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
44581 pPager->eState = PAGER_READER;
44582 return SQLITE_OK;
44585 PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
44586 rc = pager_end_transaction(pPager, pPager->setMaster, 1);
44587 return pager_error(pPager, rc);
44591 ** If a write transaction is open, then all changes made within the
44592 ** transaction are reverted and the current write-transaction is closed.
44593 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
44594 ** state if an error occurs.
44596 ** If the pager is already in PAGER_ERROR state when this function is called,
44597 ** it returns Pager.errCode immediately. No work is performed in this case.
44599 ** Otherwise, in rollback mode, this function performs two functions:
44601 ** 1) It rolls back the journal file, restoring all database file and
44602 ** in-memory cache pages to the state they were in when the transaction
44603 ** was opened, and
44605 ** 2) It finalizes the journal file, so that it is not used for hot
44606 ** rollback at any point in the future.
44608 ** Finalization of the journal file (task 2) is only performed if the
44609 ** rollback is successful.
44611 ** In WAL mode, all cache-entries containing data modified within the
44612 ** current transaction are either expelled from the cache or reverted to
44613 ** their pre-transaction state by re-reading data from the database or
44614 ** WAL files. The WAL transaction is then closed.
44616 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
44617 int rc = SQLITE_OK; /* Return code */
44618 PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
44620 /* PagerRollback() is a no-op if called in READER or OPEN state. If
44621 ** the pager is already in the ERROR state, the rollback is not
44622 ** attempted here. Instead, the error code is returned to the caller.
44624 assert( assert_pager_state(pPager) );
44625 if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
44626 if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
44628 if( pagerUseWal(pPager) ){
44629 int rc2;
44630 rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
44631 rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
44632 if( rc==SQLITE_OK ) rc = rc2;
44633 }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
44634 int eState = pPager->eState;
44635 rc = pager_end_transaction(pPager, 0, 0);
44636 if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
44637 /* This can happen using journal_mode=off. Move the pager to the error
44638 ** state to indicate that the contents of the cache may not be trusted.
44639 ** Any active readers will get SQLITE_ABORT.
44641 pPager->errCode = SQLITE_ABORT;
44642 pPager->eState = PAGER_ERROR;
44643 return rc;
44645 }else{
44646 rc = pager_playback(pPager, 0);
44649 assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
44650 assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
44651 || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
44653 /* If an error occurs during a ROLLBACK, we can no longer trust the pager
44654 ** cache. So call pager_error() on the way out to make any error persistent.
44656 return pager_error(pPager, rc);
44660 ** Return TRUE if the database file is opened read-only. Return FALSE
44661 ** if the database is (in theory) writable.
44663 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
44664 return pPager->readOnly;
44668 ** Return the number of references to the pager.
44670 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
44671 return sqlite3PcacheRefCount(pPager->pPCache);
44675 ** Return the approximate number of bytes of memory currently
44676 ** used by the pager and its associated cache.
44678 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
44679 int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
44680 + 5*sizeof(void*);
44681 return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
44682 + sqlite3MallocSize(pPager)
44683 + pPager->pageSize;
44687 ** Return the number of references to the specified page.
44689 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
44690 return sqlite3PcachePageRefcount(pPage);
44693 #ifdef SQLITE_TEST
44695 ** This routine is used for testing and analysis only.
44697 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
44698 static int a[11];
44699 a[0] = sqlite3PcacheRefCount(pPager->pPCache);
44700 a[1] = sqlite3PcachePagecount(pPager->pPCache);
44701 a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
44702 a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
44703 a[4] = pPager->eState;
44704 a[5] = pPager->errCode;
44705 a[6] = pPager->aStat[PAGER_STAT_HIT];
44706 a[7] = pPager->aStat[PAGER_STAT_MISS];
44707 a[8] = 0; /* Used to be pPager->nOvfl */
44708 a[9] = pPager->nRead;
44709 a[10] = pPager->aStat[PAGER_STAT_WRITE];
44710 return a;
44712 #endif
44715 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
44716 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
44717 ** current cache hit or miss count, according to the value of eStat. If the
44718 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
44719 ** returning.
44721 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
44723 assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
44724 || eStat==SQLITE_DBSTATUS_CACHE_MISS
44725 || eStat==SQLITE_DBSTATUS_CACHE_WRITE
44728 assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
44729 assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
44730 assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
44732 *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
44733 if( reset ){
44734 pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
44739 ** Return true if this is an in-memory pager.
44741 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
44742 return MEMDB;
44746 ** Check that there are at least nSavepoint savepoints open. If there are
44747 ** currently less than nSavepoints open, then open one or more savepoints
44748 ** to make up the difference. If the number of savepoints is already
44749 ** equal to nSavepoint, then this function is a no-op.
44751 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
44752 ** occurs while opening the sub-journal file, then an IO error code is
44753 ** returned. Otherwise, SQLITE_OK.
44755 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
44756 int rc = SQLITE_OK; /* Return code */
44757 int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
44759 assert( pPager->eState>=PAGER_WRITER_LOCKED );
44760 assert( assert_pager_state(pPager) );
44762 if( nSavepoint>nCurrent && pPager->useJournal ){
44763 int ii; /* Iterator variable */
44764 PagerSavepoint *aNew; /* New Pager.aSavepoint array */
44766 /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
44767 ** if the allocation fails. Otherwise, zero the new portion in case a
44768 ** malloc failure occurs while populating it in the for(...) loop below.
44770 aNew = (PagerSavepoint *)sqlite3Realloc(
44771 pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
44773 if( !aNew ){
44774 return SQLITE_NOMEM;
44776 memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
44777 pPager->aSavepoint = aNew;
44779 /* Populate the PagerSavepoint structures just allocated. */
44780 for(ii=nCurrent; ii<nSavepoint; ii++){
44781 aNew[ii].nOrig = pPager->dbSize;
44782 if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
44783 aNew[ii].iOffset = pPager->journalOff;
44784 }else{
44785 aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
44787 aNew[ii].iSubRec = pPager->nSubRec;
44788 aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
44789 if( !aNew[ii].pInSavepoint ){
44790 return SQLITE_NOMEM;
44792 if( pagerUseWal(pPager) ){
44793 sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
44795 pPager->nSavepoint = ii+1;
44797 assert( pPager->nSavepoint==nSavepoint );
44798 assertTruncateConstraint(pPager);
44801 return rc;
44805 ** This function is called to rollback or release (commit) a savepoint.
44806 ** The savepoint to release or rollback need not be the most recently
44807 ** created savepoint.
44809 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
44810 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
44811 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
44812 ** that have occurred since the specified savepoint was created.
44814 ** The savepoint to rollback or release is identified by parameter
44815 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
44816 ** (the first created). A value of (Pager.nSavepoint-1) means operate
44817 ** on the most recently created savepoint. If iSavepoint is greater than
44818 ** (Pager.nSavepoint-1), then this function is a no-op.
44820 ** If a negative value is passed to this function, then the current
44821 ** transaction is rolled back. This is different to calling
44822 ** sqlite3PagerRollback() because this function does not terminate
44823 ** the transaction or unlock the database, it just restores the
44824 ** contents of the database to its original state.
44826 ** In any case, all savepoints with an index greater than iSavepoint
44827 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
44828 ** then savepoint iSavepoint is also destroyed.
44830 ** This function may return SQLITE_NOMEM if a memory allocation fails,
44831 ** or an IO error code if an IO error occurs while rolling back a
44832 ** savepoint. If no errors occur, SQLITE_OK is returned.
44834 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
44835 int rc = pPager->errCode; /* Return code */
44837 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
44838 assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
44840 if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
44841 int ii; /* Iterator variable */
44842 int nNew; /* Number of remaining savepoints after this op. */
44844 /* Figure out how many savepoints will still be active after this
44845 ** operation. Store this value in nNew. Then free resources associated
44846 ** with any savepoints that are destroyed by this operation.
44848 nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
44849 for(ii=nNew; ii<pPager->nSavepoint; ii++){
44850 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
44852 pPager->nSavepoint = nNew;
44854 /* If this is a release of the outermost savepoint, truncate
44855 ** the sub-journal to zero bytes in size. */
44856 if( op==SAVEPOINT_RELEASE ){
44857 if( nNew==0 && isOpen(pPager->sjfd) ){
44858 /* Only truncate if it is an in-memory sub-journal. */
44859 if( sqlite3IsMemJournal(pPager->sjfd) ){
44860 rc = sqlite3OsTruncate(pPager->sjfd, 0);
44861 assert( rc==SQLITE_OK );
44863 pPager->nSubRec = 0;
44866 /* Else this is a rollback operation, playback the specified savepoint.
44867 ** If this is a temp-file, it is possible that the journal file has
44868 ** not yet been opened. In this case there have been no changes to
44869 ** the database file, so the playback operation can be skipped.
44871 else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
44872 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
44873 rc = pagerPlaybackSavepoint(pPager, pSavepoint);
44874 assert(rc!=SQLITE_DONE);
44878 return rc;
44882 ** Return the full pathname of the database file.
44884 ** Except, if the pager is in-memory only, then return an empty string if
44885 ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
44886 ** used to report the filename to the user, for compatibility with legacy
44887 ** behavior. But when the Btree needs to know the filename for matching to
44888 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
44889 ** participate in shared-cache.
44891 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
44892 return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
44896 ** Return the VFS structure for the pager.
44898 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
44899 return pPager->pVfs;
44903 ** Return the file handle for the database file associated
44904 ** with the pager. This might return NULL if the file has
44905 ** not yet been opened.
44907 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
44908 return pPager->fd;
44912 ** Return the full pathname of the journal file.
44914 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
44915 return pPager->zJournal;
44919 ** Return true if fsync() calls are disabled for this pager. Return FALSE
44920 ** if fsync()s are executed normally.
44922 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
44923 return pPager->noSync;
44926 #ifdef SQLITE_HAS_CODEC
44928 ** Set or retrieve the codec for this pager
44930 SQLITE_PRIVATE void sqlite3PagerSetCodec(
44931 Pager *pPager,
44932 void *(*xCodec)(void*,void*,Pgno,int),
44933 void (*xCodecSizeChng)(void*,int,int),
44934 void (*xCodecFree)(void*),
44935 void *pCodec
44937 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
44938 pPager->xCodec = pPager->memDb ? 0 : xCodec;
44939 pPager->xCodecSizeChng = xCodecSizeChng;
44940 pPager->xCodecFree = xCodecFree;
44941 pPager->pCodec = pCodec;
44942 pagerReportSize(pPager);
44944 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
44945 return pPager->pCodec;
44949 ** This function is called by the wal module when writing page content
44950 ** into the log file.
44952 ** This function returns a pointer to a buffer containing the encrypted
44953 ** page content. If a malloc fails, this function may return NULL.
44955 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
44956 void *aData = 0;
44957 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
44958 return aData;
44962 ** Return the current pager state
44964 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
44965 return pPager->eState;
44967 #endif /* SQLITE_HAS_CODEC */
44969 #ifndef SQLITE_OMIT_AUTOVACUUM
44971 ** Move the page pPg to location pgno in the file.
44973 ** There must be no references to the page previously located at
44974 ** pgno (which we call pPgOld) though that page is allowed to be
44975 ** in cache. If the page previously located at pgno is not already
44976 ** in the rollback journal, it is not put there by by this routine.
44978 ** References to the page pPg remain valid. Updating any
44979 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
44980 ** allocated along with the page) is the responsibility of the caller.
44982 ** A transaction must be active when this routine is called. It used to be
44983 ** required that a statement transaction was not active, but this restriction
44984 ** has been removed (CREATE INDEX needs to move a page when a statement
44985 ** transaction is active).
44987 ** If the fourth argument, isCommit, is non-zero, then this page is being
44988 ** moved as part of a database reorganization just before the transaction
44989 ** is being committed. In this case, it is guaranteed that the database page
44990 ** pPg refers to will not be written to again within this transaction.
44992 ** This function may return SQLITE_NOMEM or an IO error code if an error
44993 ** occurs. Otherwise, it returns SQLITE_OK.
44995 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
44996 PgHdr *pPgOld; /* The page being overwritten. */
44997 Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
44998 int rc; /* Return code */
44999 Pgno origPgno; /* The original page number */
45001 assert( pPg->nRef>0 );
45002 assert( pPager->eState==PAGER_WRITER_CACHEMOD
45003 || pPager->eState==PAGER_WRITER_DBMOD
45005 assert( assert_pager_state(pPager) );
45007 /* In order to be able to rollback, an in-memory database must journal
45008 ** the page we are moving from.
45010 if( MEMDB ){
45011 rc = sqlite3PagerWrite(pPg);
45012 if( rc ) return rc;
45015 /* If the page being moved is dirty and has not been saved by the latest
45016 ** savepoint, then save the current contents of the page into the
45017 ** sub-journal now. This is required to handle the following scenario:
45019 ** BEGIN;
45020 ** <journal page X, then modify it in memory>
45021 ** SAVEPOINT one;
45022 ** <Move page X to location Y>
45023 ** ROLLBACK TO one;
45025 ** If page X were not written to the sub-journal here, it would not
45026 ** be possible to restore its contents when the "ROLLBACK TO one"
45027 ** statement were is processed.
45029 ** subjournalPage() may need to allocate space to store pPg->pgno into
45030 ** one or more savepoint bitvecs. This is the reason this function
45031 ** may return SQLITE_NOMEM.
45033 if( pPg->flags&PGHDR_DIRTY
45034 && subjRequiresPage(pPg)
45035 && SQLITE_OK!=(rc = subjournalPage(pPg))
45037 return rc;
45040 PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
45041 PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
45042 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
45044 /* If the journal needs to be sync()ed before page pPg->pgno can
45045 ** be written to, store pPg->pgno in local variable needSyncPgno.
45047 ** If the isCommit flag is set, there is no need to remember that
45048 ** the journal needs to be sync()ed before database page pPg->pgno
45049 ** can be written to. The caller has already promised not to write to it.
45051 if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
45052 needSyncPgno = pPg->pgno;
45053 assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
45054 pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
45055 assert( pPg->flags&PGHDR_DIRTY );
45058 /* If the cache contains a page with page-number pgno, remove it
45059 ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
45060 ** page pgno before the 'move' operation, it needs to be retained
45061 ** for the page moved there.
45063 pPg->flags &= ~PGHDR_NEED_SYNC;
45064 pPgOld = pager_lookup(pPager, pgno);
45065 assert( !pPgOld || pPgOld->nRef==1 );
45066 if( pPgOld ){
45067 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
45068 if( MEMDB ){
45069 /* Do not discard pages from an in-memory database since we might
45070 ** need to rollback later. Just move the page out of the way. */
45071 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
45072 }else{
45073 sqlite3PcacheDrop(pPgOld);
45077 origPgno = pPg->pgno;
45078 sqlite3PcacheMove(pPg, pgno);
45079 sqlite3PcacheMakeDirty(pPg);
45081 /* For an in-memory database, make sure the original page continues
45082 ** to exist, in case the transaction needs to roll back. Use pPgOld
45083 ** as the original page since it has already been allocated.
45085 if( MEMDB ){
45086 assert( pPgOld );
45087 sqlite3PcacheMove(pPgOld, origPgno);
45088 sqlite3PagerUnref(pPgOld);
45091 if( needSyncPgno ){
45092 /* If needSyncPgno is non-zero, then the journal file needs to be
45093 ** sync()ed before any data is written to database file page needSyncPgno.
45094 ** Currently, no such page exists in the page-cache and the
45095 ** "is journaled" bitvec flag has been set. This needs to be remedied by
45096 ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
45097 ** flag.
45099 ** If the attempt to load the page into the page-cache fails, (due
45100 ** to a malloc() or IO failure), clear the bit in the pInJournal[]
45101 ** array. Otherwise, if the page is loaded and written again in
45102 ** this transaction, it may be written to the database file before
45103 ** it is synced into the journal file. This way, it may end up in
45104 ** the journal file twice, but that is not a problem.
45106 PgHdr *pPgHdr;
45107 rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
45108 if( rc!=SQLITE_OK ){
45109 if( needSyncPgno<=pPager->dbOrigSize ){
45110 assert( pPager->pTmpSpace!=0 );
45111 sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
45113 return rc;
45115 pPgHdr->flags |= PGHDR_NEED_SYNC;
45116 sqlite3PcacheMakeDirty(pPgHdr);
45117 sqlite3PagerUnref(pPgHdr);
45120 return SQLITE_OK;
45122 #endif
45125 ** Return a pointer to the data for the specified page.
45127 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
45128 assert( pPg->nRef>0 || pPg->pPager->memDb );
45129 return pPg->pData;
45133 ** Return a pointer to the Pager.nExtra bytes of "extra" space
45134 ** allocated along with the specified page.
45136 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
45137 return pPg->pExtra;
45141 ** Get/set the locking-mode for this pager. Parameter eMode must be one
45142 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
45143 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
45144 ** the locking-mode is set to the value specified.
45146 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
45147 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
45148 ** locking-mode.
45150 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
45151 assert( eMode==PAGER_LOCKINGMODE_QUERY
45152 || eMode==PAGER_LOCKINGMODE_NORMAL
45153 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
45154 assert( PAGER_LOCKINGMODE_QUERY<0 );
45155 assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
45156 assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
45157 if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
45158 pPager->exclusiveMode = (u8)eMode;
45160 return (int)pPager->exclusiveMode;
45164 ** Set the journal-mode for this pager. Parameter eMode must be one of:
45166 ** PAGER_JOURNALMODE_DELETE
45167 ** PAGER_JOURNALMODE_TRUNCATE
45168 ** PAGER_JOURNALMODE_PERSIST
45169 ** PAGER_JOURNALMODE_OFF
45170 ** PAGER_JOURNALMODE_MEMORY
45171 ** PAGER_JOURNALMODE_WAL
45173 ** The journalmode is set to the value specified if the change is allowed.
45174 ** The change may be disallowed for the following reasons:
45176 ** * An in-memory database can only have its journal_mode set to _OFF
45177 ** or _MEMORY.
45179 ** * Temporary databases cannot have _WAL journalmode.
45181 ** The returned indicate the current (possibly updated) journal-mode.
45183 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
45184 u8 eOld = pPager->journalMode; /* Prior journalmode */
45186 #ifdef SQLITE_DEBUG
45187 /* The print_pager_state() routine is intended to be used by the debugger
45188 ** only. We invoke it once here to suppress a compiler warning. */
45189 print_pager_state(pPager);
45190 #endif
45193 /* The eMode parameter is always valid */
45194 assert( eMode==PAGER_JOURNALMODE_DELETE
45195 || eMode==PAGER_JOURNALMODE_TRUNCATE
45196 || eMode==PAGER_JOURNALMODE_PERSIST
45197 || eMode==PAGER_JOURNALMODE_OFF
45198 || eMode==PAGER_JOURNALMODE_WAL
45199 || eMode==PAGER_JOURNALMODE_MEMORY );
45201 /* This routine is only called from the OP_JournalMode opcode, and
45202 ** the logic there will never allow a temporary file to be changed
45203 ** to WAL mode.
45205 assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
45207 /* Do allow the journalmode of an in-memory database to be set to
45208 ** anything other than MEMORY or OFF
45210 if( MEMDB ){
45211 assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
45212 if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
45213 eMode = eOld;
45217 if( eMode!=eOld ){
45219 /* Change the journal mode. */
45220 assert( pPager->eState!=PAGER_ERROR );
45221 pPager->journalMode = (u8)eMode;
45223 /* When transistioning from TRUNCATE or PERSIST to any other journal
45224 ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
45225 ** delete the journal file.
45227 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
45228 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
45229 assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
45230 assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
45231 assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
45232 assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
45234 assert( isOpen(pPager->fd) || pPager->exclusiveMode );
45235 if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
45237 /* In this case we would like to delete the journal file. If it is
45238 ** not possible, then that is not a problem. Deleting the journal file
45239 ** here is an optimization only.
45241 ** Before deleting the journal file, obtain a RESERVED lock on the
45242 ** database file. This ensures that the journal file is not deleted
45243 ** while it is in use by some other client.
45245 sqlite3OsClose(pPager->jfd);
45246 if( pPager->eLock>=RESERVED_LOCK ){
45247 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45248 }else{
45249 int rc = SQLITE_OK;
45250 int state = pPager->eState;
45251 assert( state==PAGER_OPEN || state==PAGER_READER );
45252 if( state==PAGER_OPEN ){
45253 rc = sqlite3PagerSharedLock(pPager);
45255 if( pPager->eState==PAGER_READER ){
45256 assert( rc==SQLITE_OK );
45257 rc = pagerLockDb(pPager, RESERVED_LOCK);
45259 if( rc==SQLITE_OK ){
45260 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45262 if( rc==SQLITE_OK && state==PAGER_READER ){
45263 pagerUnlockDb(pPager, SHARED_LOCK);
45264 }else if( state==PAGER_OPEN ){
45265 pager_unlock(pPager);
45267 assert( state==pPager->eState );
45272 /* Return the new journal mode */
45273 return (int)pPager->journalMode;
45277 ** Return the current journal mode.
45279 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
45280 return (int)pPager->journalMode;
45284 ** Return TRUE if the pager is in a state where it is OK to change the
45285 ** journalmode. Journalmode changes can only happen when the database
45286 ** is unmodified.
45288 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
45289 assert( assert_pager_state(pPager) );
45290 if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
45291 if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
45292 return 1;
45296 ** Get/set the size-limit used for persistent journal files.
45298 ** Setting the size limit to -1 means no limit is enforced.
45299 ** An attempt to set a limit smaller than -1 is a no-op.
45301 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
45302 if( iLimit>=-1 ){
45303 pPager->journalSizeLimit = iLimit;
45304 sqlite3WalLimit(pPager->pWal, iLimit);
45306 return pPager->journalSizeLimit;
45310 ** Return a pointer to the pPager->pBackup variable. The backup module
45311 ** in backup.c maintains the content of this variable. This module
45312 ** uses it opaquely as an argument to sqlite3BackupRestart() and
45313 ** sqlite3BackupUpdate() only.
45315 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
45316 return &pPager->pBackup;
45319 #ifndef SQLITE_OMIT_VACUUM
45321 ** Unless this is an in-memory or temporary database, clear the pager cache.
45323 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
45324 if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
45326 #endif
45328 #ifndef SQLITE_OMIT_WAL
45330 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
45331 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
45332 ** or wal_blocking_checkpoint() API functions.
45334 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
45336 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
45337 int rc = SQLITE_OK;
45338 if( pPager->pWal ){
45339 rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
45340 pPager->xBusyHandler, pPager->pBusyHandlerArg,
45341 pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
45342 pnLog, pnCkpt
45345 return rc;
45348 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
45349 return sqlite3WalCallback(pPager->pWal);
45353 ** Return true if the underlying VFS for the given pager supports the
45354 ** primitives necessary for write-ahead logging.
45356 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
45357 const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
45358 return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
45362 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
45363 ** is obtained instead, immediately release it.
45365 static int pagerExclusiveLock(Pager *pPager){
45366 int rc; /* Return code */
45368 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
45369 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
45370 if( rc!=SQLITE_OK ){
45371 /* If the attempt to grab the exclusive lock failed, release the
45372 ** pending lock that may have been obtained instead. */
45373 pagerUnlockDb(pPager, SHARED_LOCK);
45376 return rc;
45380 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
45381 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
45382 ** lock on the database file and use heap-memory to store the wal-index
45383 ** in. Otherwise, use the normal shared-memory.
45385 static int pagerOpenWal(Pager *pPager){
45386 int rc = SQLITE_OK;
45388 assert( pPager->pWal==0 && pPager->tempFile==0 );
45389 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
45391 /* If the pager is already in exclusive-mode, the WAL module will use
45392 ** heap-memory for the wal-index instead of the VFS shared-memory
45393 ** implementation. Take the exclusive lock now, before opening the WAL
45394 ** file, to make sure this is safe.
45396 if( pPager->exclusiveMode ){
45397 rc = pagerExclusiveLock(pPager);
45400 /* Open the connection to the log file. If this operation fails,
45401 ** (e.g. due to malloc() failure), return an error code.
45403 if( rc==SQLITE_OK ){
45404 rc = sqlite3WalOpen(pPager->pVfs,
45405 pPager->fd, pPager->zWal, pPager->exclusiveMode,
45406 pPager->journalSizeLimit, &pPager->pWal
45409 pagerFixMaplimit(pPager);
45411 return rc;
45416 ** The caller must be holding a SHARED lock on the database file to call
45417 ** this function.
45419 ** If the pager passed as the first argument is open on a real database
45420 ** file (not a temp file or an in-memory database), and the WAL file
45421 ** is not already open, make an attempt to open it now. If successful,
45422 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
45423 ** not support the xShmXXX() methods, return an error code. *pbOpen is
45424 ** not modified in either case.
45426 ** If the pager is open on a temp-file (or in-memory database), or if
45427 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
45428 ** without doing anything.
45430 SQLITE_PRIVATE int sqlite3PagerOpenWal(
45431 Pager *pPager, /* Pager object */
45432 int *pbOpen /* OUT: Set to true if call is a no-op */
45434 int rc = SQLITE_OK; /* Return code */
45436 assert( assert_pager_state(pPager) );
45437 assert( pPager->eState==PAGER_OPEN || pbOpen );
45438 assert( pPager->eState==PAGER_READER || !pbOpen );
45439 assert( pbOpen==0 || *pbOpen==0 );
45440 assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
45442 if( !pPager->tempFile && !pPager->pWal ){
45443 if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
45445 /* Close any rollback journal previously open */
45446 sqlite3OsClose(pPager->jfd);
45448 rc = pagerOpenWal(pPager);
45449 if( rc==SQLITE_OK ){
45450 pPager->journalMode = PAGER_JOURNALMODE_WAL;
45451 pPager->eState = PAGER_OPEN;
45453 }else{
45454 *pbOpen = 1;
45457 return rc;
45461 ** This function is called to close the connection to the log file prior
45462 ** to switching from WAL to rollback mode.
45464 ** Before closing the log file, this function attempts to take an
45465 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
45466 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
45467 ** If successful, the EXCLUSIVE lock is not released before returning.
45469 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
45470 int rc = SQLITE_OK;
45472 assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
45474 /* If the log file is not already open, but does exist in the file-system,
45475 ** it may need to be checkpointed before the connection can switch to
45476 ** rollback mode. Open it now so this can happen.
45478 if( !pPager->pWal ){
45479 int logexists = 0;
45480 rc = pagerLockDb(pPager, SHARED_LOCK);
45481 if( rc==SQLITE_OK ){
45482 rc = sqlite3OsAccess(
45483 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
45486 if( rc==SQLITE_OK && logexists ){
45487 rc = pagerOpenWal(pPager);
45491 /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
45492 ** the database file, the log and log-summary files will be deleted.
45494 if( rc==SQLITE_OK && pPager->pWal ){
45495 rc = pagerExclusiveLock(pPager);
45496 if( rc==SQLITE_OK ){
45497 rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
45498 pPager->pageSize, (u8*)pPager->pTmpSpace);
45499 pPager->pWal = 0;
45500 pagerFixMaplimit(pPager);
45503 return rc;
45506 #endif /* !SQLITE_OMIT_WAL */
45508 #ifdef SQLITE_ENABLE_ZIPVFS
45510 ** A read-lock must be held on the pager when this function is called. If
45511 ** the pager is in WAL mode and the WAL file currently contains one or more
45512 ** frames, return the size in bytes of the page images stored within the
45513 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
45514 ** is empty, return 0.
45516 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
45517 assert( pPager->eState==PAGER_READER );
45518 return sqlite3WalFramesize(pPager->pWal);
45520 #endif
45522 #endif /* SQLITE_OMIT_DISKIO */
45524 /************** End of pager.c ***********************************************/
45525 /************** Begin file wal.c *********************************************/
45527 ** 2010 February 1
45529 ** The author disclaims copyright to this source code. In place of
45530 ** a legal notice, here is a blessing:
45532 ** May you do good and not evil.
45533 ** May you find forgiveness for yourself and forgive others.
45534 ** May you share freely, never taking more than you give.
45536 *************************************************************************
45538 ** This file contains the implementation of a write-ahead log (WAL) used in
45539 ** "journal_mode=WAL" mode.
45541 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
45543 ** A WAL file consists of a header followed by zero or more "frames".
45544 ** Each frame records the revised content of a single page from the
45545 ** database file. All changes to the database are recorded by writing
45546 ** frames into the WAL. Transactions commit when a frame is written that
45547 ** contains a commit marker. A single WAL can and usually does record
45548 ** multiple transactions. Periodically, the content of the WAL is
45549 ** transferred back into the database file in an operation called a
45550 ** "checkpoint".
45552 ** A single WAL file can be used multiple times. In other words, the
45553 ** WAL can fill up with frames and then be checkpointed and then new
45554 ** frames can overwrite the old ones. A WAL always grows from beginning
45555 ** toward the end. Checksums and counters attached to each frame are
45556 ** used to determine which frames within the WAL are valid and which
45557 ** are leftovers from prior checkpoints.
45559 ** The WAL header is 32 bytes in size and consists of the following eight
45560 ** big-endian 32-bit unsigned integer values:
45562 ** 0: Magic number. 0x377f0682 or 0x377f0683
45563 ** 4: File format version. Currently 3007000
45564 ** 8: Database page size. Example: 1024
45565 ** 12: Checkpoint sequence number
45566 ** 16: Salt-1, random integer incremented with each checkpoint
45567 ** 20: Salt-2, a different random integer changing with each ckpt
45568 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
45569 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
45571 ** Immediately following the wal-header are zero or more frames. Each
45572 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
45573 ** of page data. The frame-header is six big-endian 32-bit unsigned
45574 ** integer values, as follows:
45576 ** 0: Page number.
45577 ** 4: For commit records, the size of the database image in pages
45578 ** after the commit. For all other records, zero.
45579 ** 8: Salt-1 (copied from the header)
45580 ** 12: Salt-2 (copied from the header)
45581 ** 16: Checksum-1.
45582 ** 20: Checksum-2.
45584 ** A frame is considered valid if and only if the following conditions are
45585 ** true:
45587 ** (1) The salt-1 and salt-2 values in the frame-header match
45588 ** salt values in the wal-header
45590 ** (2) The checksum values in the final 8 bytes of the frame-header
45591 ** exactly match the checksum computed consecutively on the
45592 ** WAL header and the first 8 bytes and the content of all frames
45593 ** up to and including the current frame.
45595 ** The checksum is computed using 32-bit big-endian integers if the
45596 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
45597 ** is computed using little-endian if the magic number is 0x377f0682.
45598 ** The checksum values are always stored in the frame header in a
45599 ** big-endian format regardless of which byte order is used to compute
45600 ** the checksum. The checksum is computed by interpreting the input as
45601 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
45602 ** algorithm used for the checksum is as follows:
45604 ** for i from 0 to n-1 step 2:
45605 ** s0 += x[i] + s1;
45606 ** s1 += x[i+1] + s0;
45607 ** endfor
45609 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
45610 ** in reverse order (the largest fibonacci weight occurs on the first element
45611 ** of the sequence being summed.) The s1 value spans all 32-bit
45612 ** terms of the sequence whereas s0 omits the final term.
45614 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
45615 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
45616 ** The VFS.xSync operations serve as write barriers - all writes launched
45617 ** before the xSync must complete before any write that launches after the
45618 ** xSync begins.
45620 ** After each checkpoint, the salt-1 value is incremented and the salt-2
45621 ** value is randomized. This prevents old and new frames in the WAL from
45622 ** being considered valid at the same time and being checkpointing together
45623 ** following a crash.
45625 ** READER ALGORITHM
45627 ** To read a page from the database (call it page number P), a reader
45628 ** first checks the WAL to see if it contains page P. If so, then the
45629 ** last valid instance of page P that is a followed by a commit frame
45630 ** or is a commit frame itself becomes the value read. If the WAL
45631 ** contains no copies of page P that are valid and which are a commit
45632 ** frame or are followed by a commit frame, then page P is read from
45633 ** the database file.
45635 ** To start a read transaction, the reader records the index of the last
45636 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
45637 ** for all subsequent read operations. New transactions can be appended
45638 ** to the WAL, but as long as the reader uses its original mxFrame value
45639 ** and ignores the newly appended content, it will see a consistent snapshot
45640 ** of the database from a single point in time. This technique allows
45641 ** multiple concurrent readers to view different versions of the database
45642 ** content simultaneously.
45644 ** The reader algorithm in the previous paragraphs works correctly, but
45645 ** because frames for page P can appear anywhere within the WAL, the
45646 ** reader has to scan the entire WAL looking for page P frames. If the
45647 ** WAL is large (multiple megabytes is typical) that scan can be slow,
45648 ** and read performance suffers. To overcome this problem, a separate
45649 ** data structure called the wal-index is maintained to expedite the
45650 ** search for frames of a particular page.
45652 ** WAL-INDEX FORMAT
45654 ** Conceptually, the wal-index is shared memory, though VFS implementations
45655 ** might choose to implement the wal-index using a mmapped file. Because
45656 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
45657 ** on a network filesystem. All users of the database must be able to
45658 ** share memory.
45660 ** The wal-index is transient. After a crash, the wal-index can (and should
45661 ** be) reconstructed from the original WAL file. In fact, the VFS is required
45662 ** to either truncate or zero the header of the wal-index when the last
45663 ** connection to it closes. Because the wal-index is transient, it can
45664 ** use an architecture-specific format; it does not have to be cross-platform.
45665 ** Hence, unlike the database and WAL file formats which store all values
45666 ** as big endian, the wal-index can store multi-byte values in the native
45667 ** byte order of the host computer.
45669 ** The purpose of the wal-index is to answer this question quickly: Given
45670 ** a page number P and a maximum frame index M, return the index of the
45671 ** last frame in the wal before frame M for page P in the WAL, or return
45672 ** NULL if there are no frames for page P in the WAL prior to M.
45674 ** The wal-index consists of a header region, followed by an one or
45675 ** more index blocks.
45677 ** The wal-index header contains the total number of frames within the WAL
45678 ** in the mxFrame field.
45680 ** Each index block except for the first contains information on
45681 ** HASHTABLE_NPAGE frames. The first index block contains information on
45682 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
45683 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
45684 ** first index block are the same size as all other index blocks in the
45685 ** wal-index.
45687 ** Each index block contains two sections, a page-mapping that contains the
45688 ** database page number associated with each wal frame, and a hash-table
45689 ** that allows readers to query an index block for a specific page number.
45690 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
45691 ** for the first index block) 32-bit page numbers. The first entry in the
45692 ** first index-block contains the database page number corresponding to the
45693 ** first frame in the WAL file. The first entry in the second index block
45694 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
45695 ** the log, and so on.
45697 ** The last index block in a wal-index usually contains less than the full
45698 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
45699 ** depending on the contents of the WAL file. This does not change the
45700 ** allocated size of the page-mapping array - the page-mapping array merely
45701 ** contains unused entries.
45703 ** Even without using the hash table, the last frame for page P
45704 ** can be found by scanning the page-mapping sections of each index block
45705 ** starting with the last index block and moving toward the first, and
45706 ** within each index block, starting at the end and moving toward the
45707 ** beginning. The first entry that equals P corresponds to the frame
45708 ** holding the content for that page.
45710 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
45711 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
45712 ** hash table for each page number in the mapping section, so the hash
45713 ** table is never more than half full. The expected number of collisions
45714 ** prior to finding a match is 1. Each entry of the hash table is an
45715 ** 1-based index of an entry in the mapping section of the same
45716 ** index block. Let K be the 1-based index of the largest entry in
45717 ** the mapping section. (For index blocks other than the last, K will
45718 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
45719 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
45720 ** contain a value of 0.
45722 ** To look for page P in the hash table, first compute a hash iKey on
45723 ** P as follows:
45725 ** iKey = (P * 383) % HASHTABLE_NSLOT
45727 ** Then start scanning entries of the hash table, starting with iKey
45728 ** (wrapping around to the beginning when the end of the hash table is
45729 ** reached) until an unused hash slot is found. Let the first unused slot
45730 ** be at index iUnused. (iUnused might be less than iKey if there was
45731 ** wrap-around.) Because the hash table is never more than half full,
45732 ** the search is guaranteed to eventually hit an unused entry. Let
45733 ** iMax be the value between iKey and iUnused, closest to iUnused,
45734 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
45735 ** no hash slot such that aHash[i]==p) then page P is not in the
45736 ** current index block. Otherwise the iMax-th mapping entry of the
45737 ** current index block corresponds to the last entry that references
45738 ** page P.
45740 ** A hash search begins with the last index block and moves toward the
45741 ** first index block, looking for entries corresponding to page P. On
45742 ** average, only two or three slots in each index block need to be
45743 ** examined in order to either find the last entry for page P, or to
45744 ** establish that no such entry exists in the block. Each index block
45745 ** holds over 4000 entries. So two or three index blocks are sufficient
45746 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
45747 ** comparisons (on average) suffice to either locate a frame in the
45748 ** WAL or to establish that the frame does not exist in the WAL. This
45749 ** is much faster than scanning the entire 10MB WAL.
45751 ** Note that entries are added in order of increasing K. Hence, one
45752 ** reader might be using some value K0 and a second reader that started
45753 ** at a later time (after additional transactions were added to the WAL
45754 ** and to the wal-index) might be using a different value K1, where K1>K0.
45755 ** Both readers can use the same hash table and mapping section to get
45756 ** the correct result. There may be entries in the hash table with
45757 ** K>K0 but to the first reader, those entries will appear to be unused
45758 ** slots in the hash table and so the first reader will get an answer as
45759 ** if no values greater than K0 had ever been inserted into the hash table
45760 ** in the first place - which is what reader one wants. Meanwhile, the
45761 ** second reader using K1 will see additional values that were inserted
45762 ** later, which is exactly what reader two wants.
45764 ** When a rollback occurs, the value of K is decreased. Hash table entries
45765 ** that correspond to frames greater than the new K value are removed
45766 ** from the hash table at this point.
45768 #ifndef SQLITE_OMIT_WAL
45772 ** Trace output macros
45774 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45775 SQLITE_PRIVATE int sqlite3WalTrace = 0;
45776 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
45777 #else
45778 # define WALTRACE(X)
45779 #endif
45782 ** The maximum (and only) versions of the wal and wal-index formats
45783 ** that may be interpreted by this version of SQLite.
45785 ** If a client begins recovering a WAL file and finds that (a) the checksum
45786 ** values in the wal-header are correct and (b) the version field is not
45787 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
45789 ** Similarly, if a client successfully reads a wal-index header (i.e. the
45790 ** checksum test is successful) and finds that the version field is not
45791 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
45792 ** returns SQLITE_CANTOPEN.
45794 #define WAL_MAX_VERSION 3007000
45795 #define WALINDEX_MAX_VERSION 3007000
45798 ** Indices of various locking bytes. WAL_NREADER is the number
45799 ** of available reader locks and should be at least 3.
45801 #define WAL_WRITE_LOCK 0
45802 #define WAL_ALL_BUT_WRITE 1
45803 #define WAL_CKPT_LOCK 1
45804 #define WAL_RECOVER_LOCK 2
45805 #define WAL_READ_LOCK(I) (3+(I))
45806 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
45809 /* Object declarations */
45810 typedef struct WalIndexHdr WalIndexHdr;
45811 typedef struct WalIterator WalIterator;
45812 typedef struct WalCkptInfo WalCkptInfo;
45816 ** The following object holds a copy of the wal-index header content.
45818 ** The actual header in the wal-index consists of two copies of this
45819 ** object.
45821 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
45822 ** Or it can be 1 to represent a 65536-byte page. The latter case was
45823 ** added in 3.7.1 when support for 64K pages was added.
45825 struct WalIndexHdr {
45826 u32 iVersion; /* Wal-index version */
45827 u32 unused; /* Unused (padding) field */
45828 u32 iChange; /* Counter incremented each transaction */
45829 u8 isInit; /* 1 when initialized */
45830 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
45831 u16 szPage; /* Database page size in bytes. 1==64K */
45832 u32 mxFrame; /* Index of last valid frame in the WAL */
45833 u32 nPage; /* Size of database in pages */
45834 u32 aFrameCksum[2]; /* Checksum of last frame in log */
45835 u32 aSalt[2]; /* Two salt values copied from WAL header */
45836 u32 aCksum[2]; /* Checksum over all prior fields */
45840 ** A copy of the following object occurs in the wal-index immediately
45841 ** following the second copy of the WalIndexHdr. This object stores
45842 ** information used by checkpoint.
45844 ** nBackfill is the number of frames in the WAL that have been written
45845 ** back into the database. (We call the act of moving content from WAL to
45846 ** database "backfilling".) The nBackfill number is never greater than
45847 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
45848 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
45849 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
45850 ** mxFrame back to zero when the WAL is reset.
45852 ** There is one entry in aReadMark[] for each reader lock. If a reader
45853 ** holds read-lock K, then the value in aReadMark[K] is no greater than
45854 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
45855 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
45856 ** a special case; its value is never used and it exists as a place-holder
45857 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
45858 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
45859 ** directly from the database.
45861 ** The value of aReadMark[K] may only be changed by a thread that
45862 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
45863 ** aReadMark[K] cannot changed while there is a reader is using that mark
45864 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
45866 ** The checkpointer may only transfer frames from WAL to database where
45867 ** the frame numbers are less than or equal to every aReadMark[] that is
45868 ** in use (that is, every aReadMark[j] for which there is a corresponding
45869 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
45870 ** largest value and will increase an unused aReadMark[] to mxFrame if there
45871 ** is not already an aReadMark[] equal to mxFrame. The exception to the
45872 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
45873 ** in the WAL has been backfilled into the database) then new readers
45874 ** will choose aReadMark[0] which has value 0 and hence such reader will
45875 ** get all their all content directly from the database file and ignore
45876 ** the WAL.
45878 ** Writers normally append new frames to the end of the WAL. However,
45879 ** if nBackfill equals mxFrame (meaning that all WAL content has been
45880 ** written back into the database) and if no readers are using the WAL
45881 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
45882 ** the writer will first "reset" the WAL back to the beginning and start
45883 ** writing new content beginning at frame 1.
45885 ** We assume that 32-bit loads are atomic and so no locks are needed in
45886 ** order to read from any aReadMark[] entries.
45888 struct WalCkptInfo {
45889 u32 nBackfill; /* Number of WAL frames backfilled into DB */
45890 u32 aReadMark[WAL_NREADER]; /* Reader marks */
45892 #define READMARK_NOT_USED 0xffffffff
45895 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
45896 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
45897 ** only support mandatory file-locks, we do not read or write data
45898 ** from the region of the file on which locks are applied.
45900 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
45901 #define WALINDEX_LOCK_RESERVED 16
45902 #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
45904 /* Size of header before each frame in wal */
45905 #define WAL_FRAME_HDRSIZE 24
45907 /* Size of write ahead log header, including checksum. */
45908 /* #define WAL_HDRSIZE 24 */
45909 #define WAL_HDRSIZE 32
45911 /* WAL magic value. Either this value, or the same value with the least
45912 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
45913 ** big-endian format in the first 4 bytes of a WAL file.
45915 ** If the LSB is set, then the checksums for each frame within the WAL
45916 ** file are calculated by treating all data as an array of 32-bit
45917 ** big-endian words. Otherwise, they are calculated by interpreting
45918 ** all data as 32-bit little-endian words.
45920 #define WAL_MAGIC 0x377f0682
45923 ** Return the offset of frame iFrame in the write-ahead log file,
45924 ** assuming a database page size of szPage bytes. The offset returned
45925 ** is to the start of the write-ahead log frame-header.
45927 #define walFrameOffset(iFrame, szPage) ( \
45928 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
45932 ** An open write-ahead log file is represented by an instance of the
45933 ** following object.
45935 struct Wal {
45936 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
45937 sqlite3_file *pDbFd; /* File handle for the database file */
45938 sqlite3_file *pWalFd; /* File handle for WAL file */
45939 u32 iCallback; /* Value to pass to log callback (or 0) */
45940 i64 mxWalSize; /* Truncate WAL to this size upon reset */
45941 int nWiData; /* Size of array apWiData */
45942 int szFirstBlock; /* Size of first block written to WAL file */
45943 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
45944 u32 szPage; /* Database page size */
45945 i16 readLock; /* Which read lock is being held. -1 for none */
45946 u8 syncFlags; /* Flags to use to sync header writes */
45947 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
45948 u8 writeLock; /* True if in a write transaction */
45949 u8 ckptLock; /* True if holding a checkpoint lock */
45950 u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
45951 u8 truncateOnCommit; /* True to truncate WAL file on commit */
45952 u8 syncHeader; /* Fsync the WAL header if true */
45953 u8 padToSectorBoundary; /* Pad transactions out to the next sector */
45954 WalIndexHdr hdr; /* Wal-index header for current transaction */
45955 const char *zWalName; /* Name of WAL file */
45956 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
45957 #ifdef SQLITE_DEBUG
45958 u8 lockError; /* True if a locking error has occurred */
45959 #endif
45963 ** Candidate values for Wal.exclusiveMode.
45965 #define WAL_NORMAL_MODE 0
45966 #define WAL_EXCLUSIVE_MODE 1
45967 #define WAL_HEAPMEMORY_MODE 2
45970 ** Possible values for WAL.readOnly
45972 #define WAL_RDWR 0 /* Normal read/write connection */
45973 #define WAL_RDONLY 1 /* The WAL file is readonly */
45974 #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
45977 ** Each page of the wal-index mapping contains a hash-table made up of
45978 ** an array of HASHTABLE_NSLOT elements of the following type.
45980 typedef u16 ht_slot;
45983 ** This structure is used to implement an iterator that loops through
45984 ** all frames in the WAL in database page order. Where two or more frames
45985 ** correspond to the same database page, the iterator visits only the
45986 ** frame most recently written to the WAL (in other words, the frame with
45987 ** the largest index).
45989 ** The internals of this structure are only accessed by:
45991 ** walIteratorInit() - Create a new iterator,
45992 ** walIteratorNext() - Step an iterator,
45993 ** walIteratorFree() - Free an iterator.
45995 ** This functionality is used by the checkpoint code (see walCheckpoint()).
45997 struct WalIterator {
45998 int iPrior; /* Last result returned from the iterator */
45999 int nSegment; /* Number of entries in aSegment[] */
46000 struct WalSegment {
46001 int iNext; /* Next slot in aIndex[] not yet returned */
46002 ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
46003 u32 *aPgno; /* Array of page numbers. */
46004 int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
46005 int iZero; /* Frame number associated with aPgno[0] */
46006 } aSegment[1]; /* One for every 32KB page in the wal-index */
46010 ** Define the parameters of the hash tables in the wal-index file. There
46011 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
46012 ** wal-index.
46014 ** Changing any of these constants will alter the wal-index format and
46015 ** create incompatibilities.
46017 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
46018 #define HASHTABLE_HASH_1 383 /* Should be prime */
46019 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
46022 ** The block of page numbers associated with the first hash-table in a
46023 ** wal-index is smaller than usual. This is so that there is a complete
46024 ** hash-table on each aligned 32KB page of the wal-index.
46026 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
46028 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
46029 #define WALINDEX_PGSZ ( \
46030 sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
46034 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
46035 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
46036 ** numbered from zero.
46038 ** If this call is successful, *ppPage is set to point to the wal-index
46039 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
46040 ** then an SQLite error code is returned and *ppPage is set to 0.
46042 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
46043 int rc = SQLITE_OK;
46045 /* Enlarge the pWal->apWiData[] array if required */
46046 if( pWal->nWiData<=iPage ){
46047 int nByte = sizeof(u32*)*(iPage+1);
46048 volatile u32 **apNew;
46049 apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
46050 if( !apNew ){
46051 *ppPage = 0;
46052 return SQLITE_NOMEM;
46054 memset((void*)&apNew[pWal->nWiData], 0,
46055 sizeof(u32*)*(iPage+1-pWal->nWiData));
46056 pWal->apWiData = apNew;
46057 pWal->nWiData = iPage+1;
46060 /* Request a pointer to the required page from the VFS */
46061 if( pWal->apWiData[iPage]==0 ){
46062 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46063 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
46064 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
46065 }else{
46066 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
46067 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
46069 if( rc==SQLITE_READONLY ){
46070 pWal->readOnly |= WAL_SHM_RDONLY;
46071 rc = SQLITE_OK;
46076 *ppPage = pWal->apWiData[iPage];
46077 assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
46078 return rc;
46082 ** Return a pointer to the WalCkptInfo structure in the wal-index.
46084 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
46085 assert( pWal->nWiData>0 && pWal->apWiData[0] );
46086 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
46090 ** Return a pointer to the WalIndexHdr structure in the wal-index.
46092 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
46093 assert( pWal->nWiData>0 && pWal->apWiData[0] );
46094 return (volatile WalIndexHdr*)pWal->apWiData[0];
46098 ** The argument to this macro must be of type u32. On a little-endian
46099 ** architecture, it returns the u32 value that results from interpreting
46100 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
46101 ** returns the value that would be produced by intepreting the 4 bytes
46102 ** of the input value as a little-endian integer.
46104 #define BYTESWAP32(x) ( \
46105 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
46106 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
46110 ** Generate or extend an 8 byte checksum based on the data in
46111 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
46112 ** initial values of 0 and 0 if aIn==NULL).
46114 ** The checksum is written back into aOut[] before returning.
46116 ** nByte must be a positive multiple of 8.
46118 static void walChecksumBytes(
46119 int nativeCksum, /* True for native byte-order, false for non-native */
46120 u8 *a, /* Content to be checksummed */
46121 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
46122 const u32 *aIn, /* Initial checksum value input */
46123 u32 *aOut /* OUT: Final checksum value output */
46125 u32 s1, s2;
46126 u32 *aData = (u32 *)a;
46127 u32 *aEnd = (u32 *)&a[nByte];
46129 if( aIn ){
46130 s1 = aIn[0];
46131 s2 = aIn[1];
46132 }else{
46133 s1 = s2 = 0;
46136 assert( nByte>=8 );
46137 assert( (nByte&0x00000007)==0 );
46139 if( nativeCksum ){
46140 do {
46141 s1 += *aData++ + s2;
46142 s2 += *aData++ + s1;
46143 }while( aData<aEnd );
46144 }else{
46145 do {
46146 s1 += BYTESWAP32(aData[0]) + s2;
46147 s2 += BYTESWAP32(aData[1]) + s1;
46148 aData += 2;
46149 }while( aData<aEnd );
46152 aOut[0] = s1;
46153 aOut[1] = s2;
46156 static void walShmBarrier(Wal *pWal){
46157 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
46158 sqlite3OsShmBarrier(pWal->pDbFd);
46163 ** Write the header information in pWal->hdr into the wal-index.
46165 ** The checksum on pWal->hdr is updated before it is written.
46167 static void walIndexWriteHdr(Wal *pWal){
46168 volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
46169 const int nCksum = offsetof(WalIndexHdr, aCksum);
46171 assert( pWal->writeLock );
46172 pWal->hdr.isInit = 1;
46173 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
46174 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
46175 memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46176 walShmBarrier(pWal);
46177 memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46181 ** This function encodes a single frame header and writes it to a buffer
46182 ** supplied by the caller. A frame-header is made up of a series of
46183 ** 4-byte big-endian integers, as follows:
46185 ** 0: Page number.
46186 ** 4: For commit records, the size of the database image in pages
46187 ** after the commit. For all other records, zero.
46188 ** 8: Salt-1 (copied from the wal-header)
46189 ** 12: Salt-2 (copied from the wal-header)
46190 ** 16: Checksum-1.
46191 ** 20: Checksum-2.
46193 static void walEncodeFrame(
46194 Wal *pWal, /* The write-ahead log */
46195 u32 iPage, /* Database page number for frame */
46196 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
46197 u8 *aData, /* Pointer to page data */
46198 u8 *aFrame /* OUT: Write encoded frame here */
46200 int nativeCksum; /* True for native byte-order checksums */
46201 u32 *aCksum = pWal->hdr.aFrameCksum;
46202 assert( WAL_FRAME_HDRSIZE==24 );
46203 sqlite3Put4byte(&aFrame[0], iPage);
46204 sqlite3Put4byte(&aFrame[4], nTruncate);
46205 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
46207 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46208 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46209 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46211 sqlite3Put4byte(&aFrame[16], aCksum[0]);
46212 sqlite3Put4byte(&aFrame[20], aCksum[1]);
46216 ** Check to see if the frame with header in aFrame[] and content
46217 ** in aData[] is valid. If it is a valid frame, fill *piPage and
46218 ** *pnTruncate and return true. Return if the frame is not valid.
46220 static int walDecodeFrame(
46221 Wal *pWal, /* The write-ahead log */
46222 u32 *piPage, /* OUT: Database page number for frame */
46223 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
46224 u8 *aData, /* Pointer to page data (for checksum) */
46225 u8 *aFrame /* Frame data */
46227 int nativeCksum; /* True for native byte-order checksums */
46228 u32 *aCksum = pWal->hdr.aFrameCksum;
46229 u32 pgno; /* Page number of the frame */
46230 assert( WAL_FRAME_HDRSIZE==24 );
46232 /* A frame is only valid if the salt values in the frame-header
46233 ** match the salt values in the wal-header.
46235 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
46236 return 0;
46239 /* A frame is only valid if the page number is creater than zero.
46241 pgno = sqlite3Get4byte(&aFrame[0]);
46242 if( pgno==0 ){
46243 return 0;
46246 /* A frame is only valid if a checksum of the WAL header,
46247 ** all prior frams, the first 16 bytes of this frame-header,
46248 ** and the frame-data matches the checksum in the last 8
46249 ** bytes of this frame-header.
46251 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46252 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46253 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46254 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
46255 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
46257 /* Checksum failed. */
46258 return 0;
46261 /* If we reach this point, the frame is valid. Return the page number
46262 ** and the new database size.
46264 *piPage = pgno;
46265 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
46266 return 1;
46270 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46272 ** Names of locks. This routine is used to provide debugging output and is not
46273 ** a part of an ordinary build.
46275 static const char *walLockName(int lockIdx){
46276 if( lockIdx==WAL_WRITE_LOCK ){
46277 return "WRITE-LOCK";
46278 }else if( lockIdx==WAL_CKPT_LOCK ){
46279 return "CKPT-LOCK";
46280 }else if( lockIdx==WAL_RECOVER_LOCK ){
46281 return "RECOVER-LOCK";
46282 }else{
46283 static char zName[15];
46284 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
46285 lockIdx-WAL_READ_LOCK(0));
46286 return zName;
46289 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
46293 ** Set or release locks on the WAL. Locks are either shared or exclusive.
46294 ** A lock cannot be moved directly between shared and exclusive - it must go
46295 ** through the unlocked state first.
46297 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
46299 static int walLockShared(Wal *pWal, int lockIdx){
46300 int rc;
46301 if( pWal->exclusiveMode ) return SQLITE_OK;
46302 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46303 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
46304 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
46305 walLockName(lockIdx), rc ? "failed" : "ok"));
46306 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46307 return rc;
46309 static void walUnlockShared(Wal *pWal, int lockIdx){
46310 if( pWal->exclusiveMode ) return;
46311 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46312 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
46313 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
46315 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
46316 int rc;
46317 if( pWal->exclusiveMode ) return SQLITE_OK;
46318 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46319 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
46320 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
46321 walLockName(lockIdx), n, rc ? "failed" : "ok"));
46322 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46323 return rc;
46325 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
46326 if( pWal->exclusiveMode ) return;
46327 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46328 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
46329 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
46330 walLockName(lockIdx), n));
46334 ** Compute a hash on a page number. The resulting hash value must land
46335 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
46336 ** the hash to the next value in the event of a collision.
46338 static int walHash(u32 iPage){
46339 assert( iPage>0 );
46340 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
46341 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
46343 static int walNextHash(int iPriorHash){
46344 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
46348 ** Return pointers to the hash table and page number array stored on
46349 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
46350 ** numbered starting from 0.
46352 ** Set output variable *paHash to point to the start of the hash table
46353 ** in the wal-index file. Set *piZero to one less than the frame
46354 ** number of the first frame indexed by this hash table. If a
46355 ** slot in the hash table is set to N, it refers to frame number
46356 ** (*piZero+N) in the log.
46358 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
46359 ** first frame indexed by the hash table, frame (*piZero+1).
46361 static int walHashGet(
46362 Wal *pWal, /* WAL handle */
46363 int iHash, /* Find the iHash'th table */
46364 volatile ht_slot **paHash, /* OUT: Pointer to hash index */
46365 volatile u32 **paPgno, /* OUT: Pointer to page number array */
46366 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
46368 int rc; /* Return code */
46369 volatile u32 *aPgno;
46371 rc = walIndexPage(pWal, iHash, &aPgno);
46372 assert( rc==SQLITE_OK || iHash>0 );
46374 if( rc==SQLITE_OK ){
46375 u32 iZero;
46376 volatile ht_slot *aHash;
46378 aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
46379 if( iHash==0 ){
46380 aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
46381 iZero = 0;
46382 }else{
46383 iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
46386 *paPgno = &aPgno[-1];
46387 *paHash = aHash;
46388 *piZero = iZero;
46390 return rc;
46394 ** Return the number of the wal-index page that contains the hash-table
46395 ** and page-number array that contain entries corresponding to WAL frame
46396 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
46397 ** are numbered starting from 0.
46399 static int walFramePage(u32 iFrame){
46400 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
46401 assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
46402 && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
46403 && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
46404 && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
46405 && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
46407 return iHash;
46411 ** Return the page number associated with frame iFrame in this WAL.
46413 static u32 walFramePgno(Wal *pWal, u32 iFrame){
46414 int iHash = walFramePage(iFrame);
46415 if( iHash==0 ){
46416 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
46418 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
46422 ** Remove entries from the hash table that point to WAL slots greater
46423 ** than pWal->hdr.mxFrame.
46425 ** This function is called whenever pWal->hdr.mxFrame is decreased due
46426 ** to a rollback or savepoint.
46428 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
46429 ** updated. Any later hash tables will be automatically cleared when
46430 ** pWal->hdr.mxFrame advances to the point where those hash tables are
46431 ** actually needed.
46433 static void walCleanupHash(Wal *pWal){
46434 volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
46435 volatile u32 *aPgno = 0; /* Page number array for hash table */
46436 u32 iZero = 0; /* frame == (aHash[x]+iZero) */
46437 int iLimit = 0; /* Zero values greater than this */
46438 int nByte; /* Number of bytes to zero in aPgno[] */
46439 int i; /* Used to iterate through aHash[] */
46441 assert( pWal->writeLock );
46442 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
46443 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
46444 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
46446 if( pWal->hdr.mxFrame==0 ) return;
46448 /* Obtain pointers to the hash-table and page-number array containing
46449 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
46450 ** that the page said hash-table and array reside on is already mapped.
46452 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
46453 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
46454 walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
46456 /* Zero all hash-table entries that correspond to frame numbers greater
46457 ** than pWal->hdr.mxFrame.
46459 iLimit = pWal->hdr.mxFrame - iZero;
46460 assert( iLimit>0 );
46461 for(i=0; i<HASHTABLE_NSLOT; i++){
46462 if( aHash[i]>iLimit ){
46463 aHash[i] = 0;
46467 /* Zero the entries in the aPgno array that correspond to frames with
46468 ** frame numbers greater than pWal->hdr.mxFrame.
46470 nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
46471 memset((void *)&aPgno[iLimit+1], 0, nByte);
46473 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46474 /* Verify that the every entry in the mapping region is still reachable
46475 ** via the hash table even after the cleanup.
46477 if( iLimit ){
46478 int i; /* Loop counter */
46479 int iKey; /* Hash key */
46480 for(i=1; i<=iLimit; i++){
46481 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
46482 if( aHash[iKey]==i ) break;
46484 assert( aHash[iKey]==i );
46487 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
46492 ** Set an entry in the wal-index that will map database page number
46493 ** pPage into WAL frame iFrame.
46495 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
46496 int rc; /* Return code */
46497 u32 iZero = 0; /* One less than frame number of aPgno[1] */
46498 volatile u32 *aPgno = 0; /* Page number array */
46499 volatile ht_slot *aHash = 0; /* Hash table */
46501 rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
46503 /* Assuming the wal-index file was successfully mapped, populate the
46504 ** page number array and hash table entry.
46506 if( rc==SQLITE_OK ){
46507 int iKey; /* Hash table key */
46508 int idx; /* Value to write to hash-table slot */
46509 int nCollide; /* Number of hash collisions */
46511 idx = iFrame - iZero;
46512 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
46514 /* If this is the first entry to be added to this hash-table, zero the
46515 ** entire hash table and aPgno[] array before proceding.
46517 if( idx==1 ){
46518 int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
46519 memset((void*)&aPgno[1], 0, nByte);
46522 /* If the entry in aPgno[] is already set, then the previous writer
46523 ** must have exited unexpectedly in the middle of a transaction (after
46524 ** writing one or more dirty pages to the WAL to free up memory).
46525 ** Remove the remnants of that writers uncommitted transaction from
46526 ** the hash-table before writing any new entries.
46528 if( aPgno[idx] ){
46529 walCleanupHash(pWal);
46530 assert( !aPgno[idx] );
46533 /* Write the aPgno[] array entry and the hash-table slot. */
46534 nCollide = idx;
46535 for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
46536 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
46538 aPgno[idx] = iPage;
46539 aHash[iKey] = (ht_slot)idx;
46541 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46542 /* Verify that the number of entries in the hash table exactly equals
46543 ** the number of entries in the mapping region.
46546 int i; /* Loop counter */
46547 int nEntry = 0; /* Number of entries in the hash table */
46548 for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
46549 assert( nEntry==idx );
46552 /* Verify that the every entry in the mapping region is reachable
46553 ** via the hash table. This turns out to be a really, really expensive
46554 ** thing to check, so only do this occasionally - not on every
46555 ** iteration.
46557 if( (idx&0x3ff)==0 ){
46558 int i; /* Loop counter */
46559 for(i=1; i<=idx; i++){
46560 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
46561 if( aHash[iKey]==i ) break;
46563 assert( aHash[iKey]==i );
46566 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
46570 return rc;
46575 ** Recover the wal-index by reading the write-ahead log file.
46577 ** This routine first tries to establish an exclusive lock on the
46578 ** wal-index to prevent other threads/processes from doing anything
46579 ** with the WAL or wal-index while recovery is running. The
46580 ** WAL_RECOVER_LOCK is also held so that other threads will know
46581 ** that this thread is running recovery. If unable to establish
46582 ** the necessary locks, this routine returns SQLITE_BUSY.
46584 static int walIndexRecover(Wal *pWal){
46585 int rc; /* Return Code */
46586 i64 nSize; /* Size of log file */
46587 u32 aFrameCksum[2] = {0, 0};
46588 int iLock; /* Lock offset to lock for checkpoint */
46589 int nLock; /* Number of locks to hold */
46591 /* Obtain an exclusive lock on all byte in the locking range not already
46592 ** locked by the caller. The caller is guaranteed to have locked the
46593 ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
46594 ** If successful, the same bytes that are locked here are unlocked before
46595 ** this function returns.
46597 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
46598 assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
46599 assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
46600 assert( pWal->writeLock );
46601 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
46602 nLock = SQLITE_SHM_NLOCK - iLock;
46603 rc = walLockExclusive(pWal, iLock, nLock);
46604 if( rc ){
46605 return rc;
46607 WALTRACE(("WAL%p: recovery begin...\n", pWal));
46609 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
46611 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
46612 if( rc!=SQLITE_OK ){
46613 goto recovery_error;
46616 if( nSize>WAL_HDRSIZE ){
46617 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
46618 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
46619 int szFrame; /* Number of bytes in buffer aFrame[] */
46620 u8 *aData; /* Pointer to data part of aFrame buffer */
46621 int iFrame; /* Index of last frame read */
46622 i64 iOffset; /* Next offset to read from log file */
46623 int szPage; /* Page size according to the log */
46624 u32 magic; /* Magic value read from WAL header */
46625 u32 version; /* Magic value read from WAL header */
46626 int isValid; /* True if this frame is valid */
46628 /* Read in the WAL header. */
46629 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
46630 if( rc!=SQLITE_OK ){
46631 goto recovery_error;
46634 /* If the database page size is not a power of two, or is greater than
46635 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
46636 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
46637 ** WAL file.
46639 magic = sqlite3Get4byte(&aBuf[0]);
46640 szPage = sqlite3Get4byte(&aBuf[8]);
46641 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
46642 || szPage&(szPage-1)
46643 || szPage>SQLITE_MAX_PAGE_SIZE
46644 || szPage<512
46646 goto finished;
46648 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
46649 pWal->szPage = szPage;
46650 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
46651 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
46653 /* Verify that the WAL header checksum is correct */
46654 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
46655 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
46657 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
46658 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
46660 goto finished;
46663 /* Verify that the version number on the WAL format is one that
46664 ** are able to understand */
46665 version = sqlite3Get4byte(&aBuf[4]);
46666 if( version!=WAL_MAX_VERSION ){
46667 rc = SQLITE_CANTOPEN_BKPT;
46668 goto finished;
46671 /* Malloc a buffer to read frames into. */
46672 szFrame = szPage + WAL_FRAME_HDRSIZE;
46673 aFrame = (u8 *)sqlite3_malloc(szFrame);
46674 if( !aFrame ){
46675 rc = SQLITE_NOMEM;
46676 goto recovery_error;
46678 aData = &aFrame[WAL_FRAME_HDRSIZE];
46680 /* Read all frames from the log file. */
46681 iFrame = 0;
46682 for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
46683 u32 pgno; /* Database page number for frame */
46684 u32 nTruncate; /* dbsize field from frame header */
46686 /* Read and decode the next log frame. */
46687 iFrame++;
46688 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
46689 if( rc!=SQLITE_OK ) break;
46690 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
46691 if( !isValid ) break;
46692 rc = walIndexAppend(pWal, iFrame, pgno);
46693 if( rc!=SQLITE_OK ) break;
46695 /* If nTruncate is non-zero, this is a commit record. */
46696 if( nTruncate ){
46697 pWal->hdr.mxFrame = iFrame;
46698 pWal->hdr.nPage = nTruncate;
46699 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
46700 testcase( szPage<=32768 );
46701 testcase( szPage>=65536 );
46702 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
46703 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
46707 sqlite3_free(aFrame);
46710 finished:
46711 if( rc==SQLITE_OK ){
46712 volatile WalCkptInfo *pInfo;
46713 int i;
46714 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
46715 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
46716 walIndexWriteHdr(pWal);
46718 /* Reset the checkpoint-header. This is safe because this thread is
46719 ** currently holding locks that exclude all other readers, writers and
46720 ** checkpointers.
46722 pInfo = walCkptInfo(pWal);
46723 pInfo->nBackfill = 0;
46724 pInfo->aReadMark[0] = 0;
46725 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46726 if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
46728 /* If more than one frame was recovered from the log file, report an
46729 ** event via sqlite3_log(). This is to help with identifying performance
46730 ** problems caused by applications routinely shutting down without
46731 ** checkpointing the log file.
46733 if( pWal->hdr.nPage ){
46734 sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
46735 "recovered %d frames from WAL file %s",
46736 pWal->hdr.mxFrame, pWal->zWalName
46741 recovery_error:
46742 WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
46743 walUnlockExclusive(pWal, iLock, nLock);
46744 return rc;
46748 ** Close an open wal-index.
46750 static void walIndexClose(Wal *pWal, int isDelete){
46751 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46752 int i;
46753 for(i=0; i<pWal->nWiData; i++){
46754 sqlite3_free((void *)pWal->apWiData[i]);
46755 pWal->apWiData[i] = 0;
46757 }else{
46758 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
46763 ** Open a connection to the WAL file zWalName. The database file must
46764 ** already be opened on connection pDbFd. The buffer that zWalName points
46765 ** to must remain valid for the lifetime of the returned Wal* handle.
46767 ** A SHARED lock should be held on the database file when this function
46768 ** is called. The purpose of this SHARED lock is to prevent any other
46769 ** client from unlinking the WAL or wal-index file. If another process
46770 ** were to do this just after this client opened one of these files, the
46771 ** system would be badly broken.
46773 ** If the log file is successfully opened, SQLITE_OK is returned and
46774 ** *ppWal is set to point to a new WAL handle. If an error occurs,
46775 ** an SQLite error code is returned and *ppWal is left unmodified.
46777 SQLITE_PRIVATE int sqlite3WalOpen(
46778 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
46779 sqlite3_file *pDbFd, /* The open database file */
46780 const char *zWalName, /* Name of the WAL file */
46781 int bNoShm, /* True to run in heap-memory mode */
46782 i64 mxWalSize, /* Truncate WAL to this size on reset */
46783 Wal **ppWal /* OUT: Allocated Wal handle */
46785 int rc; /* Return Code */
46786 Wal *pRet; /* Object to allocate and return */
46787 int flags; /* Flags passed to OsOpen() */
46789 assert( zWalName && zWalName[0] );
46790 assert( pDbFd );
46792 /* In the amalgamation, the os_unix.c and os_win.c source files come before
46793 ** this source file. Verify that the #defines of the locking byte offsets
46794 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
46796 #ifdef WIN_SHM_BASE
46797 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
46798 #endif
46799 #ifdef UNIX_SHM_BASE
46800 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
46801 #endif
46804 /* Allocate an instance of struct Wal to return. */
46805 *ppWal = 0;
46806 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
46807 if( !pRet ){
46808 return SQLITE_NOMEM;
46811 pRet->pVfs = pVfs;
46812 pRet->pWalFd = (sqlite3_file *)&pRet[1];
46813 pRet->pDbFd = pDbFd;
46814 pRet->readLock = -1;
46815 pRet->mxWalSize = mxWalSize;
46816 pRet->zWalName = zWalName;
46817 pRet->syncHeader = 1;
46818 pRet->padToSectorBoundary = 1;
46819 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
46821 /* Open file handle on the write-ahead log file. */
46822 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
46823 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
46824 if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
46825 pRet->readOnly = WAL_RDONLY;
46828 if( rc!=SQLITE_OK ){
46829 walIndexClose(pRet, 0);
46830 sqlite3OsClose(pRet->pWalFd);
46831 sqlite3_free(pRet);
46832 }else{
46833 int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
46834 if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
46835 if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
46836 pRet->padToSectorBoundary = 0;
46838 *ppWal = pRet;
46839 WALTRACE(("WAL%d: opened\n", pRet));
46841 return rc;
46845 ** Change the size to which the WAL file is trucated on each reset.
46847 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
46848 if( pWal ) pWal->mxWalSize = iLimit;
46852 ** Find the smallest page number out of all pages held in the WAL that
46853 ** has not been returned by any prior invocation of this method on the
46854 ** same WalIterator object. Write into *piFrame the frame index where
46855 ** that page was last written into the WAL. Write into *piPage the page
46856 ** number.
46858 ** Return 0 on success. If there are no pages in the WAL with a page
46859 ** number larger than *piPage, then return 1.
46861 static int walIteratorNext(
46862 WalIterator *p, /* Iterator */
46863 u32 *piPage, /* OUT: The page number of the next page */
46864 u32 *piFrame /* OUT: Wal frame index of next page */
46866 u32 iMin; /* Result pgno must be greater than iMin */
46867 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
46868 int i; /* For looping through segments */
46870 iMin = p->iPrior;
46871 assert( iMin<0xffffffff );
46872 for(i=p->nSegment-1; i>=0; i--){
46873 struct WalSegment *pSegment = &p->aSegment[i];
46874 while( pSegment->iNext<pSegment->nEntry ){
46875 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
46876 if( iPg>iMin ){
46877 if( iPg<iRet ){
46878 iRet = iPg;
46879 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
46881 break;
46883 pSegment->iNext++;
46887 *piPage = p->iPrior = iRet;
46888 return (iRet==0xFFFFFFFF);
46892 ** This function merges two sorted lists into a single sorted list.
46894 ** aLeft[] and aRight[] are arrays of indices. The sort key is
46895 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
46896 ** is guaranteed for all J<K:
46898 ** aContent[aLeft[J]] < aContent[aLeft[K]]
46899 ** aContent[aRight[J]] < aContent[aRight[K]]
46901 ** This routine overwrites aRight[] with a new (probably longer) sequence
46902 ** of indices such that the aRight[] contains every index that appears in
46903 ** either aLeft[] or the old aRight[] and such that the second condition
46904 ** above is still met.
46906 ** The aContent[aLeft[X]] values will be unique for all X. And the
46907 ** aContent[aRight[X]] values will be unique too. But there might be
46908 ** one or more combinations of X and Y such that
46910 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
46912 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
46914 static void walMerge(
46915 const u32 *aContent, /* Pages in wal - keys for the sort */
46916 ht_slot *aLeft, /* IN: Left hand input list */
46917 int nLeft, /* IN: Elements in array *paLeft */
46918 ht_slot **paRight, /* IN/OUT: Right hand input list */
46919 int *pnRight, /* IN/OUT: Elements in *paRight */
46920 ht_slot *aTmp /* Temporary buffer */
46922 int iLeft = 0; /* Current index in aLeft */
46923 int iRight = 0; /* Current index in aRight */
46924 int iOut = 0; /* Current index in output buffer */
46925 int nRight = *pnRight;
46926 ht_slot *aRight = *paRight;
46928 assert( nLeft>0 && nRight>0 );
46929 while( iRight<nRight || iLeft<nLeft ){
46930 ht_slot logpage;
46931 Pgno dbpage;
46933 if( (iLeft<nLeft)
46934 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
46936 logpage = aLeft[iLeft++];
46937 }else{
46938 logpage = aRight[iRight++];
46940 dbpage = aContent[logpage];
46942 aTmp[iOut++] = logpage;
46943 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
46945 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
46946 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
46949 *paRight = aLeft;
46950 *pnRight = iOut;
46951 memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
46955 ** Sort the elements in list aList using aContent[] as the sort key.
46956 ** Remove elements with duplicate keys, preferring to keep the
46957 ** larger aList[] values.
46959 ** The aList[] entries are indices into aContent[]. The values in
46960 ** aList[] are to be sorted so that for all J<K:
46962 ** aContent[aList[J]] < aContent[aList[K]]
46964 ** For any X and Y such that
46966 ** aContent[aList[X]] == aContent[aList[Y]]
46968 ** Keep the larger of the two values aList[X] and aList[Y] and discard
46969 ** the smaller.
46971 static void walMergesort(
46972 const u32 *aContent, /* Pages in wal */
46973 ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
46974 ht_slot *aList, /* IN/OUT: List to sort */
46975 int *pnList /* IN/OUT: Number of elements in aList[] */
46977 struct Sublist {
46978 int nList; /* Number of elements in aList */
46979 ht_slot *aList; /* Pointer to sub-list content */
46982 const int nList = *pnList; /* Size of input list */
46983 int nMerge = 0; /* Number of elements in list aMerge */
46984 ht_slot *aMerge = 0; /* List to be merged */
46985 int iList; /* Index into input list */
46986 int iSub = 0; /* Index into aSub array */
46987 struct Sublist aSub[13]; /* Array of sub-lists */
46989 memset(aSub, 0, sizeof(aSub));
46990 assert( nList<=HASHTABLE_NPAGE && nList>0 );
46991 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
46993 for(iList=0; iList<nList; iList++){
46994 nMerge = 1;
46995 aMerge = &aList[iList];
46996 for(iSub=0; iList & (1<<iSub); iSub++){
46997 struct Sublist *p = &aSub[iSub];
46998 assert( p->aList && p->nList<=(1<<iSub) );
46999 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
47000 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
47002 aSub[iSub].aList = aMerge;
47003 aSub[iSub].nList = nMerge;
47006 for(iSub++; iSub<ArraySize(aSub); iSub++){
47007 if( nList & (1<<iSub) ){
47008 struct Sublist *p = &aSub[iSub];
47009 assert( p->nList<=(1<<iSub) );
47010 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
47011 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
47014 assert( aMerge==aList );
47015 *pnList = nMerge;
47017 #ifdef SQLITE_DEBUG
47019 int i;
47020 for(i=1; i<*pnList; i++){
47021 assert( aContent[aList[i]] > aContent[aList[i-1]] );
47024 #endif
47028 ** Free an iterator allocated by walIteratorInit().
47030 static void walIteratorFree(WalIterator *p){
47031 sqlite3ScratchFree(p);
47035 ** Construct a WalInterator object that can be used to loop over all
47036 ** pages in the WAL in ascending order. The caller must hold the checkpoint
47037 ** lock.
47039 ** On success, make *pp point to the newly allocated WalInterator object
47040 ** return SQLITE_OK. Otherwise, return an error code. If this routine
47041 ** returns an error, the value of *pp is undefined.
47043 ** The calling routine should invoke walIteratorFree() to destroy the
47044 ** WalIterator object when it has finished with it.
47046 static int walIteratorInit(Wal *pWal, WalIterator **pp){
47047 WalIterator *p; /* Return value */
47048 int nSegment; /* Number of segments to merge */
47049 u32 iLast; /* Last frame in log */
47050 int nByte; /* Number of bytes to allocate */
47051 int i; /* Iterator variable */
47052 ht_slot *aTmp; /* Temp space used by merge-sort */
47053 int rc = SQLITE_OK; /* Return Code */
47055 /* This routine only runs while holding the checkpoint lock. And
47056 ** it only runs if there is actually content in the log (mxFrame>0).
47058 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
47059 iLast = pWal->hdr.mxFrame;
47061 /* Allocate space for the WalIterator object. */
47062 nSegment = walFramePage(iLast) + 1;
47063 nByte = sizeof(WalIterator)
47064 + (nSegment-1)*sizeof(struct WalSegment)
47065 + iLast*sizeof(ht_slot);
47066 p = (WalIterator *)sqlite3ScratchMalloc(nByte);
47067 if( !p ){
47068 return SQLITE_NOMEM;
47070 memset(p, 0, nByte);
47071 p->nSegment = nSegment;
47073 /* Allocate temporary space used by the merge-sort routine. This block
47074 ** of memory will be freed before this function returns.
47076 aTmp = (ht_slot *)sqlite3ScratchMalloc(
47077 sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
47079 if( !aTmp ){
47080 rc = SQLITE_NOMEM;
47083 for(i=0; rc==SQLITE_OK && i<nSegment; i++){
47084 volatile ht_slot *aHash;
47085 u32 iZero;
47086 volatile u32 *aPgno;
47088 rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
47089 if( rc==SQLITE_OK ){
47090 int j; /* Counter variable */
47091 int nEntry; /* Number of entries in this segment */
47092 ht_slot *aIndex; /* Sorted index for this segment */
47094 aPgno++;
47095 if( (i+1)==nSegment ){
47096 nEntry = (int)(iLast - iZero);
47097 }else{
47098 nEntry = (int)((u32*)aHash - (u32*)aPgno);
47100 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
47101 iZero++;
47103 for(j=0; j<nEntry; j++){
47104 aIndex[j] = (ht_slot)j;
47106 walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
47107 p->aSegment[i].iZero = iZero;
47108 p->aSegment[i].nEntry = nEntry;
47109 p->aSegment[i].aIndex = aIndex;
47110 p->aSegment[i].aPgno = (u32 *)aPgno;
47113 sqlite3ScratchFree(aTmp);
47115 if( rc!=SQLITE_OK ){
47116 walIteratorFree(p);
47118 *pp = p;
47119 return rc;
47123 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
47124 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
47125 ** busy-handler function. Invoke it and retry the lock until either the
47126 ** lock is successfully obtained or the busy-handler returns 0.
47128 static int walBusyLock(
47129 Wal *pWal, /* WAL connection */
47130 int (*xBusy)(void*), /* Function to call when busy */
47131 void *pBusyArg, /* Context argument for xBusyHandler */
47132 int lockIdx, /* Offset of first byte to lock */
47133 int n /* Number of bytes to lock */
47135 int rc;
47136 do {
47137 rc = walLockExclusive(pWal, lockIdx, n);
47138 }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
47139 return rc;
47143 ** The cache of the wal-index header must be valid to call this function.
47144 ** Return the page-size in bytes used by the database.
47146 static int walPagesize(Wal *pWal){
47147 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47151 ** Copy as much content as we can from the WAL back into the database file
47152 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
47154 ** The amount of information copies from WAL to database might be limited
47155 ** by active readers. This routine will never overwrite a database page
47156 ** that a concurrent reader might be using.
47158 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
47159 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
47160 ** checkpoints are always run by a background thread or background
47161 ** process, foreground threads will never block on a lengthy fsync call.
47163 ** Fsync is called on the WAL before writing content out of the WAL and
47164 ** into the database. This ensures that if the new content is persistent
47165 ** in the WAL and can be recovered following a power-loss or hard reset.
47167 ** Fsync is also called on the database file if (and only if) the entire
47168 ** WAL content is copied into the database file. This second fsync makes
47169 ** it safe to delete the WAL since the new content will persist in the
47170 ** database file.
47172 ** This routine uses and updates the nBackfill field of the wal-index header.
47173 ** This is the only routine tha will increase the value of nBackfill.
47174 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
47175 ** its value.)
47177 ** The caller must be holding sufficient locks to ensure that no other
47178 ** checkpoint is running (in any other thread or process) at the same
47179 ** time.
47181 static int walCheckpoint(
47182 Wal *pWal, /* Wal connection */
47183 int eMode, /* One of PASSIVE, FULL or RESTART */
47184 int (*xBusyCall)(void*), /* Function to call when busy */
47185 void *pBusyArg, /* Context argument for xBusyHandler */
47186 int sync_flags, /* Flags for OsSync() (or 0) */
47187 u8 *zBuf /* Temporary buffer to use */
47189 int rc; /* Return code */
47190 int szPage; /* Database page-size */
47191 WalIterator *pIter = 0; /* Wal iterator context */
47192 u32 iDbpage = 0; /* Next database page to write */
47193 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
47194 u32 mxSafeFrame; /* Max frame that can be backfilled */
47195 u32 mxPage; /* Max database page to write */
47196 int i; /* Loop counter */
47197 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
47198 int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
47200 szPage = walPagesize(pWal);
47201 testcase( szPage<=32768 );
47202 testcase( szPage>=65536 );
47203 pInfo = walCkptInfo(pWal);
47204 if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
47206 /* Allocate the iterator */
47207 rc = walIteratorInit(pWal, &pIter);
47208 if( rc!=SQLITE_OK ){
47209 return rc;
47211 assert( pIter );
47213 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
47215 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
47216 ** safe to write into the database. Frames beyond mxSafeFrame might
47217 ** overwrite database pages that are in use by active readers and thus
47218 ** cannot be backfilled from the WAL.
47220 mxSafeFrame = pWal->hdr.mxFrame;
47221 mxPage = pWal->hdr.nPage;
47222 for(i=1; i<WAL_NREADER; i++){
47223 u32 y = pInfo->aReadMark[i];
47224 if( mxSafeFrame>y ){
47225 assert( y<=pWal->hdr.mxFrame );
47226 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
47227 if( rc==SQLITE_OK ){
47228 pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
47229 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47230 }else if( rc==SQLITE_BUSY ){
47231 mxSafeFrame = y;
47232 xBusy = 0;
47233 }else{
47234 goto walcheckpoint_out;
47239 if( pInfo->nBackfill<mxSafeFrame
47240 && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
47242 i64 nSize; /* Current size of database file */
47243 u32 nBackfill = pInfo->nBackfill;
47245 /* Sync the WAL to disk */
47246 if( sync_flags ){
47247 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
47250 /* If the database may grow as a result of this checkpoint, hint
47251 ** about the eventual size of the db file to the VFS layer.
47253 if( rc==SQLITE_OK ){
47254 i64 nReq = ((i64)mxPage * szPage);
47255 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
47256 if( rc==SQLITE_OK && nSize<nReq ){
47257 sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
47262 /* Iterate through the contents of the WAL, copying data to the db file. */
47263 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
47264 i64 iOffset;
47265 assert( walFramePgno(pWal, iFrame)==iDbpage );
47266 if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
47267 iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
47268 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
47269 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
47270 if( rc!=SQLITE_OK ) break;
47271 iOffset = (iDbpage-1)*(i64)szPage;
47272 testcase( IS_BIG_INT(iOffset) );
47273 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
47274 if( rc!=SQLITE_OK ) break;
47277 /* If work was actually accomplished... */
47278 if( rc==SQLITE_OK ){
47279 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
47280 i64 szDb = pWal->hdr.nPage*(i64)szPage;
47281 testcase( IS_BIG_INT(szDb) );
47282 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
47283 if( rc==SQLITE_OK && sync_flags ){
47284 rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
47287 if( rc==SQLITE_OK ){
47288 pInfo->nBackfill = mxSafeFrame;
47292 /* Release the reader lock held while backfilling */
47293 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
47296 if( rc==SQLITE_BUSY ){
47297 /* Reset the return code so as not to report a checkpoint failure
47298 ** just because there are active readers. */
47299 rc = SQLITE_OK;
47302 /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
47303 ** file has been copied into the database file, then block until all
47304 ** readers have finished using the wal file. This ensures that the next
47305 ** process to write to the database restarts the wal file.
47307 if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47308 assert( pWal->writeLock );
47309 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
47310 rc = SQLITE_BUSY;
47311 }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
47312 assert( mxSafeFrame==pWal->hdr.mxFrame );
47313 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
47314 if( rc==SQLITE_OK ){
47315 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
47320 walcheckpoint_out:
47321 walIteratorFree(pIter);
47322 return rc;
47326 ** If the WAL file is currently larger than nMax bytes in size, truncate
47327 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
47329 static void walLimitSize(Wal *pWal, i64 nMax){
47330 i64 sz;
47331 int rx;
47332 sqlite3BeginBenignMalloc();
47333 rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
47334 if( rx==SQLITE_OK && (sz > nMax ) ){
47335 rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
47337 sqlite3EndBenignMalloc();
47338 if( rx ){
47339 sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
47344 ** Close a connection to a log file.
47346 SQLITE_PRIVATE int sqlite3WalClose(
47347 Wal *pWal, /* Wal to close */
47348 int sync_flags, /* Flags to pass to OsSync() (or 0) */
47349 int nBuf,
47350 u8 *zBuf /* Buffer of at least nBuf bytes */
47352 int rc = SQLITE_OK;
47353 if( pWal ){
47354 int isDelete = 0; /* True to unlink wal and wal-index files */
47356 /* If an EXCLUSIVE lock can be obtained on the database file (using the
47357 ** ordinary, rollback-mode locking methods, this guarantees that the
47358 ** connection associated with this log file is the only connection to
47359 ** the database. In this case checkpoint the database and unlink both
47360 ** the wal and wal-index files.
47362 ** The EXCLUSIVE lock is not released before returning.
47364 rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
47365 if( rc==SQLITE_OK ){
47366 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
47367 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
47369 rc = sqlite3WalCheckpoint(
47370 pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
47372 if( rc==SQLITE_OK ){
47373 int bPersist = -1;
47374 sqlite3OsFileControlHint(
47375 pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
47377 if( bPersist!=1 ){
47378 /* Try to delete the WAL file if the checkpoint completed and
47379 ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
47380 ** mode (!bPersist) */
47381 isDelete = 1;
47382 }else if( pWal->mxWalSize>=0 ){
47383 /* Try to truncate the WAL file to zero bytes if the checkpoint
47384 ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
47385 ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
47386 ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
47387 ** to zero bytes as truncating to the journal_size_limit might
47388 ** leave a corrupt WAL file on disk. */
47389 walLimitSize(pWal, 0);
47394 walIndexClose(pWal, isDelete);
47395 sqlite3OsClose(pWal->pWalFd);
47396 if( isDelete ){
47397 sqlite3BeginBenignMalloc();
47398 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
47399 sqlite3EndBenignMalloc();
47401 WALTRACE(("WAL%p: closed\n", pWal));
47402 sqlite3_free((void *)pWal->apWiData);
47403 sqlite3_free(pWal);
47405 return rc;
47409 ** Try to read the wal-index header. Return 0 on success and 1 if
47410 ** there is a problem.
47412 ** The wal-index is in shared memory. Another thread or process might
47413 ** be writing the header at the same time this procedure is trying to
47414 ** read it, which might result in inconsistency. A dirty read is detected
47415 ** by verifying that both copies of the header are the same and also by
47416 ** a checksum on the header.
47418 ** If and only if the read is consistent and the header is different from
47419 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
47420 ** and *pChanged is set to 1.
47422 ** If the checksum cannot be verified return non-zero. If the header
47423 ** is read successfully and the checksum verified, return zero.
47425 static int walIndexTryHdr(Wal *pWal, int *pChanged){
47426 u32 aCksum[2]; /* Checksum on the header content */
47427 WalIndexHdr h1, h2; /* Two copies of the header content */
47428 WalIndexHdr volatile *aHdr; /* Header in shared memory */
47430 /* The first page of the wal-index must be mapped at this point. */
47431 assert( pWal->nWiData>0 && pWal->apWiData[0] );
47433 /* Read the header. This might happen concurrently with a write to the
47434 ** same area of shared memory on a different CPU in a SMP,
47435 ** meaning it is possible that an inconsistent snapshot is read
47436 ** from the file. If this happens, return non-zero.
47438 ** There are two copies of the header at the beginning of the wal-index.
47439 ** When reading, read [0] first then [1]. Writes are in the reverse order.
47440 ** Memory barriers are used to prevent the compiler or the hardware from
47441 ** reordering the reads and writes.
47443 aHdr = walIndexHdr(pWal);
47444 memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
47445 walShmBarrier(pWal);
47446 memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
47448 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
47449 return 1; /* Dirty read */
47451 if( h1.isInit==0 ){
47452 return 1; /* Malformed header - probably all zeros */
47454 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
47455 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
47456 return 1; /* Checksum does not match */
47459 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
47460 *pChanged = 1;
47461 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
47462 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47463 testcase( pWal->szPage<=32768 );
47464 testcase( pWal->szPage>=65536 );
47467 /* The header was successfully read. Return zero. */
47468 return 0;
47472 ** Read the wal-index header from the wal-index and into pWal->hdr.
47473 ** If the wal-header appears to be corrupt, try to reconstruct the
47474 ** wal-index from the WAL before returning.
47476 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
47477 ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
47478 ** to 0.
47480 ** If the wal-index header is successfully read, return SQLITE_OK.
47481 ** Otherwise an SQLite error code.
47483 static int walIndexReadHdr(Wal *pWal, int *pChanged){
47484 int rc; /* Return code */
47485 int badHdr; /* True if a header read failed */
47486 volatile u32 *page0; /* Chunk of wal-index containing header */
47488 /* Ensure that page 0 of the wal-index (the page that contains the
47489 ** wal-index header) is mapped. Return early if an error occurs here.
47491 assert( pChanged );
47492 rc = walIndexPage(pWal, 0, &page0);
47493 if( rc!=SQLITE_OK ){
47494 return rc;
47496 assert( page0 || pWal->writeLock==0 );
47498 /* If the first page of the wal-index has been mapped, try to read the
47499 ** wal-index header immediately, without holding any lock. This usually
47500 ** works, but may fail if the wal-index header is corrupt or currently
47501 ** being modified by another thread or process.
47503 badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
47505 /* If the first attempt failed, it might have been due to a race
47506 ** with a writer. So get a WRITE lock and try again.
47508 assert( badHdr==0 || pWal->writeLock==0 );
47509 if( badHdr ){
47510 if( pWal->readOnly & WAL_SHM_RDONLY ){
47511 if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
47512 walUnlockShared(pWal, WAL_WRITE_LOCK);
47513 rc = SQLITE_READONLY_RECOVERY;
47515 }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
47516 pWal->writeLock = 1;
47517 if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
47518 badHdr = walIndexTryHdr(pWal, pChanged);
47519 if( badHdr ){
47520 /* If the wal-index header is still malformed even while holding
47521 ** a WRITE lock, it can only mean that the header is corrupted and
47522 ** needs to be reconstructed. So run recovery to do exactly that.
47524 rc = walIndexRecover(pWal);
47525 *pChanged = 1;
47528 pWal->writeLock = 0;
47529 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47533 /* If the header is read successfully, check the version number to make
47534 ** sure the wal-index was not constructed with some future format that
47535 ** this version of SQLite cannot understand.
47537 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
47538 rc = SQLITE_CANTOPEN_BKPT;
47541 return rc;
47545 ** This is the value that walTryBeginRead returns when it needs to
47546 ** be retried.
47548 #define WAL_RETRY (-1)
47551 ** Attempt to start a read transaction. This might fail due to a race or
47552 ** other transient condition. When that happens, it returns WAL_RETRY to
47553 ** indicate to the caller that it is safe to retry immediately.
47555 ** On success return SQLITE_OK. On a permanent failure (such an
47556 ** I/O error or an SQLITE_BUSY because another process is running
47557 ** recovery) return a positive error code.
47559 ** The useWal parameter is true to force the use of the WAL and disable
47560 ** the case where the WAL is bypassed because it has been completely
47561 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
47562 ** to make a copy of the wal-index header into pWal->hdr. If the
47563 ** wal-index header has changed, *pChanged is set to 1 (as an indication
47564 ** to the caller that the local paget cache is obsolete and needs to be
47565 ** flushed.) When useWal==1, the wal-index header is assumed to already
47566 ** be loaded and the pChanged parameter is unused.
47568 ** The caller must set the cnt parameter to the number of prior calls to
47569 ** this routine during the current read attempt that returned WAL_RETRY.
47570 ** This routine will start taking more aggressive measures to clear the
47571 ** race conditions after multiple WAL_RETRY returns, and after an excessive
47572 ** number of errors will ultimately return SQLITE_PROTOCOL. The
47573 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
47574 ** and is not honoring the locking protocol. There is a vanishingly small
47575 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
47576 ** bad luck when there is lots of contention for the wal-index, but that
47577 ** possibility is so small that it can be safely neglected, we believe.
47579 ** On success, this routine obtains a read lock on
47580 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
47581 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
47582 ** that means the Wal does not hold any read lock. The reader must not
47583 ** access any database page that is modified by a WAL frame up to and
47584 ** including frame number aReadMark[pWal->readLock]. The reader will
47585 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
47586 ** Or if pWal->readLock==0, then the reader will ignore the WAL
47587 ** completely and get all content directly from the database file.
47588 ** If the useWal parameter is 1 then the WAL will never be ignored and
47589 ** this routine will always set pWal->readLock>0 on success.
47590 ** When the read transaction is completed, the caller must release the
47591 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
47593 ** This routine uses the nBackfill and aReadMark[] fields of the header
47594 ** to select a particular WAL_READ_LOCK() that strives to let the
47595 ** checkpoint process do as much work as possible. This routine might
47596 ** update values of the aReadMark[] array in the header, but if it does
47597 ** so it takes care to hold an exclusive lock on the corresponding
47598 ** WAL_READ_LOCK() while changing values.
47600 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
47601 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
47602 u32 mxReadMark; /* Largest aReadMark[] value */
47603 int mxI; /* Index of largest aReadMark[] value */
47604 int i; /* Loop counter */
47605 int rc = SQLITE_OK; /* Return code */
47607 assert( pWal->readLock<0 ); /* Not currently locked */
47609 /* Take steps to avoid spinning forever if there is a protocol error.
47611 ** Circumstances that cause a RETRY should only last for the briefest
47612 ** instances of time. No I/O or other system calls are done while the
47613 ** locks are held, so the locks should not be held for very long. But
47614 ** if we are unlucky, another process that is holding a lock might get
47615 ** paged out or take a page-fault that is time-consuming to resolve,
47616 ** during the few nanoseconds that it is holding the lock. In that case,
47617 ** it might take longer than normal for the lock to free.
47619 ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
47620 ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
47621 ** is more of a scheduler yield than an actual delay. But on the 10th
47622 ** an subsequent retries, the delays start becoming longer and longer,
47623 ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
47624 ** The total delay time before giving up is less than 1 second.
47626 if( cnt>5 ){
47627 int nDelay = 1; /* Pause time in microseconds */
47628 if( cnt>100 ){
47629 VVA_ONLY( pWal->lockError = 1; )
47630 return SQLITE_PROTOCOL;
47632 if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
47633 sqlite3OsSleep(pWal->pVfs, nDelay);
47636 if( !useWal ){
47637 rc = walIndexReadHdr(pWal, pChanged);
47638 if( rc==SQLITE_BUSY ){
47639 /* If there is not a recovery running in another thread or process
47640 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
47641 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
47642 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
47643 ** would be technically correct. But the race is benign since with
47644 ** WAL_RETRY this routine will be called again and will probably be
47645 ** right on the second iteration.
47647 if( pWal->apWiData[0]==0 ){
47648 /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
47649 ** We assume this is a transient condition, so return WAL_RETRY. The
47650 ** xShmMap() implementation used by the default unix and win32 VFS
47651 ** modules may return SQLITE_BUSY due to a race condition in the
47652 ** code that determines whether or not the shared-memory region
47653 ** must be zeroed before the requested page is returned.
47655 rc = WAL_RETRY;
47656 }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
47657 walUnlockShared(pWal, WAL_RECOVER_LOCK);
47658 rc = WAL_RETRY;
47659 }else if( rc==SQLITE_BUSY ){
47660 rc = SQLITE_BUSY_RECOVERY;
47663 if( rc!=SQLITE_OK ){
47664 return rc;
47668 pInfo = walCkptInfo(pWal);
47669 if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
47670 /* The WAL has been completely backfilled (or it is empty).
47671 ** and can be safely ignored.
47673 rc = walLockShared(pWal, WAL_READ_LOCK(0));
47674 walShmBarrier(pWal);
47675 if( rc==SQLITE_OK ){
47676 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
47677 /* It is not safe to allow the reader to continue here if frames
47678 ** may have been appended to the log before READ_LOCK(0) was obtained.
47679 ** When holding READ_LOCK(0), the reader ignores the entire log file,
47680 ** which implies that the database file contains a trustworthy
47681 ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
47682 ** happening, this is usually correct.
47684 ** However, if frames have been appended to the log (or if the log
47685 ** is wrapped and written for that matter) before the READ_LOCK(0)
47686 ** is obtained, that is not necessarily true. A checkpointer may
47687 ** have started to backfill the appended frames but crashed before
47688 ** it finished. Leaving a corrupt image in the database file.
47690 walUnlockShared(pWal, WAL_READ_LOCK(0));
47691 return WAL_RETRY;
47693 pWal->readLock = 0;
47694 return SQLITE_OK;
47695 }else if( rc!=SQLITE_BUSY ){
47696 return rc;
47700 /* If we get this far, it means that the reader will want to use
47701 ** the WAL to get at content from recent commits. The job now is
47702 ** to select one of the aReadMark[] entries that is closest to
47703 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
47705 mxReadMark = 0;
47706 mxI = 0;
47707 for(i=1; i<WAL_NREADER; i++){
47708 u32 thisMark = pInfo->aReadMark[i];
47709 if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
47710 assert( thisMark!=READMARK_NOT_USED );
47711 mxReadMark = thisMark;
47712 mxI = i;
47715 /* There was once an "if" here. The extra "{" is to preserve indentation. */
47717 if( (pWal->readOnly & WAL_SHM_RDONLY)==0
47718 && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
47720 for(i=1; i<WAL_NREADER; i++){
47721 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
47722 if( rc==SQLITE_OK ){
47723 mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
47724 mxI = i;
47725 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47726 break;
47727 }else if( rc!=SQLITE_BUSY ){
47728 return rc;
47732 if( mxI==0 ){
47733 assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
47734 return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
47737 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
47738 if( rc ){
47739 return rc==SQLITE_BUSY ? WAL_RETRY : rc;
47741 /* Now that the read-lock has been obtained, check that neither the
47742 ** value in the aReadMark[] array or the contents of the wal-index
47743 ** header have changed.
47745 ** It is necessary to check that the wal-index header did not change
47746 ** between the time it was read and when the shared-lock was obtained
47747 ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
47748 ** that the log file may have been wrapped by a writer, or that frames
47749 ** that occur later in the log than pWal->hdr.mxFrame may have been
47750 ** copied into the database by a checkpointer. If either of these things
47751 ** happened, then reading the database with the current value of
47752 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
47753 ** instead.
47755 ** This does not guarantee that the copy of the wal-index header is up to
47756 ** date before proceeding. That would not be possible without somehow
47757 ** blocking writers. It only guarantees that a dangerous checkpoint or
47758 ** log-wrap (either of which would require an exclusive lock on
47759 ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
47761 walShmBarrier(pWal);
47762 if( pInfo->aReadMark[mxI]!=mxReadMark
47763 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
47765 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
47766 return WAL_RETRY;
47767 }else{
47768 assert( mxReadMark<=pWal->hdr.mxFrame );
47769 pWal->readLock = (i16)mxI;
47772 return rc;
47776 ** Begin a read transaction on the database.
47778 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
47779 ** it takes a snapshot of the state of the WAL and wal-index for the current
47780 ** instant in time. The current thread will continue to use this snapshot.
47781 ** Other threads might append new content to the WAL and wal-index but
47782 ** that extra content is ignored by the current thread.
47784 ** If the database contents have changes since the previous read
47785 ** transaction, then *pChanged is set to 1 before returning. The
47786 ** Pager layer will use this to know that is cache is stale and
47787 ** needs to be flushed.
47789 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
47790 int rc; /* Return code */
47791 int cnt = 0; /* Number of TryBeginRead attempts */
47794 rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
47795 }while( rc==WAL_RETRY );
47796 testcase( (rc&0xff)==SQLITE_BUSY );
47797 testcase( (rc&0xff)==SQLITE_IOERR );
47798 testcase( rc==SQLITE_PROTOCOL );
47799 testcase( rc==SQLITE_OK );
47800 return rc;
47804 ** Finish with a read transaction. All this does is release the
47805 ** read-lock.
47807 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
47808 sqlite3WalEndWriteTransaction(pWal);
47809 if( pWal->readLock>=0 ){
47810 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
47811 pWal->readLock = -1;
47816 ** Search the wal file for page pgno. If found, set *piRead to the frame that
47817 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
47818 ** to zero.
47820 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
47821 ** error does occur, the final value of *piRead is undefined.
47823 SQLITE_PRIVATE int sqlite3WalFindFrame(
47824 Wal *pWal, /* WAL handle */
47825 Pgno pgno, /* Database page number to read data for */
47826 u32 *piRead /* OUT: Frame number (or zero) */
47828 u32 iRead = 0; /* If !=0, WAL frame to return data from */
47829 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
47830 int iHash; /* Used to loop through N hash tables */
47832 /* This routine is only be called from within a read transaction. */
47833 assert( pWal->readLock>=0 || pWal->lockError );
47835 /* If the "last page" field of the wal-index header snapshot is 0, then
47836 ** no data will be read from the wal under any circumstances. Return early
47837 ** in this case as an optimization. Likewise, if pWal->readLock==0,
47838 ** then the WAL is ignored by the reader so return early, as if the
47839 ** WAL were empty.
47841 if( iLast==0 || pWal->readLock==0 ){
47842 *piRead = 0;
47843 return SQLITE_OK;
47846 /* Search the hash table or tables for an entry matching page number
47847 ** pgno. Each iteration of the following for() loop searches one
47848 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
47850 ** This code might run concurrently to the code in walIndexAppend()
47851 ** that adds entries to the wal-index (and possibly to this hash
47852 ** table). This means the value just read from the hash
47853 ** slot (aHash[iKey]) may have been added before or after the
47854 ** current read transaction was opened. Values added after the
47855 ** read transaction was opened may have been written incorrectly -
47856 ** i.e. these slots may contain garbage data. However, we assume
47857 ** that any slots written before the current read transaction was
47858 ** opened remain unmodified.
47860 ** For the reasons above, the if(...) condition featured in the inner
47861 ** loop of the following block is more stringent that would be required
47862 ** if we had exclusive access to the hash-table:
47864 ** (aPgno[iFrame]==pgno):
47865 ** This condition filters out normal hash-table collisions.
47867 ** (iFrame<=iLast):
47868 ** This condition filters out entries that were added to the hash
47869 ** table after the current read-transaction had started.
47871 for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
47872 volatile ht_slot *aHash; /* Pointer to hash table */
47873 volatile u32 *aPgno; /* Pointer to array of page numbers */
47874 u32 iZero; /* Frame number corresponding to aPgno[0] */
47875 int iKey; /* Hash slot index */
47876 int nCollide; /* Number of hash collisions remaining */
47877 int rc; /* Error code */
47879 rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
47880 if( rc!=SQLITE_OK ){
47881 return rc;
47883 nCollide = HASHTABLE_NSLOT;
47884 for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
47885 u32 iFrame = aHash[iKey] + iZero;
47886 if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
47887 /* assert( iFrame>iRead ); -- not true if there is corruption */
47888 iRead = iFrame;
47890 if( (nCollide--)==0 ){
47891 return SQLITE_CORRUPT_BKPT;
47896 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47897 /* If expensive assert() statements are available, do a linear search
47898 ** of the wal-index file content. Make sure the results agree with the
47899 ** result obtained using the hash indexes above. */
47901 u32 iRead2 = 0;
47902 u32 iTest;
47903 for(iTest=iLast; iTest>0; iTest--){
47904 if( walFramePgno(pWal, iTest)==pgno ){
47905 iRead2 = iTest;
47906 break;
47909 assert( iRead==iRead2 );
47911 #endif
47913 *piRead = iRead;
47914 return SQLITE_OK;
47918 ** Read the contents of frame iRead from the wal file into buffer pOut
47919 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
47920 ** error code otherwise.
47922 SQLITE_PRIVATE int sqlite3WalReadFrame(
47923 Wal *pWal, /* WAL handle */
47924 u32 iRead, /* Frame to read */
47925 int nOut, /* Size of buffer pOut in bytes */
47926 u8 *pOut /* Buffer to write page data to */
47928 int sz;
47929 i64 iOffset;
47930 sz = pWal->hdr.szPage;
47931 sz = (sz&0xfe00) + ((sz&0x0001)<<16);
47932 testcase( sz<=32768 );
47933 testcase( sz>=65536 );
47934 iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
47935 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
47936 return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
47940 ** Return the size of the database in pages (or zero, if unknown).
47942 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
47943 if( pWal && ALWAYS(pWal->readLock>=0) ){
47944 return pWal->hdr.nPage;
47946 return 0;
47951 ** This function starts a write transaction on the WAL.
47953 ** A read transaction must have already been started by a prior call
47954 ** to sqlite3WalBeginReadTransaction().
47956 ** If another thread or process has written into the database since
47957 ** the read transaction was started, then it is not possible for this
47958 ** thread to write as doing so would cause a fork. So this routine
47959 ** returns SQLITE_BUSY in that case and no write transaction is started.
47961 ** There can only be a single writer active at a time.
47963 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
47964 int rc;
47966 /* Cannot start a write transaction without first holding a read
47967 ** transaction. */
47968 assert( pWal->readLock>=0 );
47970 if( pWal->readOnly ){
47971 return SQLITE_READONLY;
47974 /* Only one writer allowed at a time. Get the write lock. Return
47975 ** SQLITE_BUSY if unable.
47977 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
47978 if( rc ){
47979 return rc;
47981 pWal->writeLock = 1;
47983 /* If another connection has written to the database file since the
47984 ** time the read transaction on this connection was started, then
47985 ** the write is disallowed.
47987 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
47988 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47989 pWal->writeLock = 0;
47990 rc = SQLITE_BUSY_SNAPSHOT;
47993 return rc;
47997 ** End a write transaction. The commit has already been done. This
47998 ** routine merely releases the lock.
48000 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
48001 if( pWal->writeLock ){
48002 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48003 pWal->writeLock = 0;
48004 pWal->truncateOnCommit = 0;
48006 return SQLITE_OK;
48010 ** If any data has been written (but not committed) to the log file, this
48011 ** function moves the write-pointer back to the start of the transaction.
48013 ** Additionally, the callback function is invoked for each frame written
48014 ** to the WAL since the start of the transaction. If the callback returns
48015 ** other than SQLITE_OK, it is not invoked again and the error code is
48016 ** returned to the caller.
48018 ** Otherwise, if the callback function does not return an error, this
48019 ** function returns SQLITE_OK.
48021 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
48022 int rc = SQLITE_OK;
48023 if( ALWAYS(pWal->writeLock) ){
48024 Pgno iMax = pWal->hdr.mxFrame;
48025 Pgno iFrame;
48027 /* Restore the clients cache of the wal-index header to the state it
48028 ** was in before the client began writing to the database.
48030 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
48032 for(iFrame=pWal->hdr.mxFrame+1;
48033 ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
48034 iFrame++
48036 /* This call cannot fail. Unless the page for which the page number
48037 ** is passed as the second argument is (a) in the cache and
48038 ** (b) has an outstanding reference, then xUndo is either a no-op
48039 ** (if (a) is false) or simply expels the page from the cache (if (b)
48040 ** is false).
48042 ** If the upper layer is doing a rollback, it is guaranteed that there
48043 ** are no outstanding references to any page other than page 1. And
48044 ** page 1 is never written to the log until the transaction is
48045 ** committed. As a result, the call to xUndo may not fail.
48047 assert( walFramePgno(pWal, iFrame)!=1 );
48048 rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
48050 if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
48052 assert( rc==SQLITE_OK );
48053 return rc;
48057 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
48058 ** values. This function populates the array with values required to
48059 ** "rollback" the write position of the WAL handle back to the current
48060 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
48062 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
48063 assert( pWal->writeLock );
48064 aWalData[0] = pWal->hdr.mxFrame;
48065 aWalData[1] = pWal->hdr.aFrameCksum[0];
48066 aWalData[2] = pWal->hdr.aFrameCksum[1];
48067 aWalData[3] = pWal->nCkpt;
48071 ** Move the write position of the WAL back to the point identified by
48072 ** the values in the aWalData[] array. aWalData must point to an array
48073 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
48074 ** by a call to WalSavepoint().
48076 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
48077 int rc = SQLITE_OK;
48079 assert( pWal->writeLock );
48080 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
48082 if( aWalData[3]!=pWal->nCkpt ){
48083 /* This savepoint was opened immediately after the write-transaction
48084 ** was started. Right after that, the writer decided to wrap around
48085 ** to the start of the log. Update the savepoint values to match.
48087 aWalData[0] = 0;
48088 aWalData[3] = pWal->nCkpt;
48091 if( aWalData[0]<pWal->hdr.mxFrame ){
48092 pWal->hdr.mxFrame = aWalData[0];
48093 pWal->hdr.aFrameCksum[0] = aWalData[1];
48094 pWal->hdr.aFrameCksum[1] = aWalData[2];
48095 walCleanupHash(pWal);
48098 return rc;
48103 ** This function is called just before writing a set of frames to the log
48104 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
48105 ** to the current log file, it is possible to overwrite the start of the
48106 ** existing log file with the new frames (i.e. "reset" the log). If so,
48107 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
48108 ** unchanged.
48110 ** SQLITE_OK is returned if no error is encountered (regardless of whether
48111 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
48112 ** if an error occurs.
48114 static int walRestartLog(Wal *pWal){
48115 int rc = SQLITE_OK;
48116 int cnt;
48118 if( pWal->readLock==0 ){
48119 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
48120 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
48121 if( pInfo->nBackfill>0 ){
48122 u32 salt1;
48123 sqlite3_randomness(4, &salt1);
48124 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48125 if( rc==SQLITE_OK ){
48126 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
48127 ** readers are currently using the WAL), then the transactions
48128 ** frames will overwrite the start of the existing log. Update the
48129 ** wal-index header to reflect this.
48131 ** In theory it would be Ok to update the cache of the header only
48132 ** at this point. But updating the actual wal-index header is also
48133 ** safe and means there is no special case for sqlite3WalUndo()
48134 ** to handle if this transaction is rolled back.
48136 int i; /* Loop counter */
48137 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
48139 pWal->nCkpt++;
48140 pWal->hdr.mxFrame = 0;
48141 sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
48142 aSalt[1] = salt1;
48143 walIndexWriteHdr(pWal);
48144 pInfo->nBackfill = 0;
48145 pInfo->aReadMark[1] = 0;
48146 for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
48147 assert( pInfo->aReadMark[0]==0 );
48148 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48149 }else if( rc!=SQLITE_BUSY ){
48150 return rc;
48153 walUnlockShared(pWal, WAL_READ_LOCK(0));
48154 pWal->readLock = -1;
48155 cnt = 0;
48157 int notUsed;
48158 rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
48159 }while( rc==WAL_RETRY );
48160 assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
48161 testcase( (rc&0xff)==SQLITE_IOERR );
48162 testcase( rc==SQLITE_PROTOCOL );
48163 testcase( rc==SQLITE_OK );
48165 return rc;
48169 ** Information about the current state of the WAL file and where
48170 ** the next fsync should occur - passed from sqlite3WalFrames() into
48171 ** walWriteToLog().
48173 typedef struct WalWriter {
48174 Wal *pWal; /* The complete WAL information */
48175 sqlite3_file *pFd; /* The WAL file to which we write */
48176 sqlite3_int64 iSyncPoint; /* Fsync at this offset */
48177 int syncFlags; /* Flags for the fsync */
48178 int szPage; /* Size of one page */
48179 } WalWriter;
48182 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
48183 ** Do a sync when crossing the p->iSyncPoint boundary.
48185 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
48186 ** first write the part before iSyncPoint, then sync, then write the
48187 ** rest.
48189 static int walWriteToLog(
48190 WalWriter *p, /* WAL to write to */
48191 void *pContent, /* Content to be written */
48192 int iAmt, /* Number of bytes to write */
48193 sqlite3_int64 iOffset /* Start writing at this offset */
48195 int rc;
48196 if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
48197 int iFirstAmt = (int)(p->iSyncPoint - iOffset);
48198 rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
48199 if( rc ) return rc;
48200 iOffset += iFirstAmt;
48201 iAmt -= iFirstAmt;
48202 pContent = (void*)(iFirstAmt + (char*)pContent);
48203 assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
48204 rc = sqlite3OsSync(p->pFd, p->syncFlags);
48205 if( iAmt==0 || rc ) return rc;
48207 rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
48208 return rc;
48212 ** Write out a single frame of the WAL
48214 static int walWriteOneFrame(
48215 WalWriter *p, /* Where to write the frame */
48216 PgHdr *pPage, /* The page of the frame to be written */
48217 int nTruncate, /* The commit flag. Usually 0. >0 for commit */
48218 sqlite3_int64 iOffset /* Byte offset at which to write */
48220 int rc; /* Result code from subfunctions */
48221 void *pData; /* Data actually written */
48222 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
48223 #if defined(SQLITE_HAS_CODEC)
48224 if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
48225 #else
48226 pData = pPage->pData;
48227 #endif
48228 walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
48229 rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
48230 if( rc ) return rc;
48231 /* Write the page data */
48232 rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
48233 return rc;
48237 ** Write a set of frames to the log. The caller must hold the write-lock
48238 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
48240 SQLITE_PRIVATE int sqlite3WalFrames(
48241 Wal *pWal, /* Wal handle to write to */
48242 int szPage, /* Database page-size in bytes */
48243 PgHdr *pList, /* List of dirty pages to write */
48244 Pgno nTruncate, /* Database size after this commit */
48245 int isCommit, /* True if this is a commit */
48246 int sync_flags /* Flags to pass to OsSync() (or 0) */
48248 int rc; /* Used to catch return codes */
48249 u32 iFrame; /* Next frame address */
48250 PgHdr *p; /* Iterator to run through pList with. */
48251 PgHdr *pLast = 0; /* Last frame in list */
48252 int nExtra = 0; /* Number of extra copies of last page */
48253 int szFrame; /* The size of a single frame */
48254 i64 iOffset; /* Next byte to write in WAL file */
48255 WalWriter w; /* The writer */
48257 assert( pList );
48258 assert( pWal->writeLock );
48260 /* If this frame set completes a transaction, then nTruncate>0. If
48261 ** nTruncate==0 then this frame set does not complete the transaction. */
48262 assert( (isCommit!=0)==(nTruncate!=0) );
48264 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48265 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
48266 WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
48267 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
48269 #endif
48271 /* See if it is possible to write these frames into the start of the
48272 ** log file, instead of appending to it at pWal->hdr.mxFrame.
48274 if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
48275 return rc;
48278 /* If this is the first frame written into the log, write the WAL
48279 ** header to the start of the WAL file. See comments at the top of
48280 ** this source file for a description of the WAL header format.
48282 iFrame = pWal->hdr.mxFrame;
48283 if( iFrame==0 ){
48284 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
48285 u32 aCksum[2]; /* Checksum for wal-header */
48287 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
48288 sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
48289 sqlite3Put4byte(&aWalHdr[8], szPage);
48290 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
48291 if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
48292 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
48293 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
48294 sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
48295 sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
48297 pWal->szPage = szPage;
48298 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
48299 pWal->hdr.aFrameCksum[0] = aCksum[0];
48300 pWal->hdr.aFrameCksum[1] = aCksum[1];
48301 pWal->truncateOnCommit = 1;
48303 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
48304 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
48305 if( rc!=SQLITE_OK ){
48306 return rc;
48309 /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
48310 ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
48311 ** an out-of-order write following a WAL restart could result in
48312 ** database corruption. See the ticket:
48314 ** http://localhost:591/sqlite/info/ff5be73dee
48316 if( pWal->syncHeader && sync_flags ){
48317 rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
48318 if( rc ) return rc;
48321 assert( (int)pWal->szPage==szPage );
48323 /* Setup information needed to write frames into the WAL */
48324 w.pWal = pWal;
48325 w.pFd = pWal->pWalFd;
48326 w.iSyncPoint = 0;
48327 w.syncFlags = sync_flags;
48328 w.szPage = szPage;
48329 iOffset = walFrameOffset(iFrame+1, szPage);
48330 szFrame = szPage + WAL_FRAME_HDRSIZE;
48332 /* Write all frames into the log file exactly once */
48333 for(p=pList; p; p=p->pDirty){
48334 int nDbSize; /* 0 normally. Positive == commit flag */
48335 iFrame++;
48336 assert( iOffset==walFrameOffset(iFrame, szPage) );
48337 nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
48338 rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
48339 if( rc ) return rc;
48340 pLast = p;
48341 iOffset += szFrame;
48344 /* If this is the end of a transaction, then we might need to pad
48345 ** the transaction and/or sync the WAL file.
48347 ** Padding and syncing only occur if this set of frames complete a
48348 ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
48349 ** or synchonous==OFF, then no padding or syncing are needed.
48351 ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
48352 ** needed and only the sync is done. If padding is needed, then the
48353 ** final frame is repeated (with its commit mark) until the next sector
48354 ** boundary is crossed. Only the part of the WAL prior to the last
48355 ** sector boundary is synced; the part of the last frame that extends
48356 ** past the sector boundary is written after the sync.
48358 if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
48359 if( pWal->padToSectorBoundary ){
48360 int sectorSize = sqlite3SectorSize(pWal->pWalFd);
48361 w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
48362 while( iOffset<w.iSyncPoint ){
48363 rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
48364 if( rc ) return rc;
48365 iOffset += szFrame;
48366 nExtra++;
48368 }else{
48369 rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
48373 /* If this frame set completes the first transaction in the WAL and
48374 ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
48375 ** journal size limit, if possible.
48377 if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
48378 i64 sz = pWal->mxWalSize;
48379 if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
48380 sz = walFrameOffset(iFrame+nExtra+1, szPage);
48382 walLimitSize(pWal, sz);
48383 pWal->truncateOnCommit = 0;
48386 /* Append data to the wal-index. It is not necessary to lock the
48387 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
48388 ** guarantees that there are no other writers, and no data that may
48389 ** be in use by existing readers is being overwritten.
48391 iFrame = pWal->hdr.mxFrame;
48392 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
48393 iFrame++;
48394 rc = walIndexAppend(pWal, iFrame, p->pgno);
48396 while( rc==SQLITE_OK && nExtra>0 ){
48397 iFrame++;
48398 nExtra--;
48399 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
48402 if( rc==SQLITE_OK ){
48403 /* Update the private copy of the header. */
48404 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
48405 testcase( szPage<=32768 );
48406 testcase( szPage>=65536 );
48407 pWal->hdr.mxFrame = iFrame;
48408 if( isCommit ){
48409 pWal->hdr.iChange++;
48410 pWal->hdr.nPage = nTruncate;
48412 /* If this is a commit, update the wal-index header too. */
48413 if( isCommit ){
48414 walIndexWriteHdr(pWal);
48415 pWal->iCallback = iFrame;
48419 WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
48420 return rc;
48424 ** This routine is called to implement sqlite3_wal_checkpoint() and
48425 ** related interfaces.
48427 ** Obtain a CHECKPOINT lock and then backfill as much information as
48428 ** we can from WAL into the database.
48430 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
48431 ** callback. In this case this function runs a blocking checkpoint.
48433 SQLITE_PRIVATE int sqlite3WalCheckpoint(
48434 Wal *pWal, /* Wal connection */
48435 int eMode, /* PASSIVE, FULL or RESTART */
48436 int (*xBusy)(void*), /* Function to call when busy */
48437 void *pBusyArg, /* Context argument for xBusyHandler */
48438 int sync_flags, /* Flags to sync db file with (or 0) */
48439 int nBuf, /* Size of temporary buffer */
48440 u8 *zBuf, /* Temporary buffer to use */
48441 int *pnLog, /* OUT: Number of frames in WAL */
48442 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
48444 int rc; /* Return code */
48445 int isChanged = 0; /* True if a new wal-index header is loaded */
48446 int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
48448 assert( pWal->ckptLock==0 );
48449 assert( pWal->writeLock==0 );
48451 if( pWal->readOnly ) return SQLITE_READONLY;
48452 WALTRACE(("WAL%p: checkpoint begins\n", pWal));
48453 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
48454 if( rc ){
48455 /* Usually this is SQLITE_BUSY meaning that another thread or process
48456 ** is already running a checkpoint, or maybe a recovery. But it might
48457 ** also be SQLITE_IOERR. */
48458 return rc;
48460 pWal->ckptLock = 1;
48462 /* If this is a blocking-checkpoint, then obtain the write-lock as well
48463 ** to prevent any writers from running while the checkpoint is underway.
48464 ** This has to be done before the call to walIndexReadHdr() below.
48466 ** If the writer lock cannot be obtained, then a passive checkpoint is
48467 ** run instead. Since the checkpointer is not holding the writer lock,
48468 ** there is no point in blocking waiting for any readers. Assuming no
48469 ** other error occurs, this function will return SQLITE_BUSY to the caller.
48471 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
48472 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
48473 if( rc==SQLITE_OK ){
48474 pWal->writeLock = 1;
48475 }else if( rc==SQLITE_BUSY ){
48476 eMode2 = SQLITE_CHECKPOINT_PASSIVE;
48477 rc = SQLITE_OK;
48481 /* Read the wal-index header. */
48482 if( rc==SQLITE_OK ){
48483 rc = walIndexReadHdr(pWal, &isChanged);
48484 if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
48485 sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
48489 /* Copy data from the log to the database file. */
48490 if( rc==SQLITE_OK ){
48491 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
48492 rc = SQLITE_CORRUPT_BKPT;
48493 }else{
48494 rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
48497 /* If no error occurred, set the output variables. */
48498 if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
48499 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
48500 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
48504 if( isChanged ){
48505 /* If a new wal-index header was loaded before the checkpoint was
48506 ** performed, then the pager-cache associated with pWal is now
48507 ** out of date. So zero the cached wal-index header to ensure that
48508 ** next time the pager opens a snapshot on this database it knows that
48509 ** the cache needs to be reset.
48511 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
48514 /* Release the locks. */
48515 sqlite3WalEndWriteTransaction(pWal);
48516 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
48517 pWal->ckptLock = 0;
48518 WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
48519 return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
48522 /* Return the value to pass to a sqlite3_wal_hook callback, the
48523 ** number of frames in the WAL at the point of the last commit since
48524 ** sqlite3WalCallback() was called. If no commits have occurred since
48525 ** the last call, then return 0.
48527 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
48528 u32 ret = 0;
48529 if( pWal ){
48530 ret = pWal->iCallback;
48531 pWal->iCallback = 0;
48533 return (int)ret;
48537 ** This function is called to change the WAL subsystem into or out
48538 ** of locking_mode=EXCLUSIVE.
48540 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
48541 ** into locking_mode=NORMAL. This means that we must acquire a lock
48542 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
48543 ** or if the acquisition of the lock fails, then return 0. If the
48544 ** transition out of exclusive-mode is successful, return 1. This
48545 ** operation must occur while the pager is still holding the exclusive
48546 ** lock on the main database file.
48548 ** If op is one, then change from locking_mode=NORMAL into
48549 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
48550 ** be released. Return 1 if the transition is made and 0 if the
48551 ** WAL is already in exclusive-locking mode - meaning that this
48552 ** routine is a no-op. The pager must already hold the exclusive lock
48553 ** on the main database file before invoking this operation.
48555 ** If op is negative, then do a dry-run of the op==1 case but do
48556 ** not actually change anything. The pager uses this to see if it
48557 ** should acquire the database exclusive lock prior to invoking
48558 ** the op==1 case.
48560 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
48561 int rc;
48562 assert( pWal->writeLock==0 );
48563 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
48565 /* pWal->readLock is usually set, but might be -1 if there was a
48566 ** prior error while attempting to acquire are read-lock. This cannot
48567 ** happen if the connection is actually in exclusive mode (as no xShmLock
48568 ** locks are taken in this case). Nor should the pager attempt to
48569 ** upgrade to exclusive-mode following such an error.
48571 assert( pWal->readLock>=0 || pWal->lockError );
48572 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
48574 if( op==0 ){
48575 if( pWal->exclusiveMode ){
48576 pWal->exclusiveMode = 0;
48577 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
48578 pWal->exclusiveMode = 1;
48580 rc = pWal->exclusiveMode==0;
48581 }else{
48582 /* Already in locking_mode=NORMAL */
48583 rc = 0;
48585 }else if( op>0 ){
48586 assert( pWal->exclusiveMode==0 );
48587 assert( pWal->readLock>=0 );
48588 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
48589 pWal->exclusiveMode = 1;
48590 rc = 1;
48591 }else{
48592 rc = pWal->exclusiveMode==0;
48594 return rc;
48598 ** Return true if the argument is non-NULL and the WAL module is using
48599 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
48600 ** WAL module is using shared-memory, return false.
48602 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
48603 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
48606 #ifdef SQLITE_ENABLE_ZIPVFS
48608 ** If the argument is not NULL, it points to a Wal object that holds a
48609 ** read-lock. This function returns the database page-size if it is known,
48610 ** or zero if it is not (or if pWal is NULL).
48612 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
48613 assert( pWal==0 || pWal->readLock>=0 );
48614 return (pWal ? pWal->szPage : 0);
48616 #endif
48618 #endif /* #ifndef SQLITE_OMIT_WAL */
48620 /************** End of wal.c *************************************************/
48621 /************** Begin file btmutex.c *****************************************/
48623 ** 2007 August 27
48625 ** The author disclaims copyright to this source code. In place of
48626 ** a legal notice, here is a blessing:
48628 ** May you do good and not evil.
48629 ** May you find forgiveness for yourself and forgive others.
48630 ** May you share freely, never taking more than you give.
48632 *************************************************************************
48634 ** This file contains code used to implement mutexes on Btree objects.
48635 ** This code really belongs in btree.c. But btree.c is getting too
48636 ** big and we want to break it down some. This packaged seemed like
48637 ** a good breakout.
48639 /************** Include btreeInt.h in the middle of btmutex.c ****************/
48640 /************** Begin file btreeInt.h ****************************************/
48642 ** 2004 April 6
48644 ** The author disclaims copyright to this source code. In place of
48645 ** a legal notice, here is a blessing:
48647 ** May you do good and not evil.
48648 ** May you find forgiveness for yourself and forgive others.
48649 ** May you share freely, never taking more than you give.
48651 *************************************************************************
48652 ** This file implements a external (disk-based) database using BTrees.
48653 ** For a detailed discussion of BTrees, refer to
48655 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
48656 ** "Sorting And Searching", pages 473-480. Addison-Wesley
48657 ** Publishing Company, Reading, Massachusetts.
48659 ** The basic idea is that each page of the file contains N database
48660 ** entries and N+1 pointers to subpages.
48662 ** ----------------------------------------------------------------
48663 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
48664 ** ----------------------------------------------------------------
48666 ** All of the keys on the page that Ptr(0) points to have values less
48667 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
48668 ** values greater than Key(0) and less than Key(1). All of the keys
48669 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
48670 ** so forth.
48672 ** Finding a particular key requires reading O(log(M)) pages from the
48673 ** disk where M is the number of entries in the tree.
48675 ** In this implementation, a single file can hold one or more separate
48676 ** BTrees. Each BTree is identified by the index of its root page. The
48677 ** key and data for any entry are combined to form the "payload". A
48678 ** fixed amount of payload can be carried directly on the database
48679 ** page. If the payload is larger than the preset amount then surplus
48680 ** bytes are stored on overflow pages. The payload for an entry
48681 ** and the preceding pointer are combined to form a "Cell". Each
48682 ** page has a small header which contains the Ptr(N) pointer and other
48683 ** information such as the size of key and data.
48685 ** FORMAT DETAILS
48687 ** The file is divided into pages. The first page is called page 1,
48688 ** the second is page 2, and so forth. A page number of zero indicates
48689 ** "no such page". The page size can be any power of 2 between 512 and 65536.
48690 ** Each page can be either a btree page, a freelist page, an overflow
48691 ** page, or a pointer-map page.
48693 ** The first page is always a btree page. The first 100 bytes of the first
48694 ** page contain a special header (the "file header") that describes the file.
48695 ** The format of the file header is as follows:
48697 ** OFFSET SIZE DESCRIPTION
48698 ** 0 16 Header string: "SQLite format 3\000"
48699 ** 16 2 Page size in bytes.
48700 ** 18 1 File format write version
48701 ** 19 1 File format read version
48702 ** 20 1 Bytes of unused space at the end of each page
48703 ** 21 1 Max embedded payload fraction
48704 ** 22 1 Min embedded payload fraction
48705 ** 23 1 Min leaf payload fraction
48706 ** 24 4 File change counter
48707 ** 28 4 Reserved for future use
48708 ** 32 4 First freelist page
48709 ** 36 4 Number of freelist pages in the file
48710 ** 40 60 15 4-byte meta values passed to higher layers
48712 ** 40 4 Schema cookie
48713 ** 44 4 File format of schema layer
48714 ** 48 4 Size of page cache
48715 ** 52 4 Largest root-page (auto/incr_vacuum)
48716 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
48717 ** 60 4 User version
48718 ** 64 4 Incremental vacuum mode
48719 ** 68 4 unused
48720 ** 72 4 unused
48721 ** 76 4 unused
48723 ** All of the integer values are big-endian (most significant byte first).
48725 ** The file change counter is incremented when the database is changed
48726 ** This counter allows other processes to know when the file has changed
48727 ** and thus when they need to flush their cache.
48729 ** The max embedded payload fraction is the amount of the total usable
48730 ** space in a page that can be consumed by a single cell for standard
48731 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
48732 ** is to limit the maximum cell size so that at least 4 cells will fit
48733 ** on one page. Thus the default max embedded payload fraction is 64.
48735 ** If the payload for a cell is larger than the max payload, then extra
48736 ** payload is spilled to overflow pages. Once an overflow page is allocated,
48737 ** as many bytes as possible are moved into the overflow pages without letting
48738 ** the cell size drop below the min embedded payload fraction.
48740 ** The min leaf payload fraction is like the min embedded payload fraction
48741 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
48742 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
48743 ** not specified in the header.
48745 ** Each btree pages is divided into three sections: The header, the
48746 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
48747 ** file header that occurs before the page header.
48749 ** |----------------|
48750 ** | file header | 100 bytes. Page 1 only.
48751 ** |----------------|
48752 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
48753 ** |----------------|
48754 ** | cell pointer | | 2 bytes per cell. Sorted order.
48755 ** | array | | Grows downward
48756 ** | | v
48757 ** |----------------|
48758 ** | unallocated |
48759 ** | space |
48760 ** |----------------| ^ Grows upwards
48761 ** | cell content | | Arbitrary order interspersed with freeblocks.
48762 ** | area | | and free space fragments.
48763 ** |----------------|
48765 ** The page headers looks like this:
48767 ** OFFSET SIZE DESCRIPTION
48768 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
48769 ** 1 2 byte offset to the first freeblock
48770 ** 3 2 number of cells on this page
48771 ** 5 2 first byte of the cell content area
48772 ** 7 1 number of fragmented free bytes
48773 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
48775 ** The flags define the format of this btree page. The leaf flag means that
48776 ** this page has no children. The zerodata flag means that this page carries
48777 ** only keys and no data. The intkey flag means that the key is a integer
48778 ** which is stored in the key size entry of the cell header rather than in
48779 ** the payload area.
48781 ** The cell pointer array begins on the first byte after the page header.
48782 ** The cell pointer array contains zero or more 2-byte numbers which are
48783 ** offsets from the beginning of the page to the cell content in the cell
48784 ** content area. The cell pointers occur in sorted order. The system strives
48785 ** to keep free space after the last cell pointer so that new cells can
48786 ** be easily added without having to defragment the page.
48788 ** Cell content is stored at the very end of the page and grows toward the
48789 ** beginning of the page.
48791 ** Unused space within the cell content area is collected into a linked list of
48792 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
48793 ** to the first freeblock is given in the header. Freeblocks occur in
48794 ** increasing order. Because a freeblock must be at least 4 bytes in size,
48795 ** any group of 3 or fewer unused bytes in the cell content area cannot
48796 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
48797 ** a fragment. The total number of bytes in all fragments is recorded.
48798 ** in the page header at offset 7.
48800 ** SIZE DESCRIPTION
48801 ** 2 Byte offset of the next freeblock
48802 ** 2 Bytes in this freeblock
48804 ** Cells are of variable length. Cells are stored in the cell content area at
48805 ** the end of the page. Pointers to the cells are in the cell pointer array
48806 ** that immediately follows the page header. Cells is not necessarily
48807 ** contiguous or in order, but cell pointers are contiguous and in order.
48809 ** Cell content makes use of variable length integers. A variable
48810 ** length integer is 1 to 9 bytes where the lower 7 bits of each
48811 ** byte are used. The integer consists of all bytes that have bit 8 set and
48812 ** the first byte with bit 8 clear. The most significant byte of the integer
48813 ** appears first. A variable-length integer may not be more than 9 bytes long.
48814 ** As a special case, all 8 bytes of the 9th byte are used as data. This
48815 ** allows a 64-bit integer to be encoded in 9 bytes.
48817 ** 0x00 becomes 0x00000000
48818 ** 0x7f becomes 0x0000007f
48819 ** 0x81 0x00 becomes 0x00000080
48820 ** 0x82 0x00 becomes 0x00000100
48821 ** 0x80 0x7f becomes 0x0000007f
48822 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
48823 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
48825 ** Variable length integers are used for rowids and to hold the number of
48826 ** bytes of key and data in a btree cell.
48828 ** The content of a cell looks like this:
48830 ** SIZE DESCRIPTION
48831 ** 4 Page number of the left child. Omitted if leaf flag is set.
48832 ** var Number of bytes of data. Omitted if the zerodata flag is set.
48833 ** var Number of bytes of key. Or the key itself if intkey flag is set.
48834 ** * Payload
48835 ** 4 First page of the overflow chain. Omitted if no overflow
48837 ** Overflow pages form a linked list. Each page except the last is completely
48838 ** filled with data (pagesize - 4 bytes). The last page can have as little
48839 ** as 1 byte of data.
48841 ** SIZE DESCRIPTION
48842 ** 4 Page number of next overflow page
48843 ** * Data
48845 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
48846 ** file header points to the first in a linked list of trunk page. Each trunk
48847 ** page points to multiple leaf pages. The content of a leaf page is
48848 ** unspecified. A trunk page looks like this:
48850 ** SIZE DESCRIPTION
48851 ** 4 Page number of next trunk page
48852 ** 4 Number of leaf pointers on this page
48853 ** * zero or more pages numbers of leaves
48857 /* The following value is the maximum cell size assuming a maximum page
48858 ** size give above.
48860 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
48862 /* The maximum number of cells on a single page of the database. This
48863 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
48864 ** plus 2 bytes for the index to the cell in the page header). Such
48865 ** small cells will be rare, but they are possible.
48867 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
48869 /* Forward declarations */
48870 typedef struct MemPage MemPage;
48871 typedef struct BtLock BtLock;
48874 ** This is a magic string that appears at the beginning of every
48875 ** SQLite database in order to identify the file as a real database.
48877 ** You can change this value at compile-time by specifying a
48878 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
48879 ** header must be exactly 16 bytes including the zero-terminator so
48880 ** the string itself should be 15 characters long. If you change
48881 ** the header, then your custom library will not be able to read
48882 ** databases generated by the standard tools and the standard tools
48883 ** will not be able to read databases created by your custom library.
48885 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
48886 # define SQLITE_FILE_HEADER "SQLite format 3"
48887 #endif
48890 ** Page type flags. An ORed combination of these flags appear as the
48891 ** first byte of on-disk image of every BTree page.
48893 #define PTF_INTKEY 0x01
48894 #define PTF_ZERODATA 0x02
48895 #define PTF_LEAFDATA 0x04
48896 #define PTF_LEAF 0x08
48899 ** As each page of the file is loaded into memory, an instance of the following
48900 ** structure is appended and initialized to zero. This structure stores
48901 ** information about the page that is decoded from the raw file page.
48903 ** The pParent field points back to the parent page. This allows us to
48904 ** walk up the BTree from any leaf to the root. Care must be taken to
48905 ** unref() the parent page pointer when this page is no longer referenced.
48906 ** The pageDestructor() routine handles that chore.
48908 ** Access to all fields of this structure is controlled by the mutex
48909 ** stored in MemPage.pBt->mutex.
48911 struct MemPage {
48912 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
48913 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
48914 u8 intKey; /* True if intkey flag is set */
48915 u8 leaf; /* True if leaf flag is set */
48916 u8 hasData; /* True if this page stores data */
48917 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
48918 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
48919 u8 max1bytePayload; /* min(maxLocal,127) */
48920 u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
48921 u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
48922 u16 cellOffset; /* Index in aData of first cell pointer */
48923 u16 nFree; /* Number of free bytes on the page */
48924 u16 nCell; /* Number of cells on this page, local and ovfl */
48925 u16 maskPage; /* Mask for page offset */
48926 u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
48927 ** non-overflow cell */
48928 u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
48929 BtShared *pBt; /* Pointer to BtShared that this page is part of */
48930 u8 *aData; /* Pointer to disk image of the page data */
48931 u8 *aDataEnd; /* One byte past the end of usable data */
48932 u8 *aCellIdx; /* The cell index area */
48933 DbPage *pDbPage; /* Pager page handle */
48934 Pgno pgno; /* Page number for this page */
48938 ** The in-memory image of a disk page has the auxiliary information appended
48939 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
48940 ** that extra information.
48942 #define EXTRA_SIZE sizeof(MemPage)
48945 ** A linked list of the following structures is stored at BtShared.pLock.
48946 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
48947 ** is opened on the table with root page BtShared.iTable. Locks are removed
48948 ** from this list when a transaction is committed or rolled back, or when
48949 ** a btree handle is closed.
48951 struct BtLock {
48952 Btree *pBtree; /* Btree handle holding this lock */
48953 Pgno iTable; /* Root page of table */
48954 u8 eLock; /* READ_LOCK or WRITE_LOCK */
48955 BtLock *pNext; /* Next in BtShared.pLock list */
48958 /* Candidate values for BtLock.eLock */
48959 #define READ_LOCK 1
48960 #define WRITE_LOCK 2
48962 /* A Btree handle
48964 ** A database connection contains a pointer to an instance of
48965 ** this object for every database file that it has open. This structure
48966 ** is opaque to the database connection. The database connection cannot
48967 ** see the internals of this structure and only deals with pointers to
48968 ** this structure.
48970 ** For some database files, the same underlying database cache might be
48971 ** shared between multiple connections. In that case, each connection
48972 ** has it own instance of this object. But each instance of this object
48973 ** points to the same BtShared object. The database cache and the
48974 ** schema associated with the database file are all contained within
48975 ** the BtShared object.
48977 ** All fields in this structure are accessed under sqlite3.mutex.
48978 ** The pBt pointer itself may not be changed while there exists cursors
48979 ** in the referenced BtShared that point back to this Btree since those
48980 ** cursors have to go through this Btree to find their BtShared and
48981 ** they often do so without holding sqlite3.mutex.
48983 struct Btree {
48984 sqlite3 *db; /* The database connection holding this btree */
48985 BtShared *pBt; /* Sharable content of this btree */
48986 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
48987 u8 sharable; /* True if we can share pBt with another db */
48988 u8 locked; /* True if db currently has pBt locked */
48989 int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
48990 int nBackup; /* Number of backup operations reading this btree */
48991 Btree *pNext; /* List of other sharable Btrees from the same db */
48992 Btree *pPrev; /* Back pointer of the same list */
48993 #ifndef SQLITE_OMIT_SHARED_CACHE
48994 BtLock lock; /* Object used to lock page 1 */
48995 #endif
48999 ** Btree.inTrans may take one of the following values.
49001 ** If the shared-data extension is enabled, there may be multiple users
49002 ** of the Btree structure. At most one of these may open a write transaction,
49003 ** but any number may have active read transactions.
49005 #define TRANS_NONE 0
49006 #define TRANS_READ 1
49007 #define TRANS_WRITE 2
49010 ** An instance of this object represents a single database file.
49012 ** A single database file can be in use at the same time by two
49013 ** or more database connections. When two or more connections are
49014 ** sharing the same database file, each connection has it own
49015 ** private Btree object for the file and each of those Btrees points
49016 ** to this one BtShared object. BtShared.nRef is the number of
49017 ** connections currently sharing this database file.
49019 ** Fields in this structure are accessed under the BtShared.mutex
49020 ** mutex, except for nRef and pNext which are accessed under the
49021 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
49022 ** may not be modified once it is initially set as long as nRef>0.
49023 ** The pSchema field may be set once under BtShared.mutex and
49024 ** thereafter is unchanged as long as nRef>0.
49026 ** isPending:
49028 ** If a BtShared client fails to obtain a write-lock on a database
49029 ** table (because there exists one or more read-locks on the table),
49030 ** the shared-cache enters 'pending-lock' state and isPending is
49031 ** set to true.
49033 ** The shared-cache leaves the 'pending lock' state when either of
49034 ** the following occur:
49036 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
49037 ** 2) The number of locks held by other connections drops to zero.
49039 ** while in the 'pending-lock' state, no connection may start a new
49040 ** transaction.
49042 ** This feature is included to help prevent writer-starvation.
49044 struct BtShared {
49045 Pager *pPager; /* The page cache */
49046 sqlite3 *db; /* Database connection currently using this Btree */
49047 BtCursor *pCursor; /* A list of all open cursors */
49048 MemPage *pPage1; /* First page of the database */
49049 u8 openFlags; /* Flags to sqlite3BtreeOpen() */
49050 #ifndef SQLITE_OMIT_AUTOVACUUM
49051 u8 autoVacuum; /* True if auto-vacuum is enabled */
49052 u8 incrVacuum; /* True if incr-vacuum is enabled */
49053 u8 bDoTruncate; /* True to truncate db on commit */
49054 #endif
49055 u8 inTransaction; /* Transaction state */
49056 u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
49057 u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
49058 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
49059 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
49060 u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
49061 u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
49062 u32 pageSize; /* Total number of bytes on a page */
49063 u32 usableSize; /* Number of usable bytes on each page */
49064 int nTransaction; /* Number of open transactions (read + write) */
49065 u32 nPage; /* Number of pages in the database */
49066 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
49067 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
49068 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
49069 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
49070 #ifndef SQLITE_OMIT_SHARED_CACHE
49071 int nRef; /* Number of references to this structure */
49072 BtShared *pNext; /* Next on a list of sharable BtShared structs */
49073 BtLock *pLock; /* List of locks held on this shared-btree struct */
49074 Btree *pWriter; /* Btree with currently open write transaction */
49075 #endif
49076 u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
49080 ** Allowed values for BtShared.btsFlags
49082 #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
49083 #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
49084 #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
49085 #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
49086 #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
49087 #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
49088 #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
49091 ** An instance of the following structure is used to hold information
49092 ** about a cell. The parseCellPtr() function fills in this structure
49093 ** based on information extract from the raw disk page.
49095 typedef struct CellInfo CellInfo;
49096 struct CellInfo {
49097 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
49098 u8 *pCell; /* Pointer to the start of cell content */
49099 u32 nData; /* Number of bytes of data */
49100 u32 nPayload; /* Total amount of payload */
49101 u16 nHeader; /* Size of the cell content header in bytes */
49102 u16 nLocal; /* Amount of payload held locally */
49103 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
49104 u16 nSize; /* Size of the cell content on the main b-tree page */
49108 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
49109 ** this will be declared corrupt. This value is calculated based on a
49110 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
49111 ** root-node and 3 for all other internal nodes.
49113 ** If a tree that appears to be taller than this is encountered, it is
49114 ** assumed that the database is corrupt.
49116 #define BTCURSOR_MAX_DEPTH 20
49119 ** A cursor is a pointer to a particular entry within a particular
49120 ** b-tree within a database file.
49122 ** The entry is identified by its MemPage and the index in
49123 ** MemPage.aCell[] of the entry.
49125 ** A single database file can be shared by two more database connections,
49126 ** but cursors cannot be shared. Each cursor is associated with a
49127 ** particular database connection identified BtCursor.pBtree.db.
49129 ** Fields in this structure are accessed under the BtShared.mutex
49130 ** found at self->pBt->mutex.
49132 struct BtCursor {
49133 Btree *pBtree; /* The Btree to which this cursor belongs */
49134 BtShared *pBt; /* The BtShared this cursor points to */
49135 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
49136 struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
49137 #ifndef SQLITE_OMIT_INCRBLOB
49138 Pgno *aOverflow; /* Cache of overflow page locations */
49139 #endif
49140 Pgno pgnoRoot; /* The root page of this tree */
49141 sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
49142 CellInfo info; /* A parse of the cell we are pointing at */
49143 i64 nKey; /* Size of pKey, or last integer key */
49144 void *pKey; /* Saved key that was cursor's last known position */
49145 int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
49146 u8 wrFlag; /* True if writable */
49147 u8 atLast; /* Cursor pointing to the last entry */
49148 u8 validNKey; /* True if info.nKey is valid */
49149 u8 eState; /* One of the CURSOR_XXX constants (see below) */
49150 #ifndef SQLITE_OMIT_INCRBLOB
49151 u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
49152 #endif
49153 u8 hints; /* As configured by CursorSetHints() */
49154 i16 iPage; /* Index of current page in apPage */
49155 u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
49156 MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
49160 ** Potential values for BtCursor.eState.
49162 ** CURSOR_INVALID:
49163 ** Cursor does not point to a valid entry. This can happen (for example)
49164 ** because the table is empty or because BtreeCursorFirst() has not been
49165 ** called.
49167 ** CURSOR_VALID:
49168 ** Cursor points to a valid entry. getPayload() etc. may be called.
49170 ** CURSOR_SKIPNEXT:
49171 ** Cursor is valid except that the Cursor.skipNext field is non-zero
49172 ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
49173 ** operation should be a no-op.
49175 ** CURSOR_REQUIRESEEK:
49176 ** The table that this cursor was opened on still exists, but has been
49177 ** modified since the cursor was last used. The cursor position is saved
49178 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
49179 ** this state, restoreCursorPosition() can be called to attempt to
49180 ** seek the cursor to the saved position.
49182 ** CURSOR_FAULT:
49183 ** A unrecoverable error (an I/O error or a malloc failure) has occurred
49184 ** on a different connection that shares the BtShared cache with this
49185 ** cursor. The error has left the cache in an inconsistent state.
49186 ** Do nothing else with this cursor. Any attempt to use the cursor
49187 ** should return the error code stored in BtCursor.skip
49189 #define CURSOR_INVALID 0
49190 #define CURSOR_VALID 1
49191 #define CURSOR_SKIPNEXT 2
49192 #define CURSOR_REQUIRESEEK 3
49193 #define CURSOR_FAULT 4
49196 ** The database page the PENDING_BYTE occupies. This page is never used.
49198 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
49201 ** These macros define the location of the pointer-map entry for a
49202 ** database page. The first argument to each is the number of usable
49203 ** bytes on each page of the database (often 1024). The second is the
49204 ** page number to look up in the pointer map.
49206 ** PTRMAP_PAGENO returns the database page number of the pointer-map
49207 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
49208 ** the offset of the requested map entry.
49210 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
49211 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
49212 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
49213 ** this test.
49215 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
49216 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
49217 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
49220 ** The pointer map is a lookup table that identifies the parent page for
49221 ** each child page in the database file. The parent page is the page that
49222 ** contains a pointer to the child. Every page in the database contains
49223 ** 0 or 1 parent pages. (In this context 'database page' refers
49224 ** to any page that is not part of the pointer map itself.) Each pointer map
49225 ** entry consists of a single byte 'type' and a 4 byte parent page number.
49226 ** The PTRMAP_XXX identifiers below are the valid types.
49228 ** The purpose of the pointer map is to facility moving pages from one
49229 ** position in the file to another as part of autovacuum. When a page
49230 ** is moved, the pointer in its parent must be updated to point to the
49231 ** new location. The pointer map is used to locate the parent page quickly.
49233 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
49234 ** used in this case.
49236 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
49237 ** is not used in this case.
49239 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
49240 ** overflow pages. The page number identifies the page that
49241 ** contains the cell with a pointer to this overflow page.
49243 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
49244 ** overflow pages. The page-number identifies the previous
49245 ** page in the overflow page list.
49247 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
49248 ** identifies the parent page in the btree.
49250 #define PTRMAP_ROOTPAGE 1
49251 #define PTRMAP_FREEPAGE 2
49252 #define PTRMAP_OVERFLOW1 3
49253 #define PTRMAP_OVERFLOW2 4
49254 #define PTRMAP_BTREE 5
49256 /* A bunch of assert() statements to check the transaction state variables
49257 ** of handle p (type Btree*) are internally consistent.
49259 #define btreeIntegrity(p) \
49260 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
49261 assert( p->pBt->inTransaction>=p->inTrans );
49265 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
49266 ** if the database supports auto-vacuum or not. Because it is used
49267 ** within an expression that is an argument to another macro
49268 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
49269 ** So, this macro is defined instead.
49271 #ifndef SQLITE_OMIT_AUTOVACUUM
49272 #define ISAUTOVACUUM (pBt->autoVacuum)
49273 #else
49274 #define ISAUTOVACUUM 0
49275 #endif
49279 ** This structure is passed around through all the sanity checking routines
49280 ** in order to keep track of some global state information.
49282 ** The aRef[] array is allocated so that there is 1 bit for each page in
49283 ** the database. As the integrity-check proceeds, for each page used in
49284 ** the database the corresponding bit is set. This allows integrity-check to
49285 ** detect pages that are used twice and orphaned pages (both of which
49286 ** indicate corruption).
49288 typedef struct IntegrityCk IntegrityCk;
49289 struct IntegrityCk {
49290 BtShared *pBt; /* The tree being checked out */
49291 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
49292 u8 *aPgRef; /* 1 bit per page in the db (see above) */
49293 Pgno nPage; /* Number of pages in the database */
49294 int mxErr; /* Stop accumulating errors when this reaches zero */
49295 int nErr; /* Number of messages written to zErrMsg so far */
49296 int mallocFailed; /* A memory allocation error has occurred */
49297 StrAccum errMsg; /* Accumulate the error message text here */
49301 ** Routines to read or write a two- and four-byte big-endian integer values.
49303 #define get2byte(x) ((x)[0]<<8 | (x)[1])
49304 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
49305 #define get4byte sqlite3Get4byte
49306 #define put4byte sqlite3Put4byte
49308 /************** End of btreeInt.h ********************************************/
49309 /************** Continuing where we left off in btmutex.c ********************/
49310 #ifndef SQLITE_OMIT_SHARED_CACHE
49311 #if SQLITE_THREADSAFE
49314 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
49315 ** set BtShared.db to the database handle associated with p and the
49316 ** p->locked boolean to true.
49318 static void lockBtreeMutex(Btree *p){
49319 assert( p->locked==0 );
49320 assert( sqlite3_mutex_notheld(p->pBt->mutex) );
49321 assert( sqlite3_mutex_held(p->db->mutex) );
49323 sqlite3_mutex_enter(p->pBt->mutex);
49324 p->pBt->db = p->db;
49325 p->locked = 1;
49329 ** Release the BtShared mutex associated with B-Tree handle p and
49330 ** clear the p->locked boolean.
49332 static void unlockBtreeMutex(Btree *p){
49333 BtShared *pBt = p->pBt;
49334 assert( p->locked==1 );
49335 assert( sqlite3_mutex_held(pBt->mutex) );
49336 assert( sqlite3_mutex_held(p->db->mutex) );
49337 assert( p->db==pBt->db );
49339 sqlite3_mutex_leave(pBt->mutex);
49340 p->locked = 0;
49344 ** Enter a mutex on the given BTree object.
49346 ** If the object is not sharable, then no mutex is ever required
49347 ** and this routine is a no-op. The underlying mutex is non-recursive.
49348 ** But we keep a reference count in Btree.wantToLock so the behavior
49349 ** of this interface is recursive.
49351 ** To avoid deadlocks, multiple Btrees are locked in the same order
49352 ** by all database connections. The p->pNext is a list of other
49353 ** Btrees belonging to the same database connection as the p Btree
49354 ** which need to be locked after p. If we cannot get a lock on
49355 ** p, then first unlock all of the others on p->pNext, then wait
49356 ** for the lock to become available on p, then relock all of the
49357 ** subsequent Btrees that desire a lock.
49359 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49360 Btree *pLater;
49362 /* Some basic sanity checking on the Btree. The list of Btrees
49363 ** connected by pNext and pPrev should be in sorted order by
49364 ** Btree.pBt value. All elements of the list should belong to
49365 ** the same connection. Only shared Btrees are on the list. */
49366 assert( p->pNext==0 || p->pNext->pBt>p->pBt );
49367 assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
49368 assert( p->pNext==0 || p->pNext->db==p->db );
49369 assert( p->pPrev==0 || p->pPrev->db==p->db );
49370 assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
49372 /* Check for locking consistency */
49373 assert( !p->locked || p->wantToLock>0 );
49374 assert( p->sharable || p->wantToLock==0 );
49376 /* We should already hold a lock on the database connection */
49377 assert( sqlite3_mutex_held(p->db->mutex) );
49379 /* Unless the database is sharable and unlocked, then BtShared.db
49380 ** should already be set correctly. */
49381 assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
49383 if( !p->sharable ) return;
49384 p->wantToLock++;
49385 if( p->locked ) return;
49387 /* In most cases, we should be able to acquire the lock we
49388 ** want without having to go throught the ascending lock
49389 ** procedure that follows. Just be sure not to block.
49391 if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
49392 p->pBt->db = p->db;
49393 p->locked = 1;
49394 return;
49397 /* To avoid deadlock, first release all locks with a larger
49398 ** BtShared address. Then acquire our lock. Then reacquire
49399 ** the other BtShared locks that we used to hold in ascending
49400 ** order.
49402 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49403 assert( pLater->sharable );
49404 assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
49405 assert( !pLater->locked || pLater->wantToLock>0 );
49406 if( pLater->locked ){
49407 unlockBtreeMutex(pLater);
49410 lockBtreeMutex(p);
49411 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49412 if( pLater->wantToLock ){
49413 lockBtreeMutex(pLater);
49419 ** Exit the recursive mutex on a Btree.
49421 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
49422 if( p->sharable ){
49423 assert( p->wantToLock>0 );
49424 p->wantToLock--;
49425 if( p->wantToLock==0 ){
49426 unlockBtreeMutex(p);
49431 #ifndef NDEBUG
49433 ** Return true if the BtShared mutex is held on the btree, or if the
49434 ** B-Tree is not marked as sharable.
49436 ** This routine is used only from within assert() statements.
49438 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
49439 assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
49440 assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
49441 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
49442 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
49444 return (p->sharable==0 || p->locked);
49446 #endif
49449 #ifndef SQLITE_OMIT_INCRBLOB
49451 ** Enter and leave a mutex on a Btree given a cursor owned by that
49452 ** Btree. These entry points are used by incremental I/O and can be
49453 ** omitted if that module is not used.
49455 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
49456 sqlite3BtreeEnter(pCur->pBtree);
49458 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
49459 sqlite3BtreeLeave(pCur->pBtree);
49461 #endif /* SQLITE_OMIT_INCRBLOB */
49465 ** Enter the mutex on every Btree associated with a database
49466 ** connection. This is needed (for example) prior to parsing
49467 ** a statement since we will be comparing table and column names
49468 ** against all schemas and we do not want those schemas being
49469 ** reset out from under us.
49471 ** There is a corresponding leave-all procedures.
49473 ** Enter the mutexes in accending order by BtShared pointer address
49474 ** to avoid the possibility of deadlock when two threads with
49475 ** two or more btrees in common both try to lock all their btrees
49476 ** at the same instant.
49478 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49479 int i;
49480 Btree *p;
49481 assert( sqlite3_mutex_held(db->mutex) );
49482 for(i=0; i<db->nDb; i++){
49483 p = db->aDb[i].pBt;
49484 if( p ) sqlite3BtreeEnter(p);
49487 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
49488 int i;
49489 Btree *p;
49490 assert( sqlite3_mutex_held(db->mutex) );
49491 for(i=0; i<db->nDb; i++){
49492 p = db->aDb[i].pBt;
49493 if( p ) sqlite3BtreeLeave(p);
49498 ** Return true if a particular Btree requires a lock. Return FALSE if
49499 ** no lock is ever required since it is not sharable.
49501 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
49502 return p->sharable;
49505 #ifndef NDEBUG
49507 ** Return true if the current thread holds the database connection
49508 ** mutex and all required BtShared mutexes.
49510 ** This routine is used inside assert() statements only.
49512 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
49513 int i;
49514 if( !sqlite3_mutex_held(db->mutex) ){
49515 return 0;
49517 for(i=0; i<db->nDb; i++){
49518 Btree *p;
49519 p = db->aDb[i].pBt;
49520 if( p && p->sharable &&
49521 (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
49522 return 0;
49525 return 1;
49527 #endif /* NDEBUG */
49529 #ifndef NDEBUG
49531 ** Return true if the correct mutexes are held for accessing the
49532 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
49533 ** access are:
49535 ** (1) The mutex on db
49536 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
49538 ** If pSchema is not NULL, then iDb is computed from pSchema and
49539 ** db using sqlite3SchemaToIndex().
49541 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
49542 Btree *p;
49543 assert( db!=0 );
49544 if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
49545 assert( iDb>=0 && iDb<db->nDb );
49546 if( !sqlite3_mutex_held(db->mutex) ) return 0;
49547 if( iDb==1 ) return 1;
49548 p = db->aDb[iDb].pBt;
49549 assert( p!=0 );
49550 return p->sharable==0 || p->locked==1;
49552 #endif /* NDEBUG */
49554 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
49556 ** The following are special cases for mutex enter routines for use
49557 ** in single threaded applications that use shared cache. Except for
49558 ** these two routines, all mutex operations are no-ops in that case and
49559 ** are null #defines in btree.h.
49561 ** If shared cache is disabled, then all btree mutex routines, including
49562 ** the ones below, are no-ops and are null #defines in btree.h.
49565 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49566 p->pBt->db = p->db;
49568 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49569 int i;
49570 for(i=0; i<db->nDb; i++){
49571 Btree *p = db->aDb[i].pBt;
49572 if( p ){
49573 p->pBt->db = p->db;
49577 #endif /* if SQLITE_THREADSAFE */
49578 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
49580 /************** End of btmutex.c *********************************************/
49581 /************** Begin file btree.c *******************************************/
49583 ** 2004 April 6
49585 ** The author disclaims copyright to this source code. In place of
49586 ** a legal notice, here is a blessing:
49588 ** May you do good and not evil.
49589 ** May you find forgiveness for yourself and forgive others.
49590 ** May you share freely, never taking more than you give.
49592 *************************************************************************
49593 ** This file implements a external (disk-based) database using BTrees.
49594 ** See the header comment on "btreeInt.h" for additional information.
49595 ** Including a description of file format and an overview of operation.
49599 ** The header string that appears at the beginning of every
49600 ** SQLite database.
49602 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
49605 ** Set this global variable to 1 to enable tracing using the TRACE
49606 ** macro.
49608 #if 0
49609 int sqlite3BtreeTrace=1; /* True to enable tracing */
49610 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
49611 #else
49612 # define TRACE(X)
49613 #endif
49616 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
49617 ** But if the value is zero, make it 65536.
49619 ** This routine is used to extract the "offset to cell content area" value
49620 ** from the header of a btree page. If the page size is 65536 and the page
49621 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
49622 ** This routine makes the necessary adjustment to 65536.
49624 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
49627 ** Values passed as the 5th argument to allocateBtreePage()
49629 #define BTALLOC_ANY 0 /* Allocate any page */
49630 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
49631 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
49634 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
49635 ** defined, or 0 if it is. For example:
49637 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
49639 #ifndef SQLITE_OMIT_AUTOVACUUM
49640 #define IfNotOmitAV(expr) (expr)
49641 #else
49642 #define IfNotOmitAV(expr) 0
49643 #endif
49645 #ifndef SQLITE_OMIT_SHARED_CACHE
49647 ** A list of BtShared objects that are eligible for participation
49648 ** in shared cache. This variable has file scope during normal builds,
49649 ** but the test harness needs to access it so we make it global for
49650 ** test builds.
49652 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
49654 #ifdef SQLITE_TEST
49655 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
49656 #else
49657 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
49658 #endif
49659 #endif /* SQLITE_OMIT_SHARED_CACHE */
49661 #ifndef SQLITE_OMIT_SHARED_CACHE
49663 ** Enable or disable the shared pager and schema features.
49665 ** This routine has no effect on existing database connections.
49666 ** The shared cache setting effects only future calls to
49667 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
49669 SQLITE_API int sqlite3_enable_shared_cache(int enable){
49670 sqlite3GlobalConfig.sharedCacheEnabled = enable;
49671 return SQLITE_OK;
49673 #endif
49677 #ifdef SQLITE_OMIT_SHARED_CACHE
49679 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
49680 ** and clearAllSharedCacheTableLocks()
49681 ** manipulate entries in the BtShared.pLock linked list used to store
49682 ** shared-cache table level locks. If the library is compiled with the
49683 ** shared-cache feature disabled, then there is only ever one user
49684 ** of each BtShared structure and so this locking is not necessary.
49685 ** So define the lock related functions as no-ops.
49687 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
49688 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
49689 #define clearAllSharedCacheTableLocks(a)
49690 #define downgradeAllSharedCacheTableLocks(a)
49691 #define hasSharedCacheTableLock(a,b,c,d) 1
49692 #define hasReadConflicts(a, b) 0
49693 #endif
49695 #ifndef SQLITE_OMIT_SHARED_CACHE
49697 #ifdef SQLITE_DEBUG
49699 **** This function is only used as part of an assert() statement. ***
49701 ** Check to see if pBtree holds the required locks to read or write to the
49702 ** table with root page iRoot. Return 1 if it does and 0 if not.
49704 ** For example, when writing to a table with root-page iRoot via
49705 ** Btree connection pBtree:
49707 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
49709 ** When writing to an index that resides in a sharable database, the
49710 ** caller should have first obtained a lock specifying the root page of
49711 ** the corresponding table. This makes things a bit more complicated,
49712 ** as this module treats each table as a separate structure. To determine
49713 ** the table corresponding to the index being written, this
49714 ** function has to search through the database schema.
49716 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
49717 ** hold a write-lock on the schema table (root page 1). This is also
49718 ** acceptable.
49720 static int hasSharedCacheTableLock(
49721 Btree *pBtree, /* Handle that must hold lock */
49722 Pgno iRoot, /* Root page of b-tree */
49723 int isIndex, /* True if iRoot is the root of an index b-tree */
49724 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
49726 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
49727 Pgno iTab = 0;
49728 BtLock *pLock;
49730 /* If this database is not shareable, or if the client is reading
49731 ** and has the read-uncommitted flag set, then no lock is required.
49732 ** Return true immediately.
49734 if( (pBtree->sharable==0)
49735 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
49737 return 1;
49740 /* If the client is reading or writing an index and the schema is
49741 ** not loaded, then it is too difficult to actually check to see if
49742 ** the correct locks are held. So do not bother - just return true.
49743 ** This case does not come up very often anyhow.
49745 if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
49746 return 1;
49749 /* Figure out the root-page that the lock should be held on. For table
49750 ** b-trees, this is just the root page of the b-tree being read or
49751 ** written. For index b-trees, it is the root page of the associated
49752 ** table. */
49753 if( isIndex ){
49754 HashElem *p;
49755 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
49756 Index *pIdx = (Index *)sqliteHashData(p);
49757 if( pIdx->tnum==(int)iRoot ){
49758 iTab = pIdx->pTable->tnum;
49761 }else{
49762 iTab = iRoot;
49765 /* Search for the required lock. Either a write-lock on root-page iTab, a
49766 ** write-lock on the schema table, or (if the client is reading) a
49767 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
49768 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
49769 if( pLock->pBtree==pBtree
49770 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
49771 && pLock->eLock>=eLockType
49773 return 1;
49777 /* Failed to find the required lock. */
49778 return 0;
49780 #endif /* SQLITE_DEBUG */
49782 #ifdef SQLITE_DEBUG
49784 **** This function may be used as part of assert() statements only. ****
49786 ** Return true if it would be illegal for pBtree to write into the
49787 ** table or index rooted at iRoot because other shared connections are
49788 ** simultaneously reading that same table or index.
49790 ** It is illegal for pBtree to write if some other Btree object that
49791 ** shares the same BtShared object is currently reading or writing
49792 ** the iRoot table. Except, if the other Btree object has the
49793 ** read-uncommitted flag set, then it is OK for the other object to
49794 ** have a read cursor.
49796 ** For example, before writing to any part of the table or index
49797 ** rooted at page iRoot, one should call:
49799 ** assert( !hasReadConflicts(pBtree, iRoot) );
49801 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
49802 BtCursor *p;
49803 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
49804 if( p->pgnoRoot==iRoot
49805 && p->pBtree!=pBtree
49806 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
49808 return 1;
49811 return 0;
49813 #endif /* #ifdef SQLITE_DEBUG */
49816 ** Query to see if Btree handle p may obtain a lock of type eLock
49817 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
49818 ** SQLITE_OK if the lock may be obtained (by calling
49819 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
49821 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
49822 BtShared *pBt = p->pBt;
49823 BtLock *pIter;
49825 assert( sqlite3BtreeHoldsMutex(p) );
49826 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49827 assert( p->db!=0 );
49828 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
49830 /* If requesting a write-lock, then the Btree must have an open write
49831 ** transaction on this file. And, obviously, for this to be so there
49832 ** must be an open write transaction on the file itself.
49834 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
49835 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
49837 /* This routine is a no-op if the shared-cache is not enabled */
49838 if( !p->sharable ){
49839 return SQLITE_OK;
49842 /* If some other connection is holding an exclusive lock, the
49843 ** requested lock may not be obtained.
49845 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
49846 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
49847 return SQLITE_LOCKED_SHAREDCACHE;
49850 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49851 /* The condition (pIter->eLock!=eLock) in the following if(...)
49852 ** statement is a simplification of:
49854 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
49856 ** since we know that if eLock==WRITE_LOCK, then no other connection
49857 ** may hold a WRITE_LOCK on any table in this file (since there can
49858 ** only be a single writer).
49860 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
49861 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
49862 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
49863 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
49864 if( eLock==WRITE_LOCK ){
49865 assert( p==pBt->pWriter );
49866 pBt->btsFlags |= BTS_PENDING;
49868 return SQLITE_LOCKED_SHAREDCACHE;
49871 return SQLITE_OK;
49873 #endif /* !SQLITE_OMIT_SHARED_CACHE */
49875 #ifndef SQLITE_OMIT_SHARED_CACHE
49877 ** Add a lock on the table with root-page iTable to the shared-btree used
49878 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
49879 ** WRITE_LOCK.
49881 ** This function assumes the following:
49883 ** (a) The specified Btree object p is connected to a sharable
49884 ** database (one with the BtShared.sharable flag set), and
49886 ** (b) No other Btree objects hold a lock that conflicts
49887 ** with the requested lock (i.e. querySharedCacheTableLock() has
49888 ** already been called and returned SQLITE_OK).
49890 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
49891 ** is returned if a malloc attempt fails.
49893 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
49894 BtShared *pBt = p->pBt;
49895 BtLock *pLock = 0;
49896 BtLock *pIter;
49898 assert( sqlite3BtreeHoldsMutex(p) );
49899 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49900 assert( p->db!=0 );
49902 /* A connection with the read-uncommitted flag set will never try to
49903 ** obtain a read-lock using this function. The only read-lock obtained
49904 ** by a connection in read-uncommitted mode is on the sqlite_master
49905 ** table, and that lock is obtained in BtreeBeginTrans(). */
49906 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
49908 /* This function should only be called on a sharable b-tree after it
49909 ** has been determined that no other b-tree holds a conflicting lock. */
49910 assert( p->sharable );
49911 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
49913 /* First search the list for an existing lock on this table. */
49914 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49915 if( pIter->iTable==iTable && pIter->pBtree==p ){
49916 pLock = pIter;
49917 break;
49921 /* If the above search did not find a BtLock struct associating Btree p
49922 ** with table iTable, allocate one and link it into the list.
49924 if( !pLock ){
49925 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
49926 if( !pLock ){
49927 return SQLITE_NOMEM;
49929 pLock->iTable = iTable;
49930 pLock->pBtree = p;
49931 pLock->pNext = pBt->pLock;
49932 pBt->pLock = pLock;
49935 /* Set the BtLock.eLock variable to the maximum of the current lock
49936 ** and the requested lock. This means if a write-lock was already held
49937 ** and a read-lock requested, we don't incorrectly downgrade the lock.
49939 assert( WRITE_LOCK>READ_LOCK );
49940 if( eLock>pLock->eLock ){
49941 pLock->eLock = eLock;
49944 return SQLITE_OK;
49946 #endif /* !SQLITE_OMIT_SHARED_CACHE */
49948 #ifndef SQLITE_OMIT_SHARED_CACHE
49950 ** Release all the table locks (locks obtained via calls to
49951 ** the setSharedCacheTableLock() procedure) held by Btree object p.
49953 ** This function assumes that Btree p has an open read or write
49954 ** transaction. If it does not, then the BTS_PENDING flag
49955 ** may be incorrectly cleared.
49957 static void clearAllSharedCacheTableLocks(Btree *p){
49958 BtShared *pBt = p->pBt;
49959 BtLock **ppIter = &pBt->pLock;
49961 assert( sqlite3BtreeHoldsMutex(p) );
49962 assert( p->sharable || 0==*ppIter );
49963 assert( p->inTrans>0 );
49965 while( *ppIter ){
49966 BtLock *pLock = *ppIter;
49967 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
49968 assert( pLock->pBtree->inTrans>=pLock->eLock );
49969 if( pLock->pBtree==p ){
49970 *ppIter = pLock->pNext;
49971 assert( pLock->iTable!=1 || pLock==&p->lock );
49972 if( pLock->iTable!=1 ){
49973 sqlite3_free(pLock);
49975 }else{
49976 ppIter = &pLock->pNext;
49980 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
49981 if( pBt->pWriter==p ){
49982 pBt->pWriter = 0;
49983 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
49984 }else if( pBt->nTransaction==2 ){
49985 /* This function is called when Btree p is concluding its
49986 ** transaction. If there currently exists a writer, and p is not
49987 ** that writer, then the number of locks held by connections other
49988 ** than the writer must be about to drop to zero. In this case
49989 ** set the BTS_PENDING flag to 0.
49991 ** If there is not currently a writer, then BTS_PENDING must
49992 ** be zero already. So this next line is harmless in that case.
49994 pBt->btsFlags &= ~BTS_PENDING;
49999 ** This function changes all write-locks held by Btree p into read-locks.
50001 static void downgradeAllSharedCacheTableLocks(Btree *p){
50002 BtShared *pBt = p->pBt;
50003 if( pBt->pWriter==p ){
50004 BtLock *pLock;
50005 pBt->pWriter = 0;
50006 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
50007 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
50008 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
50009 pLock->eLock = READ_LOCK;
50014 #endif /* SQLITE_OMIT_SHARED_CACHE */
50016 static void releasePage(MemPage *pPage); /* Forward reference */
50019 ***** This routine is used inside of assert() only ****
50021 ** Verify that the cursor holds the mutex on its BtShared
50023 #ifdef SQLITE_DEBUG
50024 static int cursorHoldsMutex(BtCursor *p){
50025 return sqlite3_mutex_held(p->pBt->mutex);
50027 #endif
50030 #ifndef SQLITE_OMIT_INCRBLOB
50032 ** Invalidate the overflow page-list cache for cursor pCur, if any.
50034 static void invalidateOverflowCache(BtCursor *pCur){
50035 assert( cursorHoldsMutex(pCur) );
50036 sqlite3_free(pCur->aOverflow);
50037 pCur->aOverflow = 0;
50041 ** Invalidate the overflow page-list cache for all cursors opened
50042 ** on the shared btree structure pBt.
50044 static void invalidateAllOverflowCache(BtShared *pBt){
50045 BtCursor *p;
50046 assert( sqlite3_mutex_held(pBt->mutex) );
50047 for(p=pBt->pCursor; p; p=p->pNext){
50048 invalidateOverflowCache(p);
50053 ** This function is called before modifying the contents of a table
50054 ** to invalidate any incrblob cursors that are open on the
50055 ** row or one of the rows being modified.
50057 ** If argument isClearTable is true, then the entire contents of the
50058 ** table is about to be deleted. In this case invalidate all incrblob
50059 ** cursors open on any row within the table with root-page pgnoRoot.
50061 ** Otherwise, if argument isClearTable is false, then the row with
50062 ** rowid iRow is being replaced or deleted. In this case invalidate
50063 ** only those incrblob cursors open on that specific row.
50065 static void invalidateIncrblobCursors(
50066 Btree *pBtree, /* The database file to check */
50067 i64 iRow, /* The rowid that might be changing */
50068 int isClearTable /* True if all rows are being deleted */
50070 BtCursor *p;
50071 BtShared *pBt = pBtree->pBt;
50072 assert( sqlite3BtreeHoldsMutex(pBtree) );
50073 for(p=pBt->pCursor; p; p=p->pNext){
50074 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
50075 p->eState = CURSOR_INVALID;
50080 #else
50081 /* Stub functions when INCRBLOB is omitted */
50082 #define invalidateOverflowCache(x)
50083 #define invalidateAllOverflowCache(x)
50084 #define invalidateIncrblobCursors(x,y,z)
50085 #endif /* SQLITE_OMIT_INCRBLOB */
50088 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
50089 ** when a page that previously contained data becomes a free-list leaf
50090 ** page.
50092 ** The BtShared.pHasContent bitvec exists to work around an obscure
50093 ** bug caused by the interaction of two useful IO optimizations surrounding
50094 ** free-list leaf pages:
50096 ** 1) When all data is deleted from a page and the page becomes
50097 ** a free-list leaf page, the page is not written to the database
50098 ** (as free-list leaf pages contain no meaningful data). Sometimes
50099 ** such a page is not even journalled (as it will not be modified,
50100 ** why bother journalling it?).
50102 ** 2) When a free-list leaf page is reused, its content is not read
50103 ** from the database or written to the journal file (why should it
50104 ** be, if it is not at all meaningful?).
50106 ** By themselves, these optimizations work fine and provide a handy
50107 ** performance boost to bulk delete or insert operations. However, if
50108 ** a page is moved to the free-list and then reused within the same
50109 ** transaction, a problem comes up. If the page is not journalled when
50110 ** it is moved to the free-list and it is also not journalled when it
50111 ** is extracted from the free-list and reused, then the original data
50112 ** may be lost. In the event of a rollback, it may not be possible
50113 ** to restore the database to its original configuration.
50115 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
50116 ** moved to become a free-list leaf page, the corresponding bit is
50117 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
50118 ** optimization 2 above is omitted if the corresponding bit is already
50119 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
50120 ** at the end of every transaction.
50122 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
50123 int rc = SQLITE_OK;
50124 if( !pBt->pHasContent ){
50125 assert( pgno<=pBt->nPage );
50126 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
50127 if( !pBt->pHasContent ){
50128 rc = SQLITE_NOMEM;
50131 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
50132 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
50134 return rc;
50138 ** Query the BtShared.pHasContent vector.
50140 ** This function is called when a free-list leaf page is removed from the
50141 ** free-list for reuse. It returns false if it is safe to retrieve the
50142 ** page from the pager layer with the 'no-content' flag set. True otherwise.
50144 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
50145 Bitvec *p = pBt->pHasContent;
50146 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
50150 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
50151 ** invoked at the conclusion of each write-transaction.
50153 static void btreeClearHasContent(BtShared *pBt){
50154 sqlite3BitvecDestroy(pBt->pHasContent);
50155 pBt->pHasContent = 0;
50159 ** Release all of the apPage[] pages for a cursor.
50161 static void btreeReleaseAllCursorPages(BtCursor *pCur){
50162 int i;
50163 for(i=0; i<=pCur->iPage; i++){
50164 releasePage(pCur->apPage[i]);
50165 pCur->apPage[i] = 0;
50167 pCur->iPage = -1;
50172 ** Save the current cursor position in the variables BtCursor.nKey
50173 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
50175 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
50176 ** prior to calling this routine.
50178 static int saveCursorPosition(BtCursor *pCur){
50179 int rc;
50181 assert( CURSOR_VALID==pCur->eState );
50182 assert( 0==pCur->pKey );
50183 assert( cursorHoldsMutex(pCur) );
50185 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
50186 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
50188 /* If this is an intKey table, then the above call to BtreeKeySize()
50189 ** stores the integer key in pCur->nKey. In this case this value is
50190 ** all that is required. Otherwise, if pCur is not open on an intKey
50191 ** table, then malloc space for and store the pCur->nKey bytes of key
50192 ** data.
50194 if( 0==pCur->apPage[0]->intKey ){
50195 void *pKey = sqlite3Malloc( (int)pCur->nKey );
50196 if( pKey ){
50197 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
50198 if( rc==SQLITE_OK ){
50199 pCur->pKey = pKey;
50200 }else{
50201 sqlite3_free(pKey);
50203 }else{
50204 rc = SQLITE_NOMEM;
50207 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
50209 if( rc==SQLITE_OK ){
50210 btreeReleaseAllCursorPages(pCur);
50211 pCur->eState = CURSOR_REQUIRESEEK;
50214 invalidateOverflowCache(pCur);
50215 return rc;
50219 ** Save the positions of all cursors (except pExcept) that are open on
50220 ** the table with root-page iRoot. Usually, this is called just before cursor
50221 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
50223 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
50224 BtCursor *p;
50225 assert( sqlite3_mutex_held(pBt->mutex) );
50226 assert( pExcept==0 || pExcept->pBt==pBt );
50227 for(p=pBt->pCursor; p; p=p->pNext){
50228 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
50229 if( p->eState==CURSOR_VALID ){
50230 int rc = saveCursorPosition(p);
50231 if( SQLITE_OK!=rc ){
50232 return rc;
50234 }else{
50235 testcase( p->iPage>0 );
50236 btreeReleaseAllCursorPages(p);
50240 return SQLITE_OK;
50244 ** Clear the current cursor position.
50246 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
50247 assert( cursorHoldsMutex(pCur) );
50248 sqlite3_free(pCur->pKey);
50249 pCur->pKey = 0;
50250 pCur->eState = CURSOR_INVALID;
50254 ** In this version of BtreeMoveto, pKey is a packed index record
50255 ** such as is generated by the OP_MakeRecord opcode. Unpack the
50256 ** record and then call BtreeMovetoUnpacked() to do the work.
50258 static int btreeMoveto(
50259 BtCursor *pCur, /* Cursor open on the btree to be searched */
50260 const void *pKey, /* Packed key if the btree is an index */
50261 i64 nKey, /* Integer key for tables. Size of pKey for indices */
50262 int bias, /* Bias search to the high end */
50263 int *pRes /* Write search results here */
50265 int rc; /* Status code */
50266 UnpackedRecord *pIdxKey; /* Unpacked index key */
50267 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
50268 char *pFree = 0;
50270 if( pKey ){
50271 assert( nKey==(i64)(int)nKey );
50272 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
50273 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
50275 if( pIdxKey==0 ) return SQLITE_NOMEM;
50276 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
50277 }else{
50278 pIdxKey = 0;
50280 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
50281 if( pFree ){
50282 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
50284 return rc;
50288 ** Restore the cursor to the position it was in (or as close to as possible)
50289 ** when saveCursorPosition() was called. Note that this call deletes the
50290 ** saved position info stored by saveCursorPosition(), so there can be
50291 ** at most one effective restoreCursorPosition() call after each
50292 ** saveCursorPosition().
50294 static int btreeRestoreCursorPosition(BtCursor *pCur){
50295 int rc;
50296 assert( cursorHoldsMutex(pCur) );
50297 assert( pCur->eState>=CURSOR_REQUIRESEEK );
50298 if( pCur->eState==CURSOR_FAULT ){
50299 return pCur->skipNext;
50301 pCur->eState = CURSOR_INVALID;
50302 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
50303 if( rc==SQLITE_OK ){
50304 sqlite3_free(pCur->pKey);
50305 pCur->pKey = 0;
50306 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
50307 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
50308 pCur->eState = CURSOR_SKIPNEXT;
50311 return rc;
50314 #define restoreCursorPosition(p) \
50315 (p->eState>=CURSOR_REQUIRESEEK ? \
50316 btreeRestoreCursorPosition(p) : \
50317 SQLITE_OK)
50320 ** Determine whether or not a cursor has moved from the position it
50321 ** was last placed at. Cursors can move when the row they are pointing
50322 ** at is deleted out from under them.
50324 ** This routine returns an error code if something goes wrong. The
50325 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
50327 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
50328 int rc;
50330 rc = restoreCursorPosition(pCur);
50331 if( rc ){
50332 *pHasMoved = 1;
50333 return rc;
50335 if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
50336 *pHasMoved = 1;
50337 }else{
50338 *pHasMoved = 0;
50340 return SQLITE_OK;
50343 #ifndef SQLITE_OMIT_AUTOVACUUM
50345 ** Given a page number of a regular database page, return the page
50346 ** number for the pointer-map page that contains the entry for the
50347 ** input page number.
50349 ** Return 0 (not a valid page) for pgno==1 since there is
50350 ** no pointer map associated with page 1. The integrity_check logic
50351 ** requires that ptrmapPageno(*,1)!=1.
50353 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
50354 int nPagesPerMapPage;
50355 Pgno iPtrMap, ret;
50356 assert( sqlite3_mutex_held(pBt->mutex) );
50357 if( pgno<2 ) return 0;
50358 nPagesPerMapPage = (pBt->usableSize/5)+1;
50359 iPtrMap = (pgno-2)/nPagesPerMapPage;
50360 ret = (iPtrMap*nPagesPerMapPage) + 2;
50361 if( ret==PENDING_BYTE_PAGE(pBt) ){
50362 ret++;
50364 return ret;
50368 ** Write an entry into the pointer map.
50370 ** This routine updates the pointer map entry for page number 'key'
50371 ** so that it maps to type 'eType' and parent page number 'pgno'.
50373 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
50374 ** a no-op. If an error occurs, the appropriate error code is written
50375 ** into *pRC.
50377 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
50378 DbPage *pDbPage; /* The pointer map page */
50379 u8 *pPtrmap; /* The pointer map data */
50380 Pgno iPtrmap; /* The pointer map page number */
50381 int offset; /* Offset in pointer map page */
50382 int rc; /* Return code from subfunctions */
50384 if( *pRC ) return;
50386 assert( sqlite3_mutex_held(pBt->mutex) );
50387 /* The master-journal page number must never be used as a pointer map page */
50388 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
50390 assert( pBt->autoVacuum );
50391 if( key==0 ){
50392 *pRC = SQLITE_CORRUPT_BKPT;
50393 return;
50395 iPtrmap = PTRMAP_PAGENO(pBt, key);
50396 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50397 if( rc!=SQLITE_OK ){
50398 *pRC = rc;
50399 return;
50401 offset = PTRMAP_PTROFFSET(iPtrmap, key);
50402 if( offset<0 ){
50403 *pRC = SQLITE_CORRUPT_BKPT;
50404 goto ptrmap_exit;
50406 assert( offset <= (int)pBt->usableSize-5 );
50407 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50409 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
50410 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
50411 *pRC= rc = sqlite3PagerWrite(pDbPage);
50412 if( rc==SQLITE_OK ){
50413 pPtrmap[offset] = eType;
50414 put4byte(&pPtrmap[offset+1], parent);
50418 ptrmap_exit:
50419 sqlite3PagerUnref(pDbPage);
50423 ** Read an entry from the pointer map.
50425 ** This routine retrieves the pointer map entry for page 'key', writing
50426 ** the type and parent page number to *pEType and *pPgno respectively.
50427 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
50429 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
50430 DbPage *pDbPage; /* The pointer map page */
50431 int iPtrmap; /* Pointer map page index */
50432 u8 *pPtrmap; /* Pointer map page data */
50433 int offset; /* Offset of entry in pointer map */
50434 int rc;
50436 assert( sqlite3_mutex_held(pBt->mutex) );
50438 iPtrmap = PTRMAP_PAGENO(pBt, key);
50439 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50440 if( rc!=0 ){
50441 return rc;
50443 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50445 offset = PTRMAP_PTROFFSET(iPtrmap, key);
50446 if( offset<0 ){
50447 sqlite3PagerUnref(pDbPage);
50448 return SQLITE_CORRUPT_BKPT;
50450 assert( offset <= (int)pBt->usableSize-5 );
50451 assert( pEType!=0 );
50452 *pEType = pPtrmap[offset];
50453 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
50455 sqlite3PagerUnref(pDbPage);
50456 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
50457 return SQLITE_OK;
50460 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
50461 #define ptrmapPut(w,x,y,z,rc)
50462 #define ptrmapGet(w,x,y,z) SQLITE_OK
50463 #define ptrmapPutOvflPtr(x, y, rc)
50464 #endif
50467 ** Given a btree page and a cell index (0 means the first cell on
50468 ** the page, 1 means the second cell, and so forth) return a pointer
50469 ** to the cell content.
50471 ** This routine works only for pages that do not contain overflow cells.
50473 #define findCell(P,I) \
50474 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
50475 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
50479 ** This a more complex version of findCell() that works for
50480 ** pages that do contain overflow cells.
50482 static u8 *findOverflowCell(MemPage *pPage, int iCell){
50483 int i;
50484 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50485 for(i=pPage->nOverflow-1; i>=0; i--){
50486 int k;
50487 k = pPage->aiOvfl[i];
50488 if( k<=iCell ){
50489 if( k==iCell ){
50490 return pPage->apOvfl[i];
50492 iCell--;
50495 return findCell(pPage, iCell);
50499 ** Parse a cell content block and fill in the CellInfo structure. There
50500 ** are two versions of this function. btreeParseCell() takes a
50501 ** cell index as the second argument and btreeParseCellPtr()
50502 ** takes a pointer to the body of the cell as its second argument.
50504 ** Within this file, the parseCell() macro can be called instead of
50505 ** btreeParseCellPtr(). Using some compilers, this will be faster.
50507 static void btreeParseCellPtr(
50508 MemPage *pPage, /* Page containing the cell */
50509 u8 *pCell, /* Pointer to the cell text. */
50510 CellInfo *pInfo /* Fill in this structure */
50512 u16 n; /* Number bytes in cell content header */
50513 u32 nPayload; /* Number of bytes of cell payload */
50515 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50517 pInfo->pCell = pCell;
50518 assert( pPage->leaf==0 || pPage->leaf==1 );
50519 n = pPage->childPtrSize;
50520 assert( n==4-4*pPage->leaf );
50521 if( pPage->intKey ){
50522 if( pPage->hasData ){
50523 assert( n==0 );
50524 n = getVarint32(pCell, nPayload);
50525 }else{
50526 nPayload = 0;
50528 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
50529 pInfo->nData = nPayload;
50530 }else{
50531 pInfo->nData = 0;
50532 n += getVarint32(&pCell[n], nPayload);
50533 pInfo->nKey = nPayload;
50535 pInfo->nPayload = nPayload;
50536 pInfo->nHeader = n;
50537 testcase( nPayload==pPage->maxLocal );
50538 testcase( nPayload==pPage->maxLocal+1 );
50539 if( likely(nPayload<=pPage->maxLocal) ){
50540 /* This is the (easy) common case where the entire payload fits
50541 ** on the local page. No overflow is required.
50543 if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
50544 pInfo->nLocal = (u16)nPayload;
50545 pInfo->iOverflow = 0;
50546 }else{
50547 /* If the payload will not fit completely on the local page, we have
50548 ** to decide how much to store locally and how much to spill onto
50549 ** overflow pages. The strategy is to minimize the amount of unused
50550 ** space on overflow pages while keeping the amount of local storage
50551 ** in between minLocal and maxLocal.
50553 ** Warning: changing the way overflow payload is distributed in any
50554 ** way will result in an incompatible file format.
50556 int minLocal; /* Minimum amount of payload held locally */
50557 int maxLocal; /* Maximum amount of payload held locally */
50558 int surplus; /* Overflow payload available for local storage */
50560 minLocal = pPage->minLocal;
50561 maxLocal = pPage->maxLocal;
50562 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
50563 testcase( surplus==maxLocal );
50564 testcase( surplus==maxLocal+1 );
50565 if( surplus <= maxLocal ){
50566 pInfo->nLocal = (u16)surplus;
50567 }else{
50568 pInfo->nLocal = (u16)minLocal;
50570 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
50571 pInfo->nSize = pInfo->iOverflow + 4;
50574 #define parseCell(pPage, iCell, pInfo) \
50575 btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
50576 static void btreeParseCell(
50577 MemPage *pPage, /* Page containing the cell */
50578 int iCell, /* The cell index. First cell is 0 */
50579 CellInfo *pInfo /* Fill in this structure */
50581 parseCell(pPage, iCell, pInfo);
50585 ** Compute the total number of bytes that a Cell needs in the cell
50586 ** data area of the btree-page. The return number includes the cell
50587 ** data header and the local payload, but not any overflow page or
50588 ** the space used by the cell pointer.
50590 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
50591 u8 *pIter = &pCell[pPage->childPtrSize];
50592 u32 nSize;
50594 #ifdef SQLITE_DEBUG
50595 /* The value returned by this function should always be the same as
50596 ** the (CellInfo.nSize) value found by doing a full parse of the
50597 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
50598 ** this function verifies that this invariant is not violated. */
50599 CellInfo debuginfo;
50600 btreeParseCellPtr(pPage, pCell, &debuginfo);
50601 #endif
50603 if( pPage->intKey ){
50604 u8 *pEnd;
50605 if( pPage->hasData ){
50606 pIter += getVarint32(pIter, nSize);
50607 }else{
50608 nSize = 0;
50611 /* pIter now points at the 64-bit integer key value, a variable length
50612 ** integer. The following block moves pIter to point at the first byte
50613 ** past the end of the key value. */
50614 pEnd = &pIter[9];
50615 while( (*pIter++)&0x80 && pIter<pEnd );
50616 }else{
50617 pIter += getVarint32(pIter, nSize);
50620 testcase( nSize==pPage->maxLocal );
50621 testcase( nSize==pPage->maxLocal+1 );
50622 if( nSize>pPage->maxLocal ){
50623 int minLocal = pPage->minLocal;
50624 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
50625 testcase( nSize==pPage->maxLocal );
50626 testcase( nSize==pPage->maxLocal+1 );
50627 if( nSize>pPage->maxLocal ){
50628 nSize = minLocal;
50630 nSize += 4;
50632 nSize += (u32)(pIter - pCell);
50634 /* The minimum size of any cell is 4 bytes. */
50635 if( nSize<4 ){
50636 nSize = 4;
50639 assert( nSize==debuginfo.nSize );
50640 return (u16)nSize;
50643 #ifdef SQLITE_DEBUG
50644 /* This variation on cellSizePtr() is used inside of assert() statements
50645 ** only. */
50646 static u16 cellSize(MemPage *pPage, int iCell){
50647 return cellSizePtr(pPage, findCell(pPage, iCell));
50649 #endif
50651 #ifndef SQLITE_OMIT_AUTOVACUUM
50653 ** If the cell pCell, part of page pPage contains a pointer
50654 ** to an overflow page, insert an entry into the pointer-map
50655 ** for the overflow page.
50657 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
50658 CellInfo info;
50659 if( *pRC ) return;
50660 assert( pCell!=0 );
50661 btreeParseCellPtr(pPage, pCell, &info);
50662 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
50663 if( info.iOverflow ){
50664 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
50665 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
50668 #endif
50672 ** Defragment the page given. All Cells are moved to the
50673 ** end of the page and all free space is collected into one
50674 ** big FreeBlk that occurs in between the header and cell
50675 ** pointer array and the cell content area.
50677 static int defragmentPage(MemPage *pPage){
50678 int i; /* Loop counter */
50679 int pc; /* Address of a i-th cell */
50680 int hdr; /* Offset to the page header */
50681 int size; /* Size of a cell */
50682 int usableSize; /* Number of usable bytes on a page */
50683 int cellOffset; /* Offset to the cell pointer array */
50684 int cbrk; /* Offset to the cell content area */
50685 int nCell; /* Number of cells on the page */
50686 unsigned char *data; /* The page data */
50687 unsigned char *temp; /* Temp area for cell content */
50688 int iCellFirst; /* First allowable cell index */
50689 int iCellLast; /* Last possible cell index */
50692 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50693 assert( pPage->pBt!=0 );
50694 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
50695 assert( pPage->nOverflow==0 );
50696 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50697 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
50698 data = pPage->aData;
50699 hdr = pPage->hdrOffset;
50700 cellOffset = pPage->cellOffset;
50701 nCell = pPage->nCell;
50702 assert( nCell==get2byte(&data[hdr+3]) );
50703 usableSize = pPage->pBt->usableSize;
50704 cbrk = get2byte(&data[hdr+5]);
50705 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
50706 cbrk = usableSize;
50707 iCellFirst = cellOffset + 2*nCell;
50708 iCellLast = usableSize - 4;
50709 for(i=0; i<nCell; i++){
50710 u8 *pAddr; /* The i-th cell pointer */
50711 pAddr = &data[cellOffset + i*2];
50712 pc = get2byte(pAddr);
50713 testcase( pc==iCellFirst );
50714 testcase( pc==iCellLast );
50715 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50716 /* These conditions have already been verified in btreeInitPage()
50717 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
50719 if( pc<iCellFirst || pc>iCellLast ){
50720 return SQLITE_CORRUPT_BKPT;
50722 #endif
50723 assert( pc>=iCellFirst && pc<=iCellLast );
50724 size = cellSizePtr(pPage, &temp[pc]);
50725 cbrk -= size;
50726 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50727 if( cbrk<iCellFirst ){
50728 return SQLITE_CORRUPT_BKPT;
50730 #else
50731 if( cbrk<iCellFirst || pc+size>usableSize ){
50732 return SQLITE_CORRUPT_BKPT;
50734 #endif
50735 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
50736 testcase( cbrk+size==usableSize );
50737 testcase( pc+size==usableSize );
50738 memcpy(&data[cbrk], &temp[pc], size);
50739 put2byte(pAddr, cbrk);
50741 assert( cbrk>=iCellFirst );
50742 put2byte(&data[hdr+5], cbrk);
50743 data[hdr+1] = 0;
50744 data[hdr+2] = 0;
50745 data[hdr+7] = 0;
50746 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
50747 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50748 if( cbrk-iCellFirst!=pPage->nFree ){
50749 return SQLITE_CORRUPT_BKPT;
50751 return SQLITE_OK;
50755 ** Allocate nByte bytes of space from within the B-Tree page passed
50756 ** as the first argument. Write into *pIdx the index into pPage->aData[]
50757 ** of the first byte of allocated space. Return either SQLITE_OK or
50758 ** an error code (usually SQLITE_CORRUPT).
50760 ** The caller guarantees that there is sufficient space to make the
50761 ** allocation. This routine might need to defragment in order to bring
50762 ** all the space together, however. This routine will avoid using
50763 ** the first two bytes past the cell pointer area since presumably this
50764 ** allocation is being made in order to insert a new cell, so we will
50765 ** also end up needing a new cell pointer.
50767 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
50768 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
50769 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
50770 int nFrag; /* Number of fragmented bytes on pPage */
50771 int top; /* First byte of cell content area */
50772 int gap; /* First byte of gap between cell pointers and cell content */
50773 int rc; /* Integer return code */
50774 int usableSize; /* Usable size of the page */
50776 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50777 assert( pPage->pBt );
50778 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50779 assert( nByte>=0 ); /* Minimum cell size is 4 */
50780 assert( pPage->nFree>=nByte );
50781 assert( pPage->nOverflow==0 );
50782 usableSize = pPage->pBt->usableSize;
50783 assert( nByte < usableSize-8 );
50785 nFrag = data[hdr+7];
50786 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
50787 gap = pPage->cellOffset + 2*pPage->nCell;
50788 top = get2byteNotZero(&data[hdr+5]);
50789 if( gap>top ) return SQLITE_CORRUPT_BKPT;
50790 testcase( gap+2==top );
50791 testcase( gap+1==top );
50792 testcase( gap==top );
50794 if( nFrag>=60 ){
50795 /* Always defragment highly fragmented pages */
50796 rc = defragmentPage(pPage);
50797 if( rc ) return rc;
50798 top = get2byteNotZero(&data[hdr+5]);
50799 }else if( gap+2<=top ){
50800 /* Search the freelist looking for a free slot big enough to satisfy
50801 ** the request. The allocation is made from the first free slot in
50802 ** the list that is large enough to accommodate it.
50804 int pc, addr;
50805 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
50806 int size; /* Size of the free slot */
50807 if( pc>usableSize-4 || pc<addr+4 ){
50808 return SQLITE_CORRUPT_BKPT;
50810 size = get2byte(&data[pc+2]);
50811 if( size>=nByte ){
50812 int x = size - nByte;
50813 testcase( x==4 );
50814 testcase( x==3 );
50815 if( x<4 ){
50816 /* Remove the slot from the free-list. Update the number of
50817 ** fragmented bytes within the page. */
50818 memcpy(&data[addr], &data[pc], 2);
50819 data[hdr+7] = (u8)(nFrag + x);
50820 }else if( size+pc > usableSize ){
50821 return SQLITE_CORRUPT_BKPT;
50822 }else{
50823 /* The slot remains on the free-list. Reduce its size to account
50824 ** for the portion used by the new allocation. */
50825 put2byte(&data[pc+2], x);
50827 *pIdx = pc + x;
50828 return SQLITE_OK;
50833 /* Check to make sure there is enough space in the gap to satisfy
50834 ** the allocation. If not, defragment.
50836 testcase( gap+2+nByte==top );
50837 if( gap+2+nByte>top ){
50838 rc = defragmentPage(pPage);
50839 if( rc ) return rc;
50840 top = get2byteNotZero(&data[hdr+5]);
50841 assert( gap+nByte<=top );
50845 /* Allocate memory from the gap in between the cell pointer array
50846 ** and the cell content area. The btreeInitPage() call has already
50847 ** validated the freelist. Given that the freelist is valid, there
50848 ** is no way that the allocation can extend off the end of the page.
50849 ** The assert() below verifies the previous sentence.
50851 top -= nByte;
50852 put2byte(&data[hdr+5], top);
50853 assert( top+nByte <= (int)pPage->pBt->usableSize );
50854 *pIdx = top;
50855 return SQLITE_OK;
50859 ** Return a section of the pPage->aData to the freelist.
50860 ** The first byte of the new free block is pPage->aDisk[start]
50861 ** and the size of the block is "size" bytes.
50863 ** Most of the effort here is involved in coalesing adjacent
50864 ** free blocks into a single big free block.
50866 static int freeSpace(MemPage *pPage, int start, int size){
50867 int addr, pbegin, hdr;
50868 int iLast; /* Largest possible freeblock offset */
50869 unsigned char *data = pPage->aData;
50871 assert( pPage->pBt!=0 );
50872 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50873 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
50874 assert( (start + size) <= (int)pPage->pBt->usableSize );
50875 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50876 assert( size>=0 ); /* Minimum cell size is 4 */
50878 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
50879 /* Overwrite deleted information with zeros when the secure_delete
50880 ** option is enabled */
50881 memset(&data[start], 0, size);
50884 /* Add the space back into the linked list of freeblocks. Note that
50885 ** even though the freeblock list was checked by btreeInitPage(),
50886 ** btreeInitPage() did not detect overlapping cells or
50887 ** freeblocks that overlapped cells. Nor does it detect when the
50888 ** cell content area exceeds the value in the page header. If these
50889 ** situations arise, then subsequent insert operations might corrupt
50890 ** the freelist. So we do need to check for corruption while scanning
50891 ** the freelist.
50893 hdr = pPage->hdrOffset;
50894 addr = hdr + 1;
50895 iLast = pPage->pBt->usableSize - 4;
50896 assert( start<=iLast );
50897 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
50898 if( pbegin<addr+4 ){
50899 return SQLITE_CORRUPT_BKPT;
50901 addr = pbegin;
50903 if( pbegin>iLast ){
50904 return SQLITE_CORRUPT_BKPT;
50906 assert( pbegin>addr || pbegin==0 );
50907 put2byte(&data[addr], start);
50908 put2byte(&data[start], pbegin);
50909 put2byte(&data[start+2], size);
50910 pPage->nFree = pPage->nFree + (u16)size;
50912 /* Coalesce adjacent free blocks */
50913 addr = hdr + 1;
50914 while( (pbegin = get2byte(&data[addr]))>0 ){
50915 int pnext, psize, x;
50916 assert( pbegin>addr );
50917 assert( pbegin <= (int)pPage->pBt->usableSize-4 );
50918 pnext = get2byte(&data[pbegin]);
50919 psize = get2byte(&data[pbegin+2]);
50920 if( pbegin + psize + 3 >= pnext && pnext>0 ){
50921 int frag = pnext - (pbegin+psize);
50922 if( (frag<0) || (frag>(int)data[hdr+7]) ){
50923 return SQLITE_CORRUPT_BKPT;
50925 data[hdr+7] -= (u8)frag;
50926 x = get2byte(&data[pnext]);
50927 put2byte(&data[pbegin], x);
50928 x = pnext + get2byte(&data[pnext+2]) - pbegin;
50929 put2byte(&data[pbegin+2], x);
50930 }else{
50931 addr = pbegin;
50935 /* If the cell content area begins with a freeblock, remove it. */
50936 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
50937 int top;
50938 pbegin = get2byte(&data[hdr+1]);
50939 memcpy(&data[hdr+1], &data[pbegin], 2);
50940 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
50941 put2byte(&data[hdr+5], top);
50943 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50944 return SQLITE_OK;
50948 ** Decode the flags byte (the first byte of the header) for a page
50949 ** and initialize fields of the MemPage structure accordingly.
50951 ** Only the following combinations are supported. Anything different
50952 ** indicates a corrupt database files:
50954 ** PTF_ZERODATA
50955 ** PTF_ZERODATA | PTF_LEAF
50956 ** PTF_LEAFDATA | PTF_INTKEY
50957 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
50959 static int decodeFlags(MemPage *pPage, int flagByte){
50960 BtShared *pBt; /* A copy of pPage->pBt */
50962 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
50963 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50964 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
50965 flagByte &= ~PTF_LEAF;
50966 pPage->childPtrSize = 4-4*pPage->leaf;
50967 pBt = pPage->pBt;
50968 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
50969 pPage->intKey = 1;
50970 pPage->hasData = pPage->leaf;
50971 pPage->maxLocal = pBt->maxLeaf;
50972 pPage->minLocal = pBt->minLeaf;
50973 }else if( flagByte==PTF_ZERODATA ){
50974 pPage->intKey = 0;
50975 pPage->hasData = 0;
50976 pPage->maxLocal = pBt->maxLocal;
50977 pPage->minLocal = pBt->minLocal;
50978 }else{
50979 return SQLITE_CORRUPT_BKPT;
50981 pPage->max1bytePayload = pBt->max1bytePayload;
50982 return SQLITE_OK;
50986 ** Initialize the auxiliary information for a disk block.
50988 ** Return SQLITE_OK on success. If we see that the page does
50989 ** not contain a well-formed database page, then return
50990 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
50991 ** guarantee that the page is well-formed. It only shows that
50992 ** we failed to detect any corruption.
50994 static int btreeInitPage(MemPage *pPage){
50996 assert( pPage->pBt!=0 );
50997 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50998 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
50999 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
51000 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
51002 if( !pPage->isInit ){
51003 u16 pc; /* Address of a freeblock within pPage->aData[] */
51004 u8 hdr; /* Offset to beginning of page header */
51005 u8 *data; /* Equal to pPage->aData */
51006 BtShared *pBt; /* The main btree structure */
51007 int usableSize; /* Amount of usable space on each page */
51008 u16 cellOffset; /* Offset from start of page to first cell pointer */
51009 int nFree; /* Number of unused bytes on the page */
51010 int top; /* First byte of the cell content area */
51011 int iCellFirst; /* First allowable cell or freeblock offset */
51012 int iCellLast; /* Last possible cell or freeblock offset */
51014 pBt = pPage->pBt;
51016 hdr = pPage->hdrOffset;
51017 data = pPage->aData;
51018 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
51019 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
51020 pPage->maskPage = (u16)(pBt->pageSize - 1);
51021 pPage->nOverflow = 0;
51022 usableSize = pBt->usableSize;
51023 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
51024 pPage->aDataEnd = &data[usableSize];
51025 pPage->aCellIdx = &data[cellOffset];
51026 top = get2byteNotZero(&data[hdr+5]);
51027 pPage->nCell = get2byte(&data[hdr+3]);
51028 if( pPage->nCell>MX_CELL(pBt) ){
51029 /* To many cells for a single page. The page must be corrupt */
51030 return SQLITE_CORRUPT_BKPT;
51032 testcase( pPage->nCell==MX_CELL(pBt) );
51034 /* A malformed database page might cause us to read past the end
51035 ** of page when parsing a cell.
51037 ** The following block of code checks early to see if a cell extends
51038 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
51039 ** returned if it does.
51041 iCellFirst = cellOffset + 2*pPage->nCell;
51042 iCellLast = usableSize - 4;
51043 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51045 int i; /* Index into the cell pointer array */
51046 int sz; /* Size of a cell */
51048 if( !pPage->leaf ) iCellLast--;
51049 for(i=0; i<pPage->nCell; i++){
51050 pc = get2byte(&data[cellOffset+i*2]);
51051 testcase( pc==iCellFirst );
51052 testcase( pc==iCellLast );
51053 if( pc<iCellFirst || pc>iCellLast ){
51054 return SQLITE_CORRUPT_BKPT;
51056 sz = cellSizePtr(pPage, &data[pc]);
51057 testcase( pc+sz==usableSize );
51058 if( pc+sz>usableSize ){
51059 return SQLITE_CORRUPT_BKPT;
51062 if( !pPage->leaf ) iCellLast++;
51064 #endif
51066 /* Compute the total free space on the page */
51067 pc = get2byte(&data[hdr+1]);
51068 nFree = data[hdr+7] + top;
51069 while( pc>0 ){
51070 u16 next, size;
51071 if( pc<iCellFirst || pc>iCellLast ){
51072 /* Start of free block is off the page */
51073 return SQLITE_CORRUPT_BKPT;
51075 next = get2byte(&data[pc]);
51076 size = get2byte(&data[pc+2]);
51077 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
51078 /* Free blocks must be in ascending order. And the last byte of
51079 ** the free-block must lie on the database page. */
51080 return SQLITE_CORRUPT_BKPT;
51082 nFree = nFree + size;
51083 pc = next;
51086 /* At this point, nFree contains the sum of the offset to the start
51087 ** of the cell-content area plus the number of free bytes within
51088 ** the cell-content area. If this is greater than the usable-size
51089 ** of the page, then the page must be corrupted. This check also
51090 ** serves to verify that the offset to the start of the cell-content
51091 ** area, according to the page header, lies within the page.
51093 if( nFree>usableSize ){
51094 return SQLITE_CORRUPT_BKPT;
51096 pPage->nFree = (u16)(nFree - iCellFirst);
51097 pPage->isInit = 1;
51099 return SQLITE_OK;
51103 ** Set up a raw page so that it looks like a database page holding
51104 ** no entries.
51106 static void zeroPage(MemPage *pPage, int flags){
51107 unsigned char *data = pPage->aData;
51108 BtShared *pBt = pPage->pBt;
51109 u8 hdr = pPage->hdrOffset;
51110 u16 first;
51112 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
51113 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51114 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
51115 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51116 assert( sqlite3_mutex_held(pBt->mutex) );
51117 if( pBt->btsFlags & BTS_SECURE_DELETE ){
51118 memset(&data[hdr], 0, pBt->usableSize - hdr);
51120 data[hdr] = (char)flags;
51121 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
51122 memset(&data[hdr+1], 0, 4);
51123 data[hdr+7] = 0;
51124 put2byte(&data[hdr+5], pBt->usableSize);
51125 pPage->nFree = (u16)(pBt->usableSize - first);
51126 decodeFlags(pPage, flags);
51127 pPage->hdrOffset = hdr;
51128 pPage->cellOffset = first;
51129 pPage->aDataEnd = &data[pBt->usableSize];
51130 pPage->aCellIdx = &data[first];
51131 pPage->nOverflow = 0;
51132 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
51133 pPage->maskPage = (u16)(pBt->pageSize - 1);
51134 pPage->nCell = 0;
51135 pPage->isInit = 1;
51140 ** Convert a DbPage obtained from the pager into a MemPage used by
51141 ** the btree layer.
51143 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
51144 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
51145 pPage->aData = sqlite3PagerGetData(pDbPage);
51146 pPage->pDbPage = pDbPage;
51147 pPage->pBt = pBt;
51148 pPage->pgno = pgno;
51149 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
51150 return pPage;
51154 ** Get a page from the pager. Initialize the MemPage.pBt and
51155 ** MemPage.aData elements if needed.
51157 ** If the noContent flag is set, it means that we do not care about
51158 ** the content of the page at this time. So do not go to the disk
51159 ** to fetch the content. Just fill in the content with zeros for now.
51160 ** If in the future we call sqlite3PagerWrite() on this page, that
51161 ** means we have started to be concerned about content and the disk
51162 ** read should occur at that point.
51164 static int btreeGetPage(
51165 BtShared *pBt, /* The btree */
51166 Pgno pgno, /* Number of the page to fetch */
51167 MemPage **ppPage, /* Return the page in this parameter */
51168 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
51170 int rc;
51171 DbPage *pDbPage;
51173 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
51174 assert( sqlite3_mutex_held(pBt->mutex) );
51175 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
51176 if( rc ) return rc;
51177 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
51178 return SQLITE_OK;
51182 ** Retrieve a page from the pager cache. If the requested page is not
51183 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
51184 ** MemPage.aData elements if needed.
51186 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
51187 DbPage *pDbPage;
51188 assert( sqlite3_mutex_held(pBt->mutex) );
51189 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
51190 if( pDbPage ){
51191 return btreePageFromDbPage(pDbPage, pgno, pBt);
51193 return 0;
51197 ** Return the size of the database file in pages. If there is any kind of
51198 ** error, return ((unsigned int)-1).
51200 static Pgno btreePagecount(BtShared *pBt){
51201 return pBt->nPage;
51203 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
51204 assert( sqlite3BtreeHoldsMutex(p) );
51205 assert( ((p->pBt->nPage)&0x8000000)==0 );
51206 return (int)btreePagecount(p->pBt);
51210 ** Get a page from the pager and initialize it. This routine is just a
51211 ** convenience wrapper around separate calls to btreeGetPage() and
51212 ** btreeInitPage().
51214 ** If an error occurs, then the value *ppPage is set to is undefined. It
51215 ** may remain unchanged, or it may be set to an invalid value.
51217 static int getAndInitPage(
51218 BtShared *pBt, /* The database file */
51219 Pgno pgno, /* Number of the page to get */
51220 MemPage **ppPage, /* Write the page pointer here */
51221 int bReadonly /* PAGER_GET_READONLY or 0 */
51223 int rc;
51224 assert( sqlite3_mutex_held(pBt->mutex) );
51225 assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
51227 if( pgno>btreePagecount(pBt) ){
51228 rc = SQLITE_CORRUPT_BKPT;
51229 }else{
51230 rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
51231 if( rc==SQLITE_OK ){
51232 rc = btreeInitPage(*ppPage);
51233 if( rc!=SQLITE_OK ){
51234 releasePage(*ppPage);
51239 testcase( pgno==0 );
51240 assert( pgno!=0 || rc==SQLITE_CORRUPT );
51241 return rc;
51245 ** Release a MemPage. This should be called once for each prior
51246 ** call to btreeGetPage.
51248 static void releasePage(MemPage *pPage){
51249 if( pPage ){
51250 assert( pPage->aData );
51251 assert( pPage->pBt );
51252 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51253 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
51254 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51255 sqlite3PagerUnref(pPage->pDbPage);
51260 ** During a rollback, when the pager reloads information into the cache
51261 ** so that the cache is restored to its original state at the start of
51262 ** the transaction, for each page restored this routine is called.
51264 ** This routine needs to reset the extra data section at the end of the
51265 ** page to agree with the restored data.
51267 static void pageReinit(DbPage *pData){
51268 MemPage *pPage;
51269 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
51270 assert( sqlite3PagerPageRefcount(pData)>0 );
51271 if( pPage->isInit ){
51272 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51273 pPage->isInit = 0;
51274 if( sqlite3PagerPageRefcount(pData)>1 ){
51275 /* pPage might not be a btree page; it might be an overflow page
51276 ** or ptrmap page or a free page. In those cases, the following
51277 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
51278 ** But no harm is done by this. And it is very important that
51279 ** btreeInitPage() be called on every btree page so we make
51280 ** the call for every page that comes in for re-initing. */
51281 btreeInitPage(pPage);
51287 ** Invoke the busy handler for a btree.
51289 static int btreeInvokeBusyHandler(void *pArg){
51290 BtShared *pBt = (BtShared*)pArg;
51291 assert( pBt->db );
51292 assert( sqlite3_mutex_held(pBt->db->mutex) );
51293 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
51297 ** Open a database file.
51299 ** zFilename is the name of the database file. If zFilename is NULL
51300 ** then an ephemeral database is created. The ephemeral database might
51301 ** be exclusively in memory, or it might use a disk-based memory cache.
51302 ** Either way, the ephemeral database will be automatically deleted
51303 ** when sqlite3BtreeClose() is called.
51305 ** If zFilename is ":memory:" then an in-memory database is created
51306 ** that is automatically destroyed when it is closed.
51308 ** The "flags" parameter is a bitmask that might contain bits like
51309 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
51311 ** If the database is already opened in the same database connection
51312 ** and we are in shared cache mode, then the open will fail with an
51313 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
51314 ** objects in the same database connection since doing so will lead
51315 ** to problems with locking.
51317 SQLITE_PRIVATE int sqlite3BtreeOpen(
51318 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
51319 const char *zFilename, /* Name of the file containing the BTree database */
51320 sqlite3 *db, /* Associated database handle */
51321 Btree **ppBtree, /* Pointer to new Btree object written here */
51322 int flags, /* Options */
51323 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
51325 BtShared *pBt = 0; /* Shared part of btree structure */
51326 Btree *p; /* Handle to return */
51327 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
51328 int rc = SQLITE_OK; /* Result code from this function */
51329 u8 nReserve; /* Byte of unused space on each page */
51330 unsigned char zDbHeader[100]; /* Database header content */
51332 /* True if opening an ephemeral, temporary database */
51333 const int isTempDb = zFilename==0 || zFilename[0]==0;
51335 /* Set the variable isMemdb to true for an in-memory database, or
51336 ** false for a file-based database.
51338 #ifdef SQLITE_OMIT_MEMORYDB
51339 const int isMemdb = 0;
51340 #else
51341 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
51342 || (isTempDb && sqlite3TempInMemory(db))
51343 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
51344 #endif
51346 assert( db!=0 );
51347 assert( pVfs!=0 );
51348 assert( sqlite3_mutex_held(db->mutex) );
51349 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
51351 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
51352 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
51354 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
51355 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
51357 if( isMemdb ){
51358 flags |= BTREE_MEMORY;
51360 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
51361 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
51363 p = sqlite3MallocZero(sizeof(Btree));
51364 if( !p ){
51365 return SQLITE_NOMEM;
51367 p->inTrans = TRANS_NONE;
51368 p->db = db;
51369 #ifndef SQLITE_OMIT_SHARED_CACHE
51370 p->lock.pBtree = p;
51371 p->lock.iTable = 1;
51372 #endif
51374 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51376 ** If this Btree is a candidate for shared cache, try to find an
51377 ** existing BtShared object that we can share with
51379 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
51380 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
51381 int nFullPathname = pVfs->mxPathname+1;
51382 char *zFullPathname = sqlite3Malloc(nFullPathname);
51383 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51384 p->sharable = 1;
51385 if( !zFullPathname ){
51386 sqlite3_free(p);
51387 return SQLITE_NOMEM;
51389 if( isMemdb ){
51390 memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
51391 }else{
51392 rc = sqlite3OsFullPathname(pVfs, zFilename,
51393 nFullPathname, zFullPathname);
51394 if( rc ){
51395 sqlite3_free(zFullPathname);
51396 sqlite3_free(p);
51397 return rc;
51400 #if SQLITE_THREADSAFE
51401 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
51402 sqlite3_mutex_enter(mutexOpen);
51403 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
51404 sqlite3_mutex_enter(mutexShared);
51405 #endif
51406 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
51407 assert( pBt->nRef>0 );
51408 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
51409 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
51410 int iDb;
51411 for(iDb=db->nDb-1; iDb>=0; iDb--){
51412 Btree *pExisting = db->aDb[iDb].pBt;
51413 if( pExisting && pExisting->pBt==pBt ){
51414 sqlite3_mutex_leave(mutexShared);
51415 sqlite3_mutex_leave(mutexOpen);
51416 sqlite3_free(zFullPathname);
51417 sqlite3_free(p);
51418 return SQLITE_CONSTRAINT;
51421 p->pBt = pBt;
51422 pBt->nRef++;
51423 break;
51426 sqlite3_mutex_leave(mutexShared);
51427 sqlite3_free(zFullPathname);
51429 #ifdef SQLITE_DEBUG
51430 else{
51431 /* In debug mode, we mark all persistent databases as sharable
51432 ** even when they are not. This exercises the locking code and
51433 ** gives more opportunity for asserts(sqlite3_mutex_held())
51434 ** statements to find locking problems.
51436 p->sharable = 1;
51438 #endif
51440 #endif
51441 if( pBt==0 ){
51443 ** The following asserts make sure that structures used by the btree are
51444 ** the right size. This is to guard against size changes that result
51445 ** when compiling on a different architecture.
51447 assert( sizeof(i64)==8 || sizeof(i64)==4 );
51448 assert( sizeof(u64)==8 || sizeof(u64)==4 );
51449 assert( sizeof(u32)==4 );
51450 assert( sizeof(u16)==2 );
51451 assert( sizeof(Pgno)==4 );
51453 pBt = sqlite3MallocZero( sizeof(*pBt) );
51454 if( pBt==0 ){
51455 rc = SQLITE_NOMEM;
51456 goto btree_open_out;
51458 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
51459 EXTRA_SIZE, flags, vfsFlags, pageReinit);
51460 if( rc==SQLITE_OK ){
51461 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
51462 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
51464 if( rc!=SQLITE_OK ){
51465 goto btree_open_out;
51467 pBt->openFlags = (u8)flags;
51468 pBt->db = db;
51469 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
51470 p->pBt = pBt;
51472 pBt->pCursor = 0;
51473 pBt->pPage1 = 0;
51474 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
51475 #ifdef SQLITE_SECURE_DELETE
51476 pBt->btsFlags |= BTS_SECURE_DELETE;
51477 #endif
51478 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
51479 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
51480 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
51481 pBt->pageSize = 0;
51482 #ifndef SQLITE_OMIT_AUTOVACUUM
51483 /* If the magic name ":memory:" will create an in-memory database, then
51484 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
51485 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
51486 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
51487 ** regular file-name. In this case the auto-vacuum applies as per normal.
51489 if( zFilename && !isMemdb ){
51490 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
51491 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
51493 #endif
51494 nReserve = 0;
51495 }else{
51496 nReserve = zDbHeader[20];
51497 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51498 #ifndef SQLITE_OMIT_AUTOVACUUM
51499 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
51500 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
51501 #endif
51503 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51504 if( rc ) goto btree_open_out;
51505 pBt->usableSize = pBt->pageSize - nReserve;
51506 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
51508 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51509 /* Add the new BtShared object to the linked list sharable BtShareds.
51511 if( p->sharable ){
51512 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51513 pBt->nRef = 1;
51514 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
51515 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
51516 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
51517 if( pBt->mutex==0 ){
51518 rc = SQLITE_NOMEM;
51519 db->mallocFailed = 0;
51520 goto btree_open_out;
51523 sqlite3_mutex_enter(mutexShared);
51524 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
51525 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
51526 sqlite3_mutex_leave(mutexShared);
51528 #endif
51531 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51532 /* If the new Btree uses a sharable pBtShared, then link the new
51533 ** Btree into the list of all sharable Btrees for the same connection.
51534 ** The list is kept in ascending order by pBt address.
51536 if( p->sharable ){
51537 int i;
51538 Btree *pSib;
51539 for(i=0; i<db->nDb; i++){
51540 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
51541 while( pSib->pPrev ){ pSib = pSib->pPrev; }
51542 if( p->pBt<pSib->pBt ){
51543 p->pNext = pSib;
51544 p->pPrev = 0;
51545 pSib->pPrev = p;
51546 }else{
51547 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
51548 pSib = pSib->pNext;
51550 p->pNext = pSib->pNext;
51551 p->pPrev = pSib;
51552 if( p->pNext ){
51553 p->pNext->pPrev = p;
51555 pSib->pNext = p;
51557 break;
51561 #endif
51562 *ppBtree = p;
51564 btree_open_out:
51565 if( rc!=SQLITE_OK ){
51566 if( pBt && pBt->pPager ){
51567 sqlite3PagerClose(pBt->pPager);
51569 sqlite3_free(pBt);
51570 sqlite3_free(p);
51571 *ppBtree = 0;
51572 }else{
51573 /* If the B-Tree was successfully opened, set the pager-cache size to the
51574 ** default value. Except, when opening on an existing shared pager-cache,
51575 ** do not change the pager-cache size.
51577 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
51578 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
51581 if( mutexOpen ){
51582 assert( sqlite3_mutex_held(mutexOpen) );
51583 sqlite3_mutex_leave(mutexOpen);
51585 return rc;
51589 ** Decrement the BtShared.nRef counter. When it reaches zero,
51590 ** remove the BtShared structure from the sharing list. Return
51591 ** true if the BtShared.nRef counter reaches zero and return
51592 ** false if it is still positive.
51594 static int removeFromSharingList(BtShared *pBt){
51595 #ifndef SQLITE_OMIT_SHARED_CACHE
51596 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
51597 BtShared *pList;
51598 int removed = 0;
51600 assert( sqlite3_mutex_notheld(pBt->mutex) );
51601 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
51602 sqlite3_mutex_enter(pMaster);
51603 pBt->nRef--;
51604 if( pBt->nRef<=0 ){
51605 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
51606 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
51607 }else{
51608 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
51609 while( ALWAYS(pList) && pList->pNext!=pBt ){
51610 pList=pList->pNext;
51612 if( ALWAYS(pList) ){
51613 pList->pNext = pBt->pNext;
51616 if( SQLITE_THREADSAFE ){
51617 sqlite3_mutex_free(pBt->mutex);
51619 removed = 1;
51621 sqlite3_mutex_leave(pMaster);
51622 return removed;
51623 #else
51624 return 1;
51625 #endif
51629 ** Make sure pBt->pTmpSpace points to an allocation of
51630 ** MX_CELL_SIZE(pBt) bytes.
51632 static void allocateTempSpace(BtShared *pBt){
51633 if( !pBt->pTmpSpace ){
51634 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
51639 ** Free the pBt->pTmpSpace allocation
51641 static void freeTempSpace(BtShared *pBt){
51642 sqlite3PageFree( pBt->pTmpSpace);
51643 pBt->pTmpSpace = 0;
51647 ** Close an open database and invalidate all cursors.
51649 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
51650 BtShared *pBt = p->pBt;
51651 BtCursor *pCur;
51653 /* Close all cursors opened via this handle. */
51654 assert( sqlite3_mutex_held(p->db->mutex) );
51655 sqlite3BtreeEnter(p);
51656 pCur = pBt->pCursor;
51657 while( pCur ){
51658 BtCursor *pTmp = pCur;
51659 pCur = pCur->pNext;
51660 if( pTmp->pBtree==p ){
51661 sqlite3BtreeCloseCursor(pTmp);
51665 /* Rollback any active transaction and free the handle structure.
51666 ** The call to sqlite3BtreeRollback() drops any table-locks held by
51667 ** this handle.
51669 sqlite3BtreeRollback(p, SQLITE_OK);
51670 sqlite3BtreeLeave(p);
51672 /* If there are still other outstanding references to the shared-btree
51673 ** structure, return now. The remainder of this procedure cleans
51674 ** up the shared-btree.
51676 assert( p->wantToLock==0 && p->locked==0 );
51677 if( !p->sharable || removeFromSharingList(pBt) ){
51678 /* The pBt is no longer on the sharing list, so we can access
51679 ** it without having to hold the mutex.
51681 ** Clean out and delete the BtShared object.
51683 assert( !pBt->pCursor );
51684 sqlite3PagerClose(pBt->pPager);
51685 if( pBt->xFreeSchema && pBt->pSchema ){
51686 pBt->xFreeSchema(pBt->pSchema);
51688 sqlite3DbFree(0, pBt->pSchema);
51689 freeTempSpace(pBt);
51690 sqlite3_free(pBt);
51693 #ifndef SQLITE_OMIT_SHARED_CACHE
51694 assert( p->wantToLock==0 );
51695 assert( p->locked==0 );
51696 if( p->pPrev ) p->pPrev->pNext = p->pNext;
51697 if( p->pNext ) p->pNext->pPrev = p->pPrev;
51698 #endif
51700 sqlite3_free(p);
51701 return SQLITE_OK;
51705 ** Change the limit on the number of pages allowed in the cache.
51707 ** The maximum number of cache pages is set to the absolute
51708 ** value of mxPage. If mxPage is negative, the pager will
51709 ** operate asynchronously - it will not stop to do fsync()s
51710 ** to insure data is written to the disk surface before
51711 ** continuing. Transactions still work if synchronous is off,
51712 ** and the database cannot be corrupted if this program
51713 ** crashes. But if the operating system crashes or there is
51714 ** an abrupt power failure when synchronous is off, the database
51715 ** could be left in an inconsistent and unrecoverable state.
51716 ** Synchronous is on by default so database corruption is not
51717 ** normally a worry.
51719 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
51720 BtShared *pBt = p->pBt;
51721 assert( sqlite3_mutex_held(p->db->mutex) );
51722 sqlite3BtreeEnter(p);
51723 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
51724 sqlite3BtreeLeave(p);
51725 return SQLITE_OK;
51729 ** Change the limit on the amount of the database file that may be
51730 ** memory mapped.
51732 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
51733 BtShared *pBt = p->pBt;
51734 assert( sqlite3_mutex_held(p->db->mutex) );
51735 sqlite3BtreeEnter(p);
51736 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
51737 sqlite3BtreeLeave(p);
51738 return SQLITE_OK;
51742 ** Change the way data is synced to disk in order to increase or decrease
51743 ** how well the database resists damage due to OS crashes and power
51744 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
51745 ** there is a high probability of damage) Level 2 is the default. There
51746 ** is a very low but non-zero probability of damage. Level 3 reduces the
51747 ** probability of damage to near zero but with a write performance reduction.
51749 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
51750 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
51751 Btree *p, /* The btree to set the safety level on */
51752 unsigned pgFlags /* Various PAGER_* flags */
51754 BtShared *pBt = p->pBt;
51755 assert( sqlite3_mutex_held(p->db->mutex) );
51756 sqlite3BtreeEnter(p);
51757 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
51758 sqlite3BtreeLeave(p);
51759 return SQLITE_OK;
51761 #endif
51764 ** Return TRUE if the given btree is set to safety level 1. In other
51765 ** words, return TRUE if no sync() occurs on the disk files.
51767 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
51768 BtShared *pBt = p->pBt;
51769 int rc;
51770 assert( sqlite3_mutex_held(p->db->mutex) );
51771 sqlite3BtreeEnter(p);
51772 assert( pBt && pBt->pPager );
51773 rc = sqlite3PagerNosync(pBt->pPager);
51774 sqlite3BtreeLeave(p);
51775 return rc;
51779 ** Change the default pages size and the number of reserved bytes per page.
51780 ** Or, if the page size has already been fixed, return SQLITE_READONLY
51781 ** without changing anything.
51783 ** The page size must be a power of 2 between 512 and 65536. If the page
51784 ** size supplied does not meet this constraint then the page size is not
51785 ** changed.
51787 ** Page sizes are constrained to be a power of two so that the region
51788 ** of the database file used for locking (beginning at PENDING_BYTE,
51789 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
51790 ** at the beginning of a page.
51792 ** If parameter nReserve is less than zero, then the number of reserved
51793 ** bytes per page is left unchanged.
51795 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
51796 ** and autovacuum mode can no longer be changed.
51798 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
51799 int rc = SQLITE_OK;
51800 BtShared *pBt = p->pBt;
51801 assert( nReserve>=-1 && nReserve<=255 );
51802 sqlite3BtreeEnter(p);
51803 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
51804 sqlite3BtreeLeave(p);
51805 return SQLITE_READONLY;
51807 if( nReserve<0 ){
51808 nReserve = pBt->pageSize - pBt->usableSize;
51810 assert( nReserve>=0 && nReserve<=255 );
51811 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
51812 ((pageSize-1)&pageSize)==0 ){
51813 assert( (pageSize & 7)==0 );
51814 assert( !pBt->pPage1 && !pBt->pCursor );
51815 pBt->pageSize = (u32)pageSize;
51816 freeTempSpace(pBt);
51818 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51819 pBt->usableSize = pBt->pageSize - (u16)nReserve;
51820 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51821 sqlite3BtreeLeave(p);
51822 return rc;
51826 ** Return the currently defined page size
51828 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
51829 return p->pBt->pageSize;
51832 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
51834 ** This function is similar to sqlite3BtreeGetReserve(), except that it
51835 ** may only be called if it is guaranteed that the b-tree mutex is already
51836 ** held.
51838 ** This is useful in one special case in the backup API code where it is
51839 ** known that the shared b-tree mutex is held, but the mutex on the
51840 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
51841 ** were to be called, it might collide with some other operation on the
51842 ** database handle that owns *p, causing undefined behavior.
51844 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
51845 assert( sqlite3_mutex_held(p->pBt->mutex) );
51846 return p->pBt->pageSize - p->pBt->usableSize;
51848 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
51850 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
51852 ** Return the number of bytes of space at the end of every page that
51853 ** are intentually left unused. This is the "reserved" space that is
51854 ** sometimes used by extensions.
51856 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
51857 int n;
51858 sqlite3BtreeEnter(p);
51859 n = p->pBt->pageSize - p->pBt->usableSize;
51860 sqlite3BtreeLeave(p);
51861 return n;
51865 ** Set the maximum page count for a database if mxPage is positive.
51866 ** No changes are made if mxPage is 0 or negative.
51867 ** Regardless of the value of mxPage, return the maximum page count.
51869 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
51870 int n;
51871 sqlite3BtreeEnter(p);
51872 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
51873 sqlite3BtreeLeave(p);
51874 return n;
51878 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
51879 ** then make no changes. Always return the value of the BTS_SECURE_DELETE
51880 ** setting after the change.
51882 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
51883 int b;
51884 if( p==0 ) return 0;
51885 sqlite3BtreeEnter(p);
51886 if( newFlag>=0 ){
51887 p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
51888 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
51890 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
51891 sqlite3BtreeLeave(p);
51892 return b;
51894 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
51897 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
51898 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
51899 ** is disabled. The default value for the auto-vacuum property is
51900 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
51902 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
51903 #ifdef SQLITE_OMIT_AUTOVACUUM
51904 return SQLITE_READONLY;
51905 #else
51906 BtShared *pBt = p->pBt;
51907 int rc = SQLITE_OK;
51908 u8 av = (u8)autoVacuum;
51910 sqlite3BtreeEnter(p);
51911 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
51912 rc = SQLITE_READONLY;
51913 }else{
51914 pBt->autoVacuum = av ?1:0;
51915 pBt->incrVacuum = av==2 ?1:0;
51917 sqlite3BtreeLeave(p);
51918 return rc;
51919 #endif
51923 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
51924 ** enabled 1 is returned. Otherwise 0.
51926 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
51927 #ifdef SQLITE_OMIT_AUTOVACUUM
51928 return BTREE_AUTOVACUUM_NONE;
51929 #else
51930 int rc;
51931 sqlite3BtreeEnter(p);
51932 rc = (
51933 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
51934 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
51935 BTREE_AUTOVACUUM_INCR
51937 sqlite3BtreeLeave(p);
51938 return rc;
51939 #endif
51944 ** Get a reference to pPage1 of the database file. This will
51945 ** also acquire a readlock on that file.
51947 ** SQLITE_OK is returned on success. If the file is not a
51948 ** well-formed database file, then SQLITE_CORRUPT is returned.
51949 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
51950 ** is returned if we run out of memory.
51952 static int lockBtree(BtShared *pBt){
51953 int rc; /* Result code from subfunctions */
51954 MemPage *pPage1; /* Page 1 of the database file */
51955 int nPage; /* Number of pages in the database */
51956 int nPageFile = 0; /* Number of pages in the database file */
51957 int nPageHeader; /* Number of pages in the database according to hdr */
51959 assert( sqlite3_mutex_held(pBt->mutex) );
51960 assert( pBt->pPage1==0 );
51961 rc = sqlite3PagerSharedLock(pBt->pPager);
51962 if( rc!=SQLITE_OK ) return rc;
51963 rc = btreeGetPage(pBt, 1, &pPage1, 0);
51964 if( rc!=SQLITE_OK ) return rc;
51966 /* Do some checking to help insure the file we opened really is
51967 ** a valid database file.
51969 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
51970 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
51971 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
51972 nPage = nPageFile;
51974 if( nPage>0 ){
51975 u32 pageSize;
51976 u32 usableSize;
51977 u8 *page1 = pPage1->aData;
51978 rc = SQLITE_NOTADB;
51979 if( memcmp(page1, zMagicHeader, 16)!=0 ){
51980 goto page1_init_failed;
51983 #ifdef SQLITE_OMIT_WAL
51984 if( page1[18]>1 ){
51985 pBt->btsFlags |= BTS_READ_ONLY;
51987 if( page1[19]>1 ){
51988 goto page1_init_failed;
51990 #else
51991 if( page1[18]>2 ){
51992 pBt->btsFlags |= BTS_READ_ONLY;
51994 if( page1[19]>2 ){
51995 goto page1_init_failed;
51998 /* If the write version is set to 2, this database should be accessed
51999 ** in WAL mode. If the log is not already open, open it now. Then
52000 ** return SQLITE_OK and return without populating BtShared.pPage1.
52001 ** The caller detects this and calls this function again. This is
52002 ** required as the version of page 1 currently in the page1 buffer
52003 ** may not be the latest version - there may be a newer one in the log
52004 ** file.
52006 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
52007 int isOpen = 0;
52008 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
52009 if( rc!=SQLITE_OK ){
52010 goto page1_init_failed;
52011 }else if( isOpen==0 ){
52012 releasePage(pPage1);
52013 return SQLITE_OK;
52015 rc = SQLITE_NOTADB;
52017 #endif
52019 /* The maximum embedded fraction must be exactly 25%. And the minimum
52020 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
52021 ** The original design allowed these amounts to vary, but as of
52022 ** version 3.6.0, we require them to be fixed.
52024 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
52025 goto page1_init_failed;
52027 pageSize = (page1[16]<<8) | (page1[17]<<16);
52028 if( ((pageSize-1)&pageSize)!=0
52029 || pageSize>SQLITE_MAX_PAGE_SIZE
52030 || pageSize<=256
52032 goto page1_init_failed;
52034 assert( (pageSize & 7)==0 );
52035 usableSize = pageSize - page1[20];
52036 if( (u32)pageSize!=pBt->pageSize ){
52037 /* After reading the first page of the database assuming a page size
52038 ** of BtShared.pageSize, we have discovered that the page-size is
52039 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
52040 ** zero and return SQLITE_OK. The caller will call this function
52041 ** again with the correct page-size.
52043 releasePage(pPage1);
52044 pBt->usableSize = usableSize;
52045 pBt->pageSize = pageSize;
52046 freeTempSpace(pBt);
52047 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
52048 pageSize-usableSize);
52049 return rc;
52051 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
52052 rc = SQLITE_CORRUPT_BKPT;
52053 goto page1_init_failed;
52055 if( usableSize<480 ){
52056 goto page1_init_failed;
52058 pBt->pageSize = pageSize;
52059 pBt->usableSize = usableSize;
52060 #ifndef SQLITE_OMIT_AUTOVACUUM
52061 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
52062 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
52063 #endif
52066 /* maxLocal is the maximum amount of payload to store locally for
52067 ** a cell. Make sure it is small enough so that at least minFanout
52068 ** cells can will fit on one page. We assume a 10-byte page header.
52069 ** Besides the payload, the cell must store:
52070 ** 2-byte pointer to the cell
52071 ** 4-byte child pointer
52072 ** 9-byte nKey value
52073 ** 4-byte nData value
52074 ** 4-byte overflow page pointer
52075 ** So a cell consists of a 2-byte pointer, a header which is as much as
52076 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
52077 ** page pointer.
52079 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
52080 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
52081 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
52082 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
52083 if( pBt->maxLocal>127 ){
52084 pBt->max1bytePayload = 127;
52085 }else{
52086 pBt->max1bytePayload = (u8)pBt->maxLocal;
52088 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
52089 pBt->pPage1 = pPage1;
52090 pBt->nPage = nPage;
52091 return SQLITE_OK;
52093 page1_init_failed:
52094 releasePage(pPage1);
52095 pBt->pPage1 = 0;
52096 return rc;
52099 #ifndef NDEBUG
52101 ** Return the number of cursors open on pBt. This is for use
52102 ** in assert() expressions, so it is only compiled if NDEBUG is not
52103 ** defined.
52105 ** Only write cursors are counted if wrOnly is true. If wrOnly is
52106 ** false then all cursors are counted.
52108 ** For the purposes of this routine, a cursor is any cursor that
52109 ** is capable of reading or writing to the databse. Cursors that
52110 ** have been tripped into the CURSOR_FAULT state are not counted.
52112 static int countValidCursors(BtShared *pBt, int wrOnly){
52113 BtCursor *pCur;
52114 int r = 0;
52115 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
52116 if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++;
52118 return r;
52120 #endif
52123 ** If there are no outstanding cursors and we are not in the middle
52124 ** of a transaction but there is a read lock on the database, then
52125 ** this routine unrefs the first page of the database file which
52126 ** has the effect of releasing the read lock.
52128 ** If there is a transaction in progress, this routine is a no-op.
52130 static void unlockBtreeIfUnused(BtShared *pBt){
52131 assert( sqlite3_mutex_held(pBt->mutex) );
52132 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
52133 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
52134 assert( pBt->pPage1->aData );
52135 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
52136 assert( pBt->pPage1->aData );
52137 releasePage(pBt->pPage1);
52138 pBt->pPage1 = 0;
52143 ** If pBt points to an empty file then convert that empty file
52144 ** into a new empty database by initializing the first page of
52145 ** the database.
52147 static int newDatabase(BtShared *pBt){
52148 MemPage *pP1;
52149 unsigned char *data;
52150 int rc;
52152 assert( sqlite3_mutex_held(pBt->mutex) );
52153 if( pBt->nPage>0 ){
52154 return SQLITE_OK;
52156 pP1 = pBt->pPage1;
52157 assert( pP1!=0 );
52158 data = pP1->aData;
52159 rc = sqlite3PagerWrite(pP1->pDbPage);
52160 if( rc ) return rc;
52161 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
52162 assert( sizeof(zMagicHeader)==16 );
52163 data[16] = (u8)((pBt->pageSize>>8)&0xff);
52164 data[17] = (u8)((pBt->pageSize>>16)&0xff);
52165 data[18] = 1;
52166 data[19] = 1;
52167 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
52168 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
52169 data[21] = 64;
52170 data[22] = 32;
52171 data[23] = 32;
52172 memset(&data[24], 0, 100-24);
52173 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
52174 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
52175 #ifndef SQLITE_OMIT_AUTOVACUUM
52176 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
52177 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
52178 put4byte(&data[36 + 4*4], pBt->autoVacuum);
52179 put4byte(&data[36 + 7*4], pBt->incrVacuum);
52180 #endif
52181 pBt->nPage = 1;
52182 data[31] = 1;
52183 return SQLITE_OK;
52187 ** Initialize the first page of the database file (creating a database
52188 ** consisting of a single page and no schema objects). Return SQLITE_OK
52189 ** if successful, or an SQLite error code otherwise.
52191 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
52192 int rc;
52193 sqlite3BtreeEnter(p);
52194 p->pBt->nPage = 0;
52195 rc = newDatabase(p->pBt);
52196 sqlite3BtreeLeave(p);
52197 return rc;
52201 ** Attempt to start a new transaction. A write-transaction
52202 ** is started if the second argument is nonzero, otherwise a read-
52203 ** transaction. If the second argument is 2 or more and exclusive
52204 ** transaction is started, meaning that no other process is allowed
52205 ** to access the database. A preexisting transaction may not be
52206 ** upgraded to exclusive by calling this routine a second time - the
52207 ** exclusivity flag only works for a new transaction.
52209 ** A write-transaction must be started before attempting any
52210 ** changes to the database. None of the following routines
52211 ** will work unless a transaction is started first:
52213 ** sqlite3BtreeCreateTable()
52214 ** sqlite3BtreeCreateIndex()
52215 ** sqlite3BtreeClearTable()
52216 ** sqlite3BtreeDropTable()
52217 ** sqlite3BtreeInsert()
52218 ** sqlite3BtreeDelete()
52219 ** sqlite3BtreeUpdateMeta()
52221 ** If an initial attempt to acquire the lock fails because of lock contention
52222 ** and the database was previously unlocked, then invoke the busy handler
52223 ** if there is one. But if there was previously a read-lock, do not
52224 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
52225 ** returned when there is already a read-lock in order to avoid a deadlock.
52227 ** Suppose there are two processes A and B. A has a read lock and B has
52228 ** a reserved lock. B tries to promote to exclusive but is blocked because
52229 ** of A's read lock. A tries to promote to reserved but is blocked by B.
52230 ** One or the other of the two processes must give way or there can be
52231 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
52232 ** when A already has a read lock, we encourage A to give up and let B
52233 ** proceed.
52235 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
52236 sqlite3 *pBlock = 0;
52237 BtShared *pBt = p->pBt;
52238 int rc = SQLITE_OK;
52240 sqlite3BtreeEnter(p);
52241 btreeIntegrity(p);
52243 /* If the btree is already in a write-transaction, or it
52244 ** is already in a read-transaction and a read-transaction
52245 ** is requested, this is a no-op.
52247 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
52248 goto trans_begun;
52250 assert( IfNotOmitAV(pBt->bDoTruncate)==0 );
52252 /* Write transactions are not possible on a read-only database */
52253 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
52254 rc = SQLITE_READONLY;
52255 goto trans_begun;
52258 #ifndef SQLITE_OMIT_SHARED_CACHE
52259 /* If another database handle has already opened a write transaction
52260 ** on this shared-btree structure and a second write transaction is
52261 ** requested, return SQLITE_LOCKED.
52263 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
52264 || (pBt->btsFlags & BTS_PENDING)!=0
52266 pBlock = pBt->pWriter->db;
52267 }else if( wrflag>1 ){
52268 BtLock *pIter;
52269 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52270 if( pIter->pBtree!=p ){
52271 pBlock = pIter->pBtree->db;
52272 break;
52276 if( pBlock ){
52277 sqlite3ConnectionBlocked(p->db, pBlock);
52278 rc = SQLITE_LOCKED_SHAREDCACHE;
52279 goto trans_begun;
52281 #endif
52283 /* Any read-only or read-write transaction implies a read-lock on
52284 ** page 1. So if some other shared-cache client already has a write-lock
52285 ** on page 1, the transaction cannot be opened. */
52286 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
52287 if( SQLITE_OK!=rc ) goto trans_begun;
52289 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
52290 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
52291 do {
52292 /* Call lockBtree() until either pBt->pPage1 is populated or
52293 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
52294 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
52295 ** reading page 1 it discovers that the page-size of the database
52296 ** file is not pBt->pageSize. In this case lockBtree() will update
52297 ** pBt->pageSize to the page-size of the file on disk.
52299 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
52301 if( rc==SQLITE_OK && wrflag ){
52302 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
52303 rc = SQLITE_READONLY;
52304 }else{
52305 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
52306 if( rc==SQLITE_OK ){
52307 rc = newDatabase(pBt);
52312 if( rc!=SQLITE_OK ){
52313 unlockBtreeIfUnused(pBt);
52315 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
52316 btreeInvokeBusyHandler(pBt) );
52318 if( rc==SQLITE_OK ){
52319 if( p->inTrans==TRANS_NONE ){
52320 pBt->nTransaction++;
52321 #ifndef SQLITE_OMIT_SHARED_CACHE
52322 if( p->sharable ){
52323 assert( p->lock.pBtree==p && p->lock.iTable==1 );
52324 p->lock.eLock = READ_LOCK;
52325 p->lock.pNext = pBt->pLock;
52326 pBt->pLock = &p->lock;
52328 #endif
52330 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
52331 if( p->inTrans>pBt->inTransaction ){
52332 pBt->inTransaction = p->inTrans;
52334 if( wrflag ){
52335 MemPage *pPage1 = pBt->pPage1;
52336 #ifndef SQLITE_OMIT_SHARED_CACHE
52337 assert( !pBt->pWriter );
52338 pBt->pWriter = p;
52339 pBt->btsFlags &= ~BTS_EXCLUSIVE;
52340 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
52341 #endif
52343 /* If the db-size header field is incorrect (as it may be if an old
52344 ** client has been writing the database file), update it now. Doing
52345 ** this sooner rather than later means the database size can safely
52346 ** re-read the database size from page 1 if a savepoint or transaction
52347 ** rollback occurs within the transaction.
52349 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
52350 rc = sqlite3PagerWrite(pPage1->pDbPage);
52351 if( rc==SQLITE_OK ){
52352 put4byte(&pPage1->aData[28], pBt->nPage);
52359 trans_begun:
52360 if( rc==SQLITE_OK && wrflag ){
52361 /* This call makes sure that the pager has the correct number of
52362 ** open savepoints. If the second parameter is greater than 0 and
52363 ** the sub-journal is not already open, then it will be opened here.
52365 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
52368 btreeIntegrity(p);
52369 sqlite3BtreeLeave(p);
52370 return rc;
52373 #ifndef SQLITE_OMIT_AUTOVACUUM
52376 ** Set the pointer-map entries for all children of page pPage. Also, if
52377 ** pPage contains cells that point to overflow pages, set the pointer
52378 ** map entries for the overflow pages as well.
52380 static int setChildPtrmaps(MemPage *pPage){
52381 int i; /* Counter variable */
52382 int nCell; /* Number of cells in page pPage */
52383 int rc; /* Return code */
52384 BtShared *pBt = pPage->pBt;
52385 u8 isInitOrig = pPage->isInit;
52386 Pgno pgno = pPage->pgno;
52388 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52389 rc = btreeInitPage(pPage);
52390 if( rc!=SQLITE_OK ){
52391 goto set_child_ptrmaps_out;
52393 nCell = pPage->nCell;
52395 for(i=0; i<nCell; i++){
52396 u8 *pCell = findCell(pPage, i);
52398 ptrmapPutOvflPtr(pPage, pCell, &rc);
52400 if( !pPage->leaf ){
52401 Pgno childPgno = get4byte(pCell);
52402 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52406 if( !pPage->leaf ){
52407 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52408 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52411 set_child_ptrmaps_out:
52412 pPage->isInit = isInitOrig;
52413 return rc;
52417 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
52418 ** that it points to iTo. Parameter eType describes the type of pointer to
52419 ** be modified, as follows:
52421 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
52422 ** page of pPage.
52424 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
52425 ** page pointed to by one of the cells on pPage.
52427 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
52428 ** overflow page in the list.
52430 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
52431 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52432 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52433 if( eType==PTRMAP_OVERFLOW2 ){
52434 /* The pointer is always the first 4 bytes of the page in this case. */
52435 if( get4byte(pPage->aData)!=iFrom ){
52436 return SQLITE_CORRUPT_BKPT;
52438 put4byte(pPage->aData, iTo);
52439 }else{
52440 u8 isInitOrig = pPage->isInit;
52441 int i;
52442 int nCell;
52444 btreeInitPage(pPage);
52445 nCell = pPage->nCell;
52447 for(i=0; i<nCell; i++){
52448 u8 *pCell = findCell(pPage, i);
52449 if( eType==PTRMAP_OVERFLOW1 ){
52450 CellInfo info;
52451 btreeParseCellPtr(pPage, pCell, &info);
52452 if( info.iOverflow
52453 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
52454 && iFrom==get4byte(&pCell[info.iOverflow])
52456 put4byte(&pCell[info.iOverflow], iTo);
52457 break;
52459 }else{
52460 if( get4byte(pCell)==iFrom ){
52461 put4byte(pCell, iTo);
52462 break;
52467 if( i==nCell ){
52468 if( eType!=PTRMAP_BTREE ||
52469 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
52470 return SQLITE_CORRUPT_BKPT;
52472 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
52475 pPage->isInit = isInitOrig;
52477 return SQLITE_OK;
52482 ** Move the open database page pDbPage to location iFreePage in the
52483 ** database. The pDbPage reference remains valid.
52485 ** The isCommit flag indicates that there is no need to remember that
52486 ** the journal needs to be sync()ed before database page pDbPage->pgno
52487 ** can be written to. The caller has already promised not to write to that
52488 ** page.
52490 static int relocatePage(
52491 BtShared *pBt, /* Btree */
52492 MemPage *pDbPage, /* Open page to move */
52493 u8 eType, /* Pointer map 'type' entry for pDbPage */
52494 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
52495 Pgno iFreePage, /* The location to move pDbPage to */
52496 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
52498 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
52499 Pgno iDbPage = pDbPage->pgno;
52500 Pager *pPager = pBt->pPager;
52501 int rc;
52503 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
52504 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
52505 assert( sqlite3_mutex_held(pBt->mutex) );
52506 assert( pDbPage->pBt==pBt );
52508 /* Move page iDbPage from its current location to page number iFreePage */
52509 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
52510 iDbPage, iFreePage, iPtrPage, eType));
52511 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
52512 if( rc!=SQLITE_OK ){
52513 return rc;
52515 pDbPage->pgno = iFreePage;
52517 /* If pDbPage was a btree-page, then it may have child pages and/or cells
52518 ** that point to overflow pages. The pointer map entries for all these
52519 ** pages need to be changed.
52521 ** If pDbPage is an overflow page, then the first 4 bytes may store a
52522 ** pointer to a subsequent overflow page. If this is the case, then
52523 ** the pointer map needs to be updated for the subsequent overflow page.
52525 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
52526 rc = setChildPtrmaps(pDbPage);
52527 if( rc!=SQLITE_OK ){
52528 return rc;
52530 }else{
52531 Pgno nextOvfl = get4byte(pDbPage->aData);
52532 if( nextOvfl!=0 ){
52533 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
52534 if( rc!=SQLITE_OK ){
52535 return rc;
52540 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
52541 ** that it points at iFreePage. Also fix the pointer map entry for
52542 ** iPtrPage.
52544 if( eType!=PTRMAP_ROOTPAGE ){
52545 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
52546 if( rc!=SQLITE_OK ){
52547 return rc;
52549 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
52550 if( rc!=SQLITE_OK ){
52551 releasePage(pPtrPage);
52552 return rc;
52554 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
52555 releasePage(pPtrPage);
52556 if( rc==SQLITE_OK ){
52557 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
52560 return rc;
52563 /* Forward declaration required by incrVacuumStep(). */
52564 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
52567 ** Perform a single step of an incremental-vacuum. If successful, return
52568 ** SQLITE_OK. If there is no work to do (and therefore no point in
52569 ** calling this function again), return SQLITE_DONE. Or, if an error
52570 ** occurs, return some other error code.
52572 ** More specificly, this function attempts to re-organize the database so
52573 ** that the last page of the file currently in use is no longer in use.
52575 ** Parameter nFin is the number of pages that this database would contain
52576 ** were this function called until it returns SQLITE_DONE.
52578 ** If the bCommit parameter is non-zero, this function assumes that the
52579 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
52580 ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
52581 ** operation, or false for an incremental vacuum.
52583 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
52584 Pgno nFreeList; /* Number of pages still on the free-list */
52585 int rc;
52587 assert( sqlite3_mutex_held(pBt->mutex) );
52588 assert( iLastPg>nFin );
52590 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
52591 u8 eType;
52592 Pgno iPtrPage;
52594 nFreeList = get4byte(&pBt->pPage1->aData[36]);
52595 if( nFreeList==0 ){
52596 return SQLITE_DONE;
52599 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
52600 if( rc!=SQLITE_OK ){
52601 return rc;
52603 if( eType==PTRMAP_ROOTPAGE ){
52604 return SQLITE_CORRUPT_BKPT;
52607 if( eType==PTRMAP_FREEPAGE ){
52608 if( bCommit==0 ){
52609 /* Remove the page from the files free-list. This is not required
52610 ** if bCommit is non-zero. In that case, the free-list will be
52611 ** truncated to zero after this function returns, so it doesn't
52612 ** matter if it still contains some garbage entries.
52614 Pgno iFreePg;
52615 MemPage *pFreePg;
52616 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
52617 if( rc!=SQLITE_OK ){
52618 return rc;
52620 assert( iFreePg==iLastPg );
52621 releasePage(pFreePg);
52623 } else {
52624 Pgno iFreePg; /* Index of free page to move pLastPg to */
52625 MemPage *pLastPg;
52626 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
52627 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
52629 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
52630 if( rc!=SQLITE_OK ){
52631 return rc;
52634 /* If bCommit is zero, this loop runs exactly once and page pLastPg
52635 ** is swapped with the first free page pulled off the free list.
52637 ** On the other hand, if bCommit is greater than zero, then keep
52638 ** looping until a free-page located within the first nFin pages
52639 ** of the file is found.
52641 if( bCommit==0 ){
52642 eMode = BTALLOC_LE;
52643 iNear = nFin;
52645 do {
52646 MemPage *pFreePg;
52647 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
52648 if( rc!=SQLITE_OK ){
52649 releasePage(pLastPg);
52650 return rc;
52652 releasePage(pFreePg);
52653 }while( bCommit && iFreePg>nFin );
52654 assert( iFreePg<iLastPg );
52656 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
52657 releasePage(pLastPg);
52658 if( rc!=SQLITE_OK ){
52659 return rc;
52664 if( bCommit==0 ){
52665 do {
52666 iLastPg--;
52667 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
52668 pBt->bDoTruncate = 1;
52669 pBt->nPage = iLastPg;
52671 return SQLITE_OK;
52675 ** The database opened by the first argument is an auto-vacuum database
52676 ** nOrig pages in size containing nFree free pages. Return the expected
52677 ** size of the database in pages following an auto-vacuum operation.
52679 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
52680 int nEntry; /* Number of entries on one ptrmap page */
52681 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
52682 Pgno nFin; /* Return value */
52684 nEntry = pBt->usableSize/5;
52685 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
52686 nFin = nOrig - nFree - nPtrmap;
52687 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
52688 nFin--;
52690 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
52691 nFin--;
52694 return nFin;
52698 ** A write-transaction must be opened before calling this function.
52699 ** It performs a single unit of work towards an incremental vacuum.
52701 ** If the incremental vacuum is finished after this function has run,
52702 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
52703 ** SQLITE_OK is returned. Otherwise an SQLite error code.
52705 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
52706 int rc;
52707 BtShared *pBt = p->pBt;
52709 sqlite3BtreeEnter(p);
52710 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
52711 if( !pBt->autoVacuum ){
52712 rc = SQLITE_DONE;
52713 }else{
52714 Pgno nOrig = btreePagecount(pBt);
52715 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
52716 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
52718 if( nOrig<nFin ){
52719 rc = SQLITE_CORRUPT_BKPT;
52720 }else if( nFree>0 ){
52721 rc = saveAllCursors(pBt, 0, 0);
52722 if( rc==SQLITE_OK ){
52723 invalidateAllOverflowCache(pBt);
52724 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
52726 if( rc==SQLITE_OK ){
52727 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52728 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
52730 }else{
52731 rc = SQLITE_DONE;
52734 sqlite3BtreeLeave(p);
52735 return rc;
52739 ** This routine is called prior to sqlite3PagerCommit when a transaction
52740 ** is committed for an auto-vacuum database.
52742 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
52743 ** the database file should be truncated to during the commit process.
52744 ** i.e. the database has been reorganized so that only the first *pnTrunc
52745 ** pages are in use.
52747 static int autoVacuumCommit(BtShared *pBt){
52748 int rc = SQLITE_OK;
52749 Pager *pPager = pBt->pPager;
52750 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
52752 assert( sqlite3_mutex_held(pBt->mutex) );
52753 invalidateAllOverflowCache(pBt);
52754 assert(pBt->autoVacuum);
52755 if( !pBt->incrVacuum ){
52756 Pgno nFin; /* Number of pages in database after autovacuuming */
52757 Pgno nFree; /* Number of pages on the freelist initially */
52758 Pgno iFree; /* The next page to be freed */
52759 Pgno nOrig; /* Database size before freeing */
52761 nOrig = btreePagecount(pBt);
52762 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
52763 /* It is not possible to create a database for which the final page
52764 ** is either a pointer-map page or the pending-byte page. If one
52765 ** is encountered, this indicates corruption.
52767 return SQLITE_CORRUPT_BKPT;
52770 nFree = get4byte(&pBt->pPage1->aData[36]);
52771 nFin = finalDbSize(pBt, nOrig, nFree);
52772 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
52773 if( nFin<nOrig ){
52774 rc = saveAllCursors(pBt, 0, 0);
52776 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
52777 rc = incrVacuumStep(pBt, nFin, iFree, 1);
52779 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
52780 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52781 put4byte(&pBt->pPage1->aData[32], 0);
52782 put4byte(&pBt->pPage1->aData[36], 0);
52783 put4byte(&pBt->pPage1->aData[28], nFin);
52784 pBt->bDoTruncate = 1;
52785 pBt->nPage = nFin;
52787 if( rc!=SQLITE_OK ){
52788 sqlite3PagerRollback(pPager);
52792 assert( nRef>=sqlite3PagerRefcount(pPager) );
52793 return rc;
52796 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
52797 # define setChildPtrmaps(x) SQLITE_OK
52798 #endif
52801 ** This routine does the first phase of a two-phase commit. This routine
52802 ** causes a rollback journal to be created (if it does not already exist)
52803 ** and populated with enough information so that if a power loss occurs
52804 ** the database can be restored to its original state by playing back
52805 ** the journal. Then the contents of the journal are flushed out to
52806 ** the disk. After the journal is safely on oxide, the changes to the
52807 ** database are written into the database file and flushed to oxide.
52808 ** At the end of this call, the rollback journal still exists on the
52809 ** disk and we are still holding all locks, so the transaction has not
52810 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
52811 ** commit process.
52813 ** This call is a no-op if no write-transaction is currently active on pBt.
52815 ** Otherwise, sync the database file for the btree pBt. zMaster points to
52816 ** the name of a master journal file that should be written into the
52817 ** individual journal file, or is NULL, indicating no master journal file
52818 ** (single database transaction).
52820 ** When this is called, the master journal should already have been
52821 ** created, populated with this journal pointer and synced to disk.
52823 ** Once this is routine has returned, the only thing required to commit
52824 ** the write-transaction for this database file is to delete the journal.
52826 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
52827 int rc = SQLITE_OK;
52828 if( p->inTrans==TRANS_WRITE ){
52829 BtShared *pBt = p->pBt;
52830 sqlite3BtreeEnter(p);
52831 #ifndef SQLITE_OMIT_AUTOVACUUM
52832 if( pBt->autoVacuum ){
52833 rc = autoVacuumCommit(pBt);
52834 if( rc!=SQLITE_OK ){
52835 sqlite3BtreeLeave(p);
52836 return rc;
52839 if( pBt->bDoTruncate ){
52840 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
52842 #endif
52843 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
52844 sqlite3BtreeLeave(p);
52846 return rc;
52850 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
52851 ** at the conclusion of a transaction.
52853 static void btreeEndTransaction(Btree *p){
52854 BtShared *pBt = p->pBt;
52855 sqlite3 *db = p->db;
52856 assert( sqlite3BtreeHoldsMutex(p) );
52858 #ifndef SQLITE_OMIT_AUTOVACUUM
52859 pBt->bDoTruncate = 0;
52860 #endif
52861 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
52862 /* If there are other active statements that belong to this database
52863 ** handle, downgrade to a read-only transaction. The other statements
52864 ** may still be reading from the database. */
52865 downgradeAllSharedCacheTableLocks(p);
52866 p->inTrans = TRANS_READ;
52867 }else{
52868 /* If the handle had any kind of transaction open, decrement the
52869 ** transaction count of the shared btree. If the transaction count
52870 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
52871 ** call below will unlock the pager. */
52872 if( p->inTrans!=TRANS_NONE ){
52873 clearAllSharedCacheTableLocks(p);
52874 pBt->nTransaction--;
52875 if( 0==pBt->nTransaction ){
52876 pBt->inTransaction = TRANS_NONE;
52880 /* Set the current transaction state to TRANS_NONE and unlock the
52881 ** pager if this call closed the only read or write transaction. */
52882 p->inTrans = TRANS_NONE;
52883 unlockBtreeIfUnused(pBt);
52886 btreeIntegrity(p);
52890 ** Commit the transaction currently in progress.
52892 ** This routine implements the second phase of a 2-phase commit. The
52893 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
52894 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
52895 ** routine did all the work of writing information out to disk and flushing the
52896 ** contents so that they are written onto the disk platter. All this
52897 ** routine has to do is delete or truncate or zero the header in the
52898 ** the rollback journal (which causes the transaction to commit) and
52899 ** drop locks.
52901 ** Normally, if an error occurs while the pager layer is attempting to
52902 ** finalize the underlying journal file, this function returns an error and
52903 ** the upper layer will attempt a rollback. However, if the second argument
52904 ** is non-zero then this b-tree transaction is part of a multi-file
52905 ** transaction. In this case, the transaction has already been committed
52906 ** (by deleting a master journal file) and the caller will ignore this
52907 ** functions return code. So, even if an error occurs in the pager layer,
52908 ** reset the b-tree objects internal state to indicate that the write
52909 ** transaction has been closed. This is quite safe, as the pager will have
52910 ** transitioned to the error state.
52912 ** This will release the write lock on the database file. If there
52913 ** are no active cursors, it also releases the read lock.
52915 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
52917 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
52918 sqlite3BtreeEnter(p);
52919 btreeIntegrity(p);
52921 /* If the handle has a write-transaction open, commit the shared-btrees
52922 ** transaction and set the shared state to TRANS_READ.
52924 if( p->inTrans==TRANS_WRITE ){
52925 int rc;
52926 BtShared *pBt = p->pBt;
52927 assert( pBt->inTransaction==TRANS_WRITE );
52928 assert( pBt->nTransaction>0 );
52929 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
52930 if( rc!=SQLITE_OK && bCleanup==0 ){
52931 sqlite3BtreeLeave(p);
52932 return rc;
52934 pBt->inTransaction = TRANS_READ;
52935 btreeClearHasContent(pBt);
52938 btreeEndTransaction(p);
52939 sqlite3BtreeLeave(p);
52940 return SQLITE_OK;
52944 ** Do both phases of a commit.
52946 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
52947 int rc;
52948 sqlite3BtreeEnter(p);
52949 rc = sqlite3BtreeCommitPhaseOne(p, 0);
52950 if( rc==SQLITE_OK ){
52951 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
52953 sqlite3BtreeLeave(p);
52954 return rc;
52958 ** This routine sets the state to CURSOR_FAULT and the error
52959 ** code to errCode for every cursor on BtShared that pBtree
52960 ** references.
52962 ** Every cursor is tripped, including cursors that belong
52963 ** to other database connections that happen to be sharing
52964 ** the cache with pBtree.
52966 ** This routine gets called when a rollback occurs.
52967 ** All cursors using the same cache must be tripped
52968 ** to prevent them from trying to use the btree after
52969 ** the rollback. The rollback may have deleted tables
52970 ** or moved root pages, so it is not sufficient to
52971 ** save the state of the cursor. The cursor must be
52972 ** invalidated.
52974 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
52975 BtCursor *p;
52976 if( pBtree==0 ) return;
52977 sqlite3BtreeEnter(pBtree);
52978 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
52979 int i;
52980 sqlite3BtreeClearCursor(p);
52981 p->eState = CURSOR_FAULT;
52982 p->skipNext = errCode;
52983 for(i=0; i<=p->iPage; i++){
52984 releasePage(p->apPage[i]);
52985 p->apPage[i] = 0;
52988 sqlite3BtreeLeave(pBtree);
52992 ** Rollback the transaction in progress. All cursors will be
52993 ** invalided by this operation. Any attempt to use a cursor
52994 ** that was open at the beginning of this operation will result
52995 ** in an error.
52997 ** This will release the write lock on the database file. If there
52998 ** are no active cursors, it also releases the read lock.
53000 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
53001 int rc;
53002 BtShared *pBt = p->pBt;
53003 MemPage *pPage1;
53005 sqlite3BtreeEnter(p);
53006 if( tripCode==SQLITE_OK ){
53007 rc = tripCode = saveAllCursors(pBt, 0, 0);
53008 }else{
53009 rc = SQLITE_OK;
53011 if( tripCode ){
53012 sqlite3BtreeTripAllCursors(p, tripCode);
53014 btreeIntegrity(p);
53016 if( p->inTrans==TRANS_WRITE ){
53017 int rc2;
53019 assert( TRANS_WRITE==pBt->inTransaction );
53020 rc2 = sqlite3PagerRollback(pBt->pPager);
53021 if( rc2!=SQLITE_OK ){
53022 rc = rc2;
53025 /* The rollback may have destroyed the pPage1->aData value. So
53026 ** call btreeGetPage() on page 1 again to make
53027 ** sure pPage1->aData is set correctly. */
53028 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
53029 int nPage = get4byte(28+(u8*)pPage1->aData);
53030 testcase( nPage==0 );
53031 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
53032 testcase( pBt->nPage!=nPage );
53033 pBt->nPage = nPage;
53034 releasePage(pPage1);
53036 assert( countValidCursors(pBt, 1)==0 );
53037 pBt->inTransaction = TRANS_READ;
53038 btreeClearHasContent(pBt);
53041 btreeEndTransaction(p);
53042 sqlite3BtreeLeave(p);
53043 return rc;
53047 ** Start a statement subtransaction. The subtransaction can can be rolled
53048 ** back independently of the main transaction. You must start a transaction
53049 ** before starting a subtransaction. The subtransaction is ended automatically
53050 ** if the main transaction commits or rolls back.
53052 ** Statement subtransactions are used around individual SQL statements
53053 ** that are contained within a BEGIN...COMMIT block. If a constraint
53054 ** error occurs within the statement, the effect of that one statement
53055 ** can be rolled back without having to rollback the entire transaction.
53057 ** A statement sub-transaction is implemented as an anonymous savepoint. The
53058 ** value passed as the second parameter is the total number of savepoints,
53059 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
53060 ** are no active savepoints and no other statement-transactions open,
53061 ** iStatement is 1. This anonymous savepoint can be released or rolled back
53062 ** using the sqlite3BtreeSavepoint() function.
53064 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
53065 int rc;
53066 BtShared *pBt = p->pBt;
53067 sqlite3BtreeEnter(p);
53068 assert( p->inTrans==TRANS_WRITE );
53069 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
53070 assert( iStatement>0 );
53071 assert( iStatement>p->db->nSavepoint );
53072 assert( pBt->inTransaction==TRANS_WRITE );
53073 /* At the pager level, a statement transaction is a savepoint with
53074 ** an index greater than all savepoints created explicitly using
53075 ** SQL statements. It is illegal to open, release or rollback any
53076 ** such savepoints while the statement transaction savepoint is active.
53078 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
53079 sqlite3BtreeLeave(p);
53080 return rc;
53084 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
53085 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
53086 ** savepoint identified by parameter iSavepoint, depending on the value
53087 ** of op.
53089 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
53090 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
53091 ** contents of the entire transaction are rolled back. This is different
53092 ** from a normal transaction rollback, as no locks are released and the
53093 ** transaction remains open.
53095 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
53096 int rc = SQLITE_OK;
53097 if( p && p->inTrans==TRANS_WRITE ){
53098 BtShared *pBt = p->pBt;
53099 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
53100 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
53101 sqlite3BtreeEnter(p);
53102 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
53103 if( rc==SQLITE_OK ){
53104 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
53105 pBt->nPage = 0;
53107 rc = newDatabase(pBt);
53108 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
53110 /* The database size was written into the offset 28 of the header
53111 ** when the transaction started, so we know that the value at offset
53112 ** 28 is nonzero. */
53113 assert( pBt->nPage>0 );
53115 sqlite3BtreeLeave(p);
53117 return rc;
53121 ** Create a new cursor for the BTree whose root is on the page
53122 ** iTable. If a read-only cursor is requested, it is assumed that
53123 ** the caller already has at least a read-only transaction open
53124 ** on the database already. If a write-cursor is requested, then
53125 ** the caller is assumed to have an open write transaction.
53127 ** If wrFlag==0, then the cursor can only be used for reading.
53128 ** If wrFlag==1, then the cursor can be used for reading or for
53129 ** writing if other conditions for writing are also met. These
53130 ** are the conditions that must be met in order for writing to
53131 ** be allowed:
53133 ** 1: The cursor must have been opened with wrFlag==1
53135 ** 2: Other database connections that share the same pager cache
53136 ** but which are not in the READ_UNCOMMITTED state may not have
53137 ** cursors open with wrFlag==0 on the same table. Otherwise
53138 ** the changes made by this write cursor would be visible to
53139 ** the read cursors in the other database connection.
53141 ** 3: The database must be writable (not on read-only media)
53143 ** 4: There must be an active transaction.
53145 ** No checking is done to make sure that page iTable really is the
53146 ** root page of a b-tree. If it is not, then the cursor acquired
53147 ** will not work correctly.
53149 ** It is assumed that the sqlite3BtreeCursorZero() has been called
53150 ** on pCur to initialize the memory space prior to invoking this routine.
53152 static int btreeCursor(
53153 Btree *p, /* The btree */
53154 int iTable, /* Root page of table to open */
53155 int wrFlag, /* 1 to write. 0 read-only */
53156 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
53157 BtCursor *pCur /* Space for new cursor */
53159 BtShared *pBt = p->pBt; /* Shared b-tree handle */
53161 assert( sqlite3BtreeHoldsMutex(p) );
53162 assert( wrFlag==0 || wrFlag==1 );
53164 /* The following assert statements verify that if this is a sharable
53165 ** b-tree database, the connection is holding the required table locks,
53166 ** and that no other connection has any open cursor that conflicts with
53167 ** this lock. */
53168 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
53169 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
53171 /* Assert that the caller has opened the required transaction. */
53172 assert( p->inTrans>TRANS_NONE );
53173 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
53174 assert( pBt->pPage1 && pBt->pPage1->aData );
53176 if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
53177 return SQLITE_READONLY;
53179 if( iTable==1 && btreePagecount(pBt)==0 ){
53180 assert( wrFlag==0 );
53181 iTable = 0;
53184 /* Now that no other errors can occur, finish filling in the BtCursor
53185 ** variables and link the cursor into the BtShared list. */
53186 pCur->pgnoRoot = (Pgno)iTable;
53187 pCur->iPage = -1;
53188 pCur->pKeyInfo = pKeyInfo;
53189 pCur->pBtree = p;
53190 pCur->pBt = pBt;
53191 pCur->wrFlag = (u8)wrFlag;
53192 pCur->pNext = pBt->pCursor;
53193 if( pCur->pNext ){
53194 pCur->pNext->pPrev = pCur;
53196 pBt->pCursor = pCur;
53197 pCur->eState = CURSOR_INVALID;
53198 pCur->cachedRowid = 0;
53199 return SQLITE_OK;
53201 SQLITE_PRIVATE int sqlite3BtreeCursor(
53202 Btree *p, /* The btree */
53203 int iTable, /* Root page of table to open */
53204 int wrFlag, /* 1 to write. 0 read-only */
53205 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
53206 BtCursor *pCur /* Write new cursor here */
53208 int rc;
53209 sqlite3BtreeEnter(p);
53210 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
53211 sqlite3BtreeLeave(p);
53212 return rc;
53216 ** Return the size of a BtCursor object in bytes.
53218 ** This interfaces is needed so that users of cursors can preallocate
53219 ** sufficient storage to hold a cursor. The BtCursor object is opaque
53220 ** to users so they cannot do the sizeof() themselves - they must call
53221 ** this routine.
53223 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
53224 return ROUND8(sizeof(BtCursor));
53228 ** Initialize memory that will be converted into a BtCursor object.
53230 ** The simple approach here would be to memset() the entire object
53231 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
53232 ** do not need to be zeroed and they are large, so we can save a lot
53233 ** of run-time by skipping the initialization of those elements.
53235 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
53236 memset(p, 0, offsetof(BtCursor, iPage));
53240 ** Set the cached rowid value of every cursor in the same database file
53241 ** as pCur and having the same root page number as pCur. The value is
53242 ** set to iRowid.
53244 ** Only positive rowid values are considered valid for this cache.
53245 ** The cache is initialized to zero, indicating an invalid cache.
53246 ** A btree will work fine with zero or negative rowids. We just cannot
53247 ** cache zero or negative rowids, which means tables that use zero or
53248 ** negative rowids might run a little slower. But in practice, zero
53249 ** or negative rowids are very uncommon so this should not be a problem.
53251 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
53252 BtCursor *p;
53253 for(p=pCur->pBt->pCursor; p; p=p->pNext){
53254 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
53256 assert( pCur->cachedRowid==iRowid );
53260 ** Return the cached rowid for the given cursor. A negative or zero
53261 ** return value indicates that the rowid cache is invalid and should be
53262 ** ignored. If the rowid cache has never before been set, then a
53263 ** zero is returned.
53265 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
53266 return pCur->cachedRowid;
53270 ** Close a cursor. The read lock on the database file is released
53271 ** when the last cursor is closed.
53273 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
53274 Btree *pBtree = pCur->pBtree;
53275 if( pBtree ){
53276 int i;
53277 BtShared *pBt = pCur->pBt;
53278 sqlite3BtreeEnter(pBtree);
53279 sqlite3BtreeClearCursor(pCur);
53280 if( pCur->pPrev ){
53281 pCur->pPrev->pNext = pCur->pNext;
53282 }else{
53283 pBt->pCursor = pCur->pNext;
53285 if( pCur->pNext ){
53286 pCur->pNext->pPrev = pCur->pPrev;
53288 for(i=0; i<=pCur->iPage; i++){
53289 releasePage(pCur->apPage[i]);
53291 unlockBtreeIfUnused(pBt);
53292 invalidateOverflowCache(pCur);
53293 /* sqlite3_free(pCur); */
53294 sqlite3BtreeLeave(pBtree);
53296 return SQLITE_OK;
53300 ** Make sure the BtCursor* given in the argument has a valid
53301 ** BtCursor.info structure. If it is not already valid, call
53302 ** btreeParseCell() to fill it in.
53304 ** BtCursor.info is a cache of the information in the current cell.
53305 ** Using this cache reduces the number of calls to btreeParseCell().
53307 ** 2007-06-25: There is a bug in some versions of MSVC that cause the
53308 ** compiler to crash when getCellInfo() is implemented as a macro.
53309 ** But there is a measureable speed advantage to using the macro on gcc
53310 ** (when less compiler optimizations like -Os or -O0 are used and the
53311 ** compiler is not doing agressive inlining.) So we use a real function
53312 ** for MSVC and a macro for everything else. Ticket #2457.
53314 #ifndef NDEBUG
53315 static void assertCellInfo(BtCursor *pCur){
53316 CellInfo info;
53317 int iPage = pCur->iPage;
53318 memset(&info, 0, sizeof(info));
53319 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
53320 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
53322 #else
53323 #define assertCellInfo(x)
53324 #endif
53325 #ifdef _MSC_VER
53326 /* Use a real function in MSVC to work around bugs in that compiler. */
53327 static void getCellInfo(BtCursor *pCur){
53328 if( pCur->info.nSize==0 ){
53329 int iPage = pCur->iPage;
53330 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
53331 pCur->validNKey = 1;
53332 }else{
53333 assertCellInfo(pCur);
53336 #else /* if not _MSC_VER */
53337 /* Use a macro in all other compilers so that the function is inlined */
53338 #define getCellInfo(pCur) \
53339 if( pCur->info.nSize==0 ){ \
53340 int iPage = pCur->iPage; \
53341 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
53342 pCur->validNKey = 1; \
53343 }else{ \
53344 assertCellInfo(pCur); \
53346 #endif /* _MSC_VER */
53348 #ifndef NDEBUG /* The next routine used only within assert() statements */
53350 ** Return true if the given BtCursor is valid. A valid cursor is one
53351 ** that is currently pointing to a row in a (non-empty) table.
53352 ** This is a verification routine is used only within assert() statements.
53354 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
53355 return pCur && pCur->eState==CURSOR_VALID;
53357 #endif /* NDEBUG */
53360 ** Set *pSize to the size of the buffer needed to hold the value of
53361 ** the key for the current entry. If the cursor is not pointing
53362 ** to a valid entry, *pSize is set to 0.
53364 ** For a table with the INTKEY flag set, this routine returns the key
53365 ** itself, not the number of bytes in the key.
53367 ** The caller must position the cursor prior to invoking this routine.
53369 ** This routine cannot fail. It always returns SQLITE_OK.
53371 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
53372 assert( cursorHoldsMutex(pCur) );
53373 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
53374 if( pCur->eState!=CURSOR_VALID ){
53375 *pSize = 0;
53376 }else{
53377 getCellInfo(pCur);
53378 *pSize = pCur->info.nKey;
53380 return SQLITE_OK;
53384 ** Set *pSize to the number of bytes of data in the entry the
53385 ** cursor currently points to.
53387 ** The caller must guarantee that the cursor is pointing to a non-NULL
53388 ** valid entry. In other words, the calling procedure must guarantee
53389 ** that the cursor has Cursor.eState==CURSOR_VALID.
53391 ** Failure is not possible. This function always returns SQLITE_OK.
53392 ** It might just as well be a procedure (returning void) but we continue
53393 ** to return an integer result code for historical reasons.
53395 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
53396 assert( cursorHoldsMutex(pCur) );
53397 assert( pCur->eState==CURSOR_VALID );
53398 getCellInfo(pCur);
53399 *pSize = pCur->info.nData;
53400 return SQLITE_OK;
53404 ** Given the page number of an overflow page in the database (parameter
53405 ** ovfl), this function finds the page number of the next page in the
53406 ** linked list of overflow pages. If possible, it uses the auto-vacuum
53407 ** pointer-map data instead of reading the content of page ovfl to do so.
53409 ** If an error occurs an SQLite error code is returned. Otherwise:
53411 ** The page number of the next overflow page in the linked list is
53412 ** written to *pPgnoNext. If page ovfl is the last page in its linked
53413 ** list, *pPgnoNext is set to zero.
53415 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
53416 ** to page number pOvfl was obtained, then *ppPage is set to point to that
53417 ** reference. It is the responsibility of the caller to call releasePage()
53418 ** on *ppPage to free the reference. In no reference was obtained (because
53419 ** the pointer-map was used to obtain the value for *pPgnoNext), then
53420 ** *ppPage is set to zero.
53422 static int getOverflowPage(
53423 BtShared *pBt, /* The database file */
53424 Pgno ovfl, /* Current overflow page number */
53425 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
53426 Pgno *pPgnoNext /* OUT: Next overflow page number */
53428 Pgno next = 0;
53429 MemPage *pPage = 0;
53430 int rc = SQLITE_OK;
53432 assert( sqlite3_mutex_held(pBt->mutex) );
53433 assert(pPgnoNext);
53435 #ifndef SQLITE_OMIT_AUTOVACUUM
53436 /* Try to find the next page in the overflow list using the
53437 ** autovacuum pointer-map pages. Guess that the next page in
53438 ** the overflow list is page number (ovfl+1). If that guess turns
53439 ** out to be wrong, fall back to loading the data of page
53440 ** number ovfl to determine the next page number.
53442 if( pBt->autoVacuum ){
53443 Pgno pgno;
53444 Pgno iGuess = ovfl+1;
53445 u8 eType;
53447 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
53448 iGuess++;
53451 if( iGuess<=btreePagecount(pBt) ){
53452 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
53453 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
53454 next = iGuess;
53455 rc = SQLITE_DONE;
53459 #endif
53461 assert( next==0 || rc==SQLITE_DONE );
53462 if( rc==SQLITE_OK ){
53463 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
53464 assert( rc==SQLITE_OK || pPage==0 );
53465 if( rc==SQLITE_OK ){
53466 next = get4byte(pPage->aData);
53470 *pPgnoNext = next;
53471 if( ppPage ){
53472 *ppPage = pPage;
53473 }else{
53474 releasePage(pPage);
53476 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
53480 ** Copy data from a buffer to a page, or from a page to a buffer.
53482 ** pPayload is a pointer to data stored on database page pDbPage.
53483 ** If argument eOp is false, then nByte bytes of data are copied
53484 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
53485 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
53486 ** of data are copied from the buffer pBuf to pPayload.
53488 ** SQLITE_OK is returned on success, otherwise an error code.
53490 static int copyPayload(
53491 void *pPayload, /* Pointer to page data */
53492 void *pBuf, /* Pointer to buffer */
53493 int nByte, /* Number of bytes to copy */
53494 int eOp, /* 0 -> copy from page, 1 -> copy to page */
53495 DbPage *pDbPage /* Page containing pPayload */
53497 if( eOp ){
53498 /* Copy data from buffer to page (a write operation) */
53499 int rc = sqlite3PagerWrite(pDbPage);
53500 if( rc!=SQLITE_OK ){
53501 return rc;
53503 memcpy(pPayload, pBuf, nByte);
53504 }else{
53505 /* Copy data from page to buffer (a read operation) */
53506 memcpy(pBuf, pPayload, nByte);
53508 return SQLITE_OK;
53512 ** This function is used to read or overwrite payload information
53513 ** for the entry that the pCur cursor is pointing to. If the eOp
53514 ** parameter is 0, this is a read operation (data copied into
53515 ** buffer pBuf). If it is non-zero, a write (data copied from
53516 ** buffer pBuf).
53518 ** A total of "amt" bytes are read or written beginning at "offset".
53519 ** Data is read to or from the buffer pBuf.
53521 ** The content being read or written might appear on the main page
53522 ** or be scattered out on multiple overflow pages.
53524 ** If the BtCursor.isIncrblobHandle flag is set, and the current
53525 ** cursor entry uses one or more overflow pages, this function
53526 ** allocates space for and lazily popluates the overflow page-list
53527 ** cache array (BtCursor.aOverflow). Subsequent calls use this
53528 ** cache to make seeking to the supplied offset more efficient.
53530 ** Once an overflow page-list cache has been allocated, it may be
53531 ** invalidated if some other cursor writes to the same table, or if
53532 ** the cursor is moved to a different row. Additionally, in auto-vacuum
53533 ** mode, the following events may invalidate an overflow page-list cache.
53535 ** * An incremental vacuum,
53536 ** * A commit in auto_vacuum="full" mode,
53537 ** * Creating a table (may require moving an overflow page).
53539 static int accessPayload(
53540 BtCursor *pCur, /* Cursor pointing to entry to read from */
53541 u32 offset, /* Begin reading this far into payload */
53542 u32 amt, /* Read this many bytes */
53543 unsigned char *pBuf, /* Write the bytes into this buffer */
53544 int eOp /* zero to read. non-zero to write. */
53546 unsigned char *aPayload;
53547 int rc = SQLITE_OK;
53548 u32 nKey;
53549 int iIdx = 0;
53550 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
53551 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
53553 assert( pPage );
53554 assert( pCur->eState==CURSOR_VALID );
53555 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53556 assert( cursorHoldsMutex(pCur) );
53558 getCellInfo(pCur);
53559 aPayload = pCur->info.pCell + pCur->info.nHeader;
53560 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
53562 if( NEVER(offset+amt > nKey+pCur->info.nData)
53563 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
53565 /* Trying to read or write past the end of the data is an error */
53566 return SQLITE_CORRUPT_BKPT;
53569 /* Check if data must be read/written to/from the btree page itself. */
53570 if( offset<pCur->info.nLocal ){
53571 int a = amt;
53572 if( a+offset>pCur->info.nLocal ){
53573 a = pCur->info.nLocal - offset;
53575 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
53576 offset = 0;
53577 pBuf += a;
53578 amt -= a;
53579 }else{
53580 offset -= pCur->info.nLocal;
53583 if( rc==SQLITE_OK && amt>0 ){
53584 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
53585 Pgno nextPage;
53587 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
53589 #ifndef SQLITE_OMIT_INCRBLOB
53590 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
53591 ** has not been allocated, allocate it now. The array is sized at
53592 ** one entry for each overflow page in the overflow chain. The
53593 ** page number of the first overflow page is stored in aOverflow[0],
53594 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
53595 ** (the cache is lazily populated).
53597 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
53598 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
53599 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
53600 /* nOvfl is always positive. If it were zero, fetchPayload would have
53601 ** been used instead of this routine. */
53602 if( ALWAYS(nOvfl) && !pCur->aOverflow ){
53603 rc = SQLITE_NOMEM;
53607 /* If the overflow page-list cache has been allocated and the
53608 ** entry for the first required overflow page is valid, skip
53609 ** directly to it.
53611 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
53612 iIdx = (offset/ovflSize);
53613 nextPage = pCur->aOverflow[iIdx];
53614 offset = (offset%ovflSize);
53616 #endif
53618 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
53620 #ifndef SQLITE_OMIT_INCRBLOB
53621 /* If required, populate the overflow page-list cache. */
53622 if( pCur->aOverflow ){
53623 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
53624 pCur->aOverflow[iIdx] = nextPage;
53626 #endif
53628 if( offset>=ovflSize ){
53629 /* The only reason to read this page is to obtain the page
53630 ** number for the next page in the overflow chain. The page
53631 ** data is not required. So first try to lookup the overflow
53632 ** page-list cache, if any, then fall back to the getOverflowPage()
53633 ** function.
53635 #ifndef SQLITE_OMIT_INCRBLOB
53636 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
53637 nextPage = pCur->aOverflow[iIdx+1];
53638 } else
53639 #endif
53640 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
53641 offset -= ovflSize;
53642 }else{
53643 /* Need to read this page properly. It contains some of the
53644 ** range of data that is being read (eOp==0) or written (eOp!=0).
53646 #ifdef SQLITE_DIRECT_OVERFLOW_READ
53647 sqlite3_file *fd;
53648 #endif
53649 int a = amt;
53650 if( a + offset > ovflSize ){
53651 a = ovflSize - offset;
53654 #ifdef SQLITE_DIRECT_OVERFLOW_READ
53655 /* If all the following are true:
53657 ** 1) this is a read operation, and
53658 ** 2) data is required from the start of this overflow page, and
53659 ** 3) the database is file-backed, and
53660 ** 4) there is no open write-transaction, and
53661 ** 5) the database is not a WAL database,
53663 ** then data can be read directly from the database file into the
53664 ** output buffer, bypassing the page-cache altogether. This speeds
53665 ** up loading large records that span many overflow pages.
53667 if( eOp==0 /* (1) */
53668 && offset==0 /* (2) */
53669 && pBt->inTransaction==TRANS_READ /* (4) */
53670 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
53671 && pBt->pPage1->aData[19]==0x01 /* (5) */
53673 u8 aSave[4];
53674 u8 *aWrite = &pBuf[-4];
53675 memcpy(aSave, aWrite, 4);
53676 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
53677 nextPage = get4byte(aWrite);
53678 memcpy(aWrite, aSave, 4);
53679 }else
53680 #endif
53683 DbPage *pDbPage;
53684 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
53685 (eOp==0 ? PAGER_GET_READONLY : 0)
53687 if( rc==SQLITE_OK ){
53688 aPayload = sqlite3PagerGetData(pDbPage);
53689 nextPage = get4byte(aPayload);
53690 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
53691 sqlite3PagerUnref(pDbPage);
53692 offset = 0;
53695 amt -= a;
53696 pBuf += a;
53701 if( rc==SQLITE_OK && amt>0 ){
53702 return SQLITE_CORRUPT_BKPT;
53704 return rc;
53708 ** Read part of the key associated with cursor pCur. Exactly
53709 ** "amt" bytes will be transfered into pBuf[]. The transfer
53710 ** begins at "offset".
53712 ** The caller must ensure that pCur is pointing to a valid row
53713 ** in the table.
53715 ** Return SQLITE_OK on success or an error code if anything goes
53716 ** wrong. An error is returned if "offset+amt" is larger than
53717 ** the available payload.
53719 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53720 assert( cursorHoldsMutex(pCur) );
53721 assert( pCur->eState==CURSOR_VALID );
53722 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53723 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53724 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
53728 ** Read part of the data associated with cursor pCur. Exactly
53729 ** "amt" bytes will be transfered into pBuf[]. The transfer
53730 ** begins at "offset".
53732 ** Return SQLITE_OK on success or an error code if anything goes
53733 ** wrong. An error is returned if "offset+amt" is larger than
53734 ** the available payload.
53736 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53737 int rc;
53739 #ifndef SQLITE_OMIT_INCRBLOB
53740 if ( pCur->eState==CURSOR_INVALID ){
53741 return SQLITE_ABORT;
53743 #endif
53745 assert( cursorHoldsMutex(pCur) );
53746 rc = restoreCursorPosition(pCur);
53747 if( rc==SQLITE_OK ){
53748 assert( pCur->eState==CURSOR_VALID );
53749 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53750 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53751 rc = accessPayload(pCur, offset, amt, pBuf, 0);
53753 return rc;
53757 ** Return a pointer to payload information from the entry that the
53758 ** pCur cursor is pointing to. The pointer is to the beginning of
53759 ** the key if skipKey==0 and it points to the beginning of data if
53760 ** skipKey==1. The number of bytes of available key/data is written
53761 ** into *pAmt. If *pAmt==0, then the value returned will not be
53762 ** a valid pointer.
53764 ** This routine is an optimization. It is common for the entire key
53765 ** and data to fit on the local page and for there to be no overflow
53766 ** pages. When that is so, this routine can be used to access the
53767 ** key and data without making a copy. If the key and/or data spills
53768 ** onto overflow pages, then accessPayload() must be used to reassemble
53769 ** the key/data and copy it into a preallocated buffer.
53771 ** The pointer returned by this routine looks directly into the cached
53772 ** page of the database. The data might change or move the next time
53773 ** any btree routine is called.
53775 static const unsigned char *fetchPayload(
53776 BtCursor *pCur, /* Cursor pointing to entry to read from */
53777 int *pAmt, /* Write the number of available bytes here */
53778 int skipKey /* read beginning at data if this is true */
53780 unsigned char *aPayload;
53781 MemPage *pPage;
53782 u32 nKey;
53783 u32 nLocal;
53785 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
53786 assert( pCur->eState==CURSOR_VALID );
53787 assert( cursorHoldsMutex(pCur) );
53788 pPage = pCur->apPage[pCur->iPage];
53789 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53790 if( NEVER(pCur->info.nSize==0) ){
53791 btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
53792 &pCur->info);
53794 aPayload = pCur->info.pCell;
53795 aPayload += pCur->info.nHeader;
53796 if( pPage->intKey ){
53797 nKey = 0;
53798 }else{
53799 nKey = (int)pCur->info.nKey;
53801 if( skipKey ){
53802 aPayload += nKey;
53803 nLocal = pCur->info.nLocal - nKey;
53804 }else{
53805 nLocal = pCur->info.nLocal;
53806 assert( nLocal<=nKey );
53808 *pAmt = nLocal;
53809 return aPayload;
53814 ** For the entry that cursor pCur is point to, return as
53815 ** many bytes of the key or data as are available on the local
53816 ** b-tree page. Write the number of available bytes into *pAmt.
53818 ** The pointer returned is ephemeral. The key/data may move
53819 ** or be destroyed on the next call to any Btree routine,
53820 ** including calls from other threads against the same cache.
53821 ** Hence, a mutex on the BtShared should be held prior to calling
53822 ** this routine.
53824 ** These routines is used to get quick access to key and data
53825 ** in the common case where no overflow pages are used.
53827 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
53828 const void *p = 0;
53829 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53830 assert( cursorHoldsMutex(pCur) );
53831 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53832 p = (const void*)fetchPayload(pCur, pAmt, 0);
53834 return p;
53836 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
53837 const void *p = 0;
53838 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53839 assert( cursorHoldsMutex(pCur) );
53840 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53841 p = (const void*)fetchPayload(pCur, pAmt, 1);
53843 return p;
53848 ** Move the cursor down to a new child page. The newPgno argument is the
53849 ** page number of the child page to move to.
53851 ** This function returns SQLITE_CORRUPT if the page-header flags field of
53852 ** the new child page does not match the flags field of the parent (i.e.
53853 ** if an intkey page appears to be the parent of a non-intkey page, or
53854 ** vice-versa).
53856 static int moveToChild(BtCursor *pCur, u32 newPgno){
53857 int rc;
53858 int i = pCur->iPage;
53859 MemPage *pNewPage;
53860 BtShared *pBt = pCur->pBt;
53862 assert( cursorHoldsMutex(pCur) );
53863 assert( pCur->eState==CURSOR_VALID );
53864 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
53865 assert( pCur->iPage>=0 );
53866 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
53867 return SQLITE_CORRUPT_BKPT;
53869 rc = getAndInitPage(pBt, newPgno, &pNewPage,
53870 pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
53871 if( rc ) return rc;
53872 pCur->apPage[i+1] = pNewPage;
53873 pCur->aiIdx[i+1] = 0;
53874 pCur->iPage++;
53876 pCur->info.nSize = 0;
53877 pCur->validNKey = 0;
53878 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
53879 return SQLITE_CORRUPT_BKPT;
53881 return SQLITE_OK;
53884 #if 0
53886 ** Page pParent is an internal (non-leaf) tree page. This function
53887 ** asserts that page number iChild is the left-child if the iIdx'th
53888 ** cell in page pParent. Or, if iIdx is equal to the total number of
53889 ** cells in pParent, that page number iChild is the right-child of
53890 ** the page.
53892 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
53893 assert( iIdx<=pParent->nCell );
53894 if( iIdx==pParent->nCell ){
53895 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
53896 }else{
53897 assert( get4byte(findCell(pParent, iIdx))==iChild );
53900 #else
53901 # define assertParentIndex(x,y,z)
53902 #endif
53905 ** Move the cursor up to the parent page.
53907 ** pCur->idx is set to the cell index that contains the pointer
53908 ** to the page we are coming from. If we are coming from the
53909 ** right-most child page then pCur->idx is set to one more than
53910 ** the largest cell index.
53912 static void moveToParent(BtCursor *pCur){
53913 assert( cursorHoldsMutex(pCur) );
53914 assert( pCur->eState==CURSOR_VALID );
53915 assert( pCur->iPage>0 );
53916 assert( pCur->apPage[pCur->iPage] );
53918 /* UPDATE: It is actually possible for the condition tested by the assert
53919 ** below to be untrue if the database file is corrupt. This can occur if
53920 ** one cursor has modified page pParent while a reference to it is held
53921 ** by a second cursor. Which can only happen if a single page is linked
53922 ** into more than one b-tree structure in a corrupt database. */
53923 #if 0
53924 assertParentIndex(
53925 pCur->apPage[pCur->iPage-1],
53926 pCur->aiIdx[pCur->iPage-1],
53927 pCur->apPage[pCur->iPage]->pgno
53929 #endif
53930 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
53932 releasePage(pCur->apPage[pCur->iPage]);
53933 pCur->iPage--;
53934 pCur->info.nSize = 0;
53935 pCur->validNKey = 0;
53939 ** Move the cursor to point to the root page of its b-tree structure.
53941 ** If the table has a virtual root page, then the cursor is moved to point
53942 ** to the virtual root page instead of the actual root page. A table has a
53943 ** virtual root page when the actual root page contains no cells and a
53944 ** single child page. This can only happen with the table rooted at page 1.
53946 ** If the b-tree structure is empty, the cursor state is set to
53947 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
53948 ** cell located on the root (or virtual root) page and the cursor state
53949 ** is set to CURSOR_VALID.
53951 ** If this function returns successfully, it may be assumed that the
53952 ** page-header flags indicate that the [virtual] root-page is the expected
53953 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
53954 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
53955 ** indicating a table b-tree, or if the caller did specify a KeyInfo
53956 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
53957 ** b-tree).
53959 static int moveToRoot(BtCursor *pCur){
53960 MemPage *pRoot;
53961 int rc = SQLITE_OK;
53962 Btree *p = pCur->pBtree;
53963 BtShared *pBt = p->pBt;
53965 assert( cursorHoldsMutex(pCur) );
53966 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
53967 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
53968 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
53969 if( pCur->eState>=CURSOR_REQUIRESEEK ){
53970 if( pCur->eState==CURSOR_FAULT ){
53971 assert( pCur->skipNext!=SQLITE_OK );
53972 return pCur->skipNext;
53974 sqlite3BtreeClearCursor(pCur);
53977 if( pCur->iPage>=0 ){
53978 int i;
53979 for(i=1; i<=pCur->iPage; i++){
53980 releasePage(pCur->apPage[i]);
53982 pCur->iPage = 0;
53983 }else if( pCur->pgnoRoot==0 ){
53984 pCur->eState = CURSOR_INVALID;
53985 return SQLITE_OK;
53986 }else{
53987 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0],
53988 pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
53989 if( rc!=SQLITE_OK ){
53990 pCur->eState = CURSOR_INVALID;
53991 return rc;
53993 pCur->iPage = 0;
53995 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
53996 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
53997 ** NULL, the caller expects a table b-tree. If this is not the case,
53998 ** return an SQLITE_CORRUPT error. */
53999 assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
54000 if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
54001 return SQLITE_CORRUPT_BKPT;
54005 /* Assert that the root page is of the correct type. This must be the
54006 ** case as the call to this function that loaded the root-page (either
54007 ** this call or a previous invocation) would have detected corruption
54008 ** if the assumption were not true, and it is not possible for the flags
54009 ** byte to have been modified while this cursor is holding a reference
54010 ** to the page. */
54011 pRoot = pCur->apPage[0];
54012 assert( pRoot->pgno==pCur->pgnoRoot );
54013 assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
54015 pCur->aiIdx[0] = 0;
54016 pCur->info.nSize = 0;
54017 pCur->atLast = 0;
54018 pCur->validNKey = 0;
54020 if( pRoot->nCell==0 && !pRoot->leaf ){
54021 Pgno subpage;
54022 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
54023 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
54024 pCur->eState = CURSOR_VALID;
54025 rc = moveToChild(pCur, subpage);
54026 }else{
54027 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
54029 return rc;
54033 ** Move the cursor down to the left-most leaf entry beneath the
54034 ** entry to which it is currently pointing.
54036 ** The left-most leaf is the one with the smallest key - the first
54037 ** in ascending order.
54039 static int moveToLeftmost(BtCursor *pCur){
54040 Pgno pgno;
54041 int rc = SQLITE_OK;
54042 MemPage *pPage;
54044 assert( cursorHoldsMutex(pCur) );
54045 assert( pCur->eState==CURSOR_VALID );
54046 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
54047 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
54048 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
54049 rc = moveToChild(pCur, pgno);
54051 return rc;
54055 ** Move the cursor down to the right-most leaf entry beneath the
54056 ** page to which it is currently pointing. Notice the difference
54057 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
54058 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
54059 ** finds the right-most entry beneath the *page*.
54061 ** The right-most entry is the one with the largest key - the last
54062 ** key in ascending order.
54064 static int moveToRightmost(BtCursor *pCur){
54065 Pgno pgno;
54066 int rc = SQLITE_OK;
54067 MemPage *pPage = 0;
54069 assert( cursorHoldsMutex(pCur) );
54070 assert( pCur->eState==CURSOR_VALID );
54071 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
54072 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54073 pCur->aiIdx[pCur->iPage] = pPage->nCell;
54074 rc = moveToChild(pCur, pgno);
54076 if( rc==SQLITE_OK ){
54077 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
54078 pCur->info.nSize = 0;
54079 pCur->validNKey = 0;
54081 return rc;
54084 /* Move the cursor to the first entry in the table. Return SQLITE_OK
54085 ** on success. Set *pRes to 0 if the cursor actually points to something
54086 ** or set *pRes to 1 if the table is empty.
54088 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
54089 int rc;
54091 assert( cursorHoldsMutex(pCur) );
54092 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54093 rc = moveToRoot(pCur);
54094 if( rc==SQLITE_OK ){
54095 if( pCur->eState==CURSOR_INVALID ){
54096 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54097 *pRes = 1;
54098 }else{
54099 assert( pCur->apPage[pCur->iPage]->nCell>0 );
54100 *pRes = 0;
54101 rc = moveToLeftmost(pCur);
54104 return rc;
54107 /* Move the cursor to the last entry in the table. Return SQLITE_OK
54108 ** on success. Set *pRes to 0 if the cursor actually points to something
54109 ** or set *pRes to 1 if the table is empty.
54111 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
54112 int rc;
54114 assert( cursorHoldsMutex(pCur) );
54115 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54117 /* If the cursor already points to the last entry, this is a no-op. */
54118 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
54119 #ifdef SQLITE_DEBUG
54120 /* This block serves to assert() that the cursor really does point
54121 ** to the last entry in the b-tree. */
54122 int ii;
54123 for(ii=0; ii<pCur->iPage; ii++){
54124 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
54126 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
54127 assert( pCur->apPage[pCur->iPage]->leaf );
54128 #endif
54129 return SQLITE_OK;
54132 rc = moveToRoot(pCur);
54133 if( rc==SQLITE_OK ){
54134 if( CURSOR_INVALID==pCur->eState ){
54135 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54136 *pRes = 1;
54137 }else{
54138 assert( pCur->eState==CURSOR_VALID );
54139 *pRes = 0;
54140 rc = moveToRightmost(pCur);
54141 pCur->atLast = rc==SQLITE_OK ?1:0;
54144 return rc;
54147 /* Move the cursor so that it points to an entry near the key
54148 ** specified by pIdxKey or intKey. Return a success code.
54150 ** For INTKEY tables, the intKey parameter is used. pIdxKey
54151 ** must be NULL. For index tables, pIdxKey is used and intKey
54152 ** is ignored.
54154 ** If an exact match is not found, then the cursor is always
54155 ** left pointing at a leaf page which would hold the entry if it
54156 ** were present. The cursor might point to an entry that comes
54157 ** before or after the key.
54159 ** An integer is written into *pRes which is the result of
54160 ** comparing the key with the entry to which the cursor is
54161 ** pointing. The meaning of the integer written into
54162 ** *pRes is as follows:
54164 ** *pRes<0 The cursor is left pointing at an entry that
54165 ** is smaller than intKey/pIdxKey or if the table is empty
54166 ** and the cursor is therefore left point to nothing.
54168 ** *pRes==0 The cursor is left pointing at an entry that
54169 ** exactly matches intKey/pIdxKey.
54171 ** *pRes>0 The cursor is left pointing at an entry that
54172 ** is larger than intKey/pIdxKey.
54175 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
54176 BtCursor *pCur, /* The cursor to be moved */
54177 UnpackedRecord *pIdxKey, /* Unpacked index key */
54178 i64 intKey, /* The table key */
54179 int biasRight, /* If true, bias the search to the high end */
54180 int *pRes /* Write search results here */
54182 int rc;
54184 assert( cursorHoldsMutex(pCur) );
54185 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54186 assert( pRes );
54187 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
54189 /* If the cursor is already positioned at the point we are trying
54190 ** to move to, then just return without doing any work */
54191 if( pCur->eState==CURSOR_VALID && pCur->validNKey
54192 && pCur->apPage[0]->intKey
54194 if( pCur->info.nKey==intKey ){
54195 *pRes = 0;
54196 return SQLITE_OK;
54198 if( pCur->atLast && pCur->info.nKey<intKey ){
54199 *pRes = -1;
54200 return SQLITE_OK;
54204 rc = moveToRoot(pCur);
54205 if( rc ){
54206 return rc;
54208 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
54209 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
54210 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
54211 if( pCur->eState==CURSOR_INVALID ){
54212 *pRes = -1;
54213 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54214 return SQLITE_OK;
54216 assert( pCur->apPage[0]->intKey || pIdxKey );
54217 for(;;){
54218 int lwr, upr, idx;
54219 Pgno chldPg;
54220 MemPage *pPage = pCur->apPage[pCur->iPage];
54221 int c;
54223 /* pPage->nCell must be greater than zero. If this is the root-page
54224 ** the cursor would have been INVALID above and this for(;;) loop
54225 ** not run. If this is not the root-page, then the moveToChild() routine
54226 ** would have already detected db corruption. Similarly, pPage must
54227 ** be the right kind (index or table) of b-tree page. Otherwise
54228 ** a moveToChild() or moveToRoot() call would have detected corruption. */
54229 assert( pPage->nCell>0 );
54230 assert( pPage->intKey==(pIdxKey==0) );
54231 lwr = 0;
54232 upr = pPage->nCell-1;
54233 if( biasRight ){
54234 pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
54235 }else{
54236 pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
54238 for(;;){
54239 u8 *pCell; /* Pointer to current cell in pPage */
54241 assert( idx==pCur->aiIdx[pCur->iPage] );
54242 pCur->info.nSize = 0;
54243 pCell = findCell(pPage, idx) + pPage->childPtrSize;
54244 if( pPage->intKey ){
54245 i64 nCellKey;
54246 if( pPage->hasData ){
54247 u32 dummy;
54248 pCell += getVarint32(pCell, dummy);
54250 getVarint(pCell, (u64*)&nCellKey);
54251 if( nCellKey==intKey ){
54252 c = 0;
54253 }else if( nCellKey<intKey ){
54254 c = -1;
54255 }else{
54256 assert( nCellKey>intKey );
54257 c = +1;
54259 pCur->validNKey = 1;
54260 pCur->info.nKey = nCellKey;
54261 }else{
54262 /* The maximum supported page-size is 65536 bytes. This means that
54263 ** the maximum number of record bytes stored on an index B-Tree
54264 ** page is less than 16384 bytes and may be stored as a 2-byte
54265 ** varint. This information is used to attempt to avoid parsing
54266 ** the entire cell by checking for the cases where the record is
54267 ** stored entirely within the b-tree page by inspecting the first
54268 ** 2 bytes of the cell.
54270 int nCell = pCell[0];
54271 if( nCell<=pPage->max1bytePayload
54272 /* && (pCell+nCell)<pPage->aDataEnd */
54274 /* This branch runs if the record-size field of the cell is a
54275 ** single byte varint and the record fits entirely on the main
54276 ** b-tree page. */
54277 testcase( pCell+nCell+1==pPage->aDataEnd );
54278 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
54279 }else if( !(pCell[1] & 0x80)
54280 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
54281 /* && (pCell+nCell+2)<=pPage->aDataEnd */
54283 /* The record-size field is a 2 byte varint and the record
54284 ** fits entirely on the main b-tree page. */
54285 testcase( pCell+nCell+2==pPage->aDataEnd );
54286 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
54287 }else{
54288 /* The record flows over onto one or more overflow pages. In
54289 ** this case the whole cell needs to be parsed, a buffer allocated
54290 ** and accessPayload() used to retrieve the record into the
54291 ** buffer before VdbeRecordCompare() can be called. */
54292 void *pCellKey;
54293 u8 * const pCellBody = pCell - pPage->childPtrSize;
54294 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
54295 nCell = (int)pCur->info.nKey;
54296 pCellKey = sqlite3Malloc( nCell );
54297 if( pCellKey==0 ){
54298 rc = SQLITE_NOMEM;
54299 goto moveto_finish;
54301 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
54302 if( rc ){
54303 sqlite3_free(pCellKey);
54304 goto moveto_finish;
54306 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
54307 sqlite3_free(pCellKey);
54310 if( c==0 ){
54311 if( pPage->intKey && !pPage->leaf ){
54312 lwr = idx;
54313 break;
54314 }else{
54315 *pRes = 0;
54316 rc = SQLITE_OK;
54317 goto moveto_finish;
54320 if( c<0 ){
54321 lwr = idx+1;
54322 }else{
54323 upr = idx-1;
54325 if( lwr>upr ){
54326 break;
54328 pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
54330 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
54331 assert( pPage->isInit );
54332 if( pPage->leaf ){
54333 chldPg = 0;
54334 }else if( lwr>=pPage->nCell ){
54335 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54336 }else{
54337 chldPg = get4byte(findCell(pPage, lwr));
54339 if( chldPg==0 ){
54340 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54341 *pRes = c;
54342 rc = SQLITE_OK;
54343 goto moveto_finish;
54345 pCur->aiIdx[pCur->iPage] = (u16)lwr;
54346 pCur->info.nSize = 0;
54347 pCur->validNKey = 0;
54348 rc = moveToChild(pCur, chldPg);
54349 if( rc ) goto moveto_finish;
54351 moveto_finish:
54352 return rc;
54357 ** Return TRUE if the cursor is not pointing at an entry of the table.
54359 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
54360 ** past the last entry in the table or sqlite3BtreePrev() moves past
54361 ** the first entry. TRUE is also returned if the table is empty.
54363 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
54364 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
54365 ** have been deleted? This API will need to change to return an error code
54366 ** as well as the boolean result value.
54368 return (CURSOR_VALID!=pCur->eState);
54372 ** Advance the cursor to the next entry in the database. If
54373 ** successful then set *pRes=0. If the cursor
54374 ** was already pointing to the last entry in the database before
54375 ** this routine was called, then set *pRes=1.
54377 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
54378 int rc;
54379 int idx;
54380 MemPage *pPage;
54382 assert( cursorHoldsMutex(pCur) );
54383 assert( pRes!=0 );
54384 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
54385 if( pCur->eState!=CURSOR_VALID ){
54386 rc = restoreCursorPosition(pCur);
54387 if( rc!=SQLITE_OK ){
54388 *pRes = 0;
54389 return rc;
54391 if( CURSOR_INVALID==pCur->eState ){
54392 *pRes = 1;
54393 return SQLITE_OK;
54395 if( pCur->skipNext ){
54396 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
54397 pCur->eState = CURSOR_VALID;
54398 if( pCur->skipNext>0 ){
54399 pCur->skipNext = 0;
54400 *pRes = 0;
54401 return SQLITE_OK;
54403 pCur->skipNext = 0;
54407 pPage = pCur->apPage[pCur->iPage];
54408 idx = ++pCur->aiIdx[pCur->iPage];
54409 assert( pPage->isInit );
54411 /* If the database file is corrupt, it is possible for the value of idx
54412 ** to be invalid here. This can only occur if a second cursor modifies
54413 ** the page while cursor pCur is holding a reference to it. Which can
54414 ** only happen if the database is corrupt in such a way as to link the
54415 ** page into more than one b-tree structure. */
54416 testcase( idx>pPage->nCell );
54418 pCur->info.nSize = 0;
54419 pCur->validNKey = 0;
54420 if( idx>=pPage->nCell ){
54421 if( !pPage->leaf ){
54422 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54423 if( rc ){
54424 *pRes = 0;
54425 return rc;
54427 rc = moveToLeftmost(pCur);
54428 *pRes = 0;
54429 return rc;
54432 if( pCur->iPage==0 ){
54433 *pRes = 1;
54434 pCur->eState = CURSOR_INVALID;
54435 return SQLITE_OK;
54437 moveToParent(pCur);
54438 pPage = pCur->apPage[pCur->iPage];
54439 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
54440 *pRes = 0;
54441 if( pPage->intKey ){
54442 rc = sqlite3BtreeNext(pCur, pRes);
54443 }else{
54444 rc = SQLITE_OK;
54446 return rc;
54448 *pRes = 0;
54449 if( pPage->leaf ){
54450 return SQLITE_OK;
54452 rc = moveToLeftmost(pCur);
54453 return rc;
54458 ** Step the cursor to the back to the previous entry in the database. If
54459 ** successful then set *pRes=0. If the cursor
54460 ** was already pointing to the first entry in the database before
54461 ** this routine was called, then set *pRes=1.
54463 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
54464 int rc;
54465 MemPage *pPage;
54467 assert( cursorHoldsMutex(pCur) );
54468 assert( pRes!=0 );
54469 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
54470 pCur->atLast = 0;
54471 if( pCur->eState!=CURSOR_VALID ){
54472 if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
54473 rc = btreeRestoreCursorPosition(pCur);
54474 if( rc!=SQLITE_OK ){
54475 *pRes = 0;
54476 return rc;
54479 if( CURSOR_INVALID==pCur->eState ){
54480 *pRes = 1;
54481 return SQLITE_OK;
54483 if( pCur->skipNext ){
54484 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
54485 pCur->eState = CURSOR_VALID;
54486 if( pCur->skipNext<0 ){
54487 pCur->skipNext = 0;
54488 *pRes = 0;
54489 return SQLITE_OK;
54491 pCur->skipNext = 0;
54495 pPage = pCur->apPage[pCur->iPage];
54496 assert( pPage->isInit );
54497 if( !pPage->leaf ){
54498 int idx = pCur->aiIdx[pCur->iPage];
54499 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
54500 if( rc ){
54501 *pRes = 0;
54502 return rc;
54504 rc = moveToRightmost(pCur);
54505 }else{
54506 while( pCur->aiIdx[pCur->iPage]==0 ){
54507 if( pCur->iPage==0 ){
54508 pCur->eState = CURSOR_INVALID;
54509 *pRes = 1;
54510 return SQLITE_OK;
54512 moveToParent(pCur);
54514 pCur->info.nSize = 0;
54515 pCur->validNKey = 0;
54517 pCur->aiIdx[pCur->iPage]--;
54518 pPage = pCur->apPage[pCur->iPage];
54519 if( pPage->intKey && !pPage->leaf ){
54520 rc = sqlite3BtreePrevious(pCur, pRes);
54521 }else{
54522 rc = SQLITE_OK;
54525 *pRes = 0;
54526 return rc;
54530 ** Allocate a new page from the database file.
54532 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
54533 ** has already been called on the new page.) The new page has also
54534 ** been referenced and the calling routine is responsible for calling
54535 ** sqlite3PagerUnref() on the new page when it is done.
54537 ** SQLITE_OK is returned on success. Any other return value indicates
54538 ** an error. *ppPage and *pPgno are undefined in the event of an error.
54539 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
54541 ** If the "nearby" parameter is not 0, then an effort is made to
54542 ** locate a page close to the page number "nearby". This can be used in an
54543 ** attempt to keep related pages close to each other in the database file,
54544 ** which in turn can make database access faster.
54546 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
54547 ** anywhere on the free-list, then it is guaranteed to be returned. If
54548 ** eMode is BTALLOC_LT then the page returned will be less than or equal
54549 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
54550 ** are no restrictions on which page is returned.
54552 static int allocateBtreePage(
54553 BtShared *pBt, /* The btree */
54554 MemPage **ppPage, /* Store pointer to the allocated page here */
54555 Pgno *pPgno, /* Store the page number here */
54556 Pgno nearby, /* Search for a page near this one */
54557 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
54559 MemPage *pPage1;
54560 int rc;
54561 u32 n; /* Number of pages on the freelist */
54562 u32 k; /* Number of leaves on the trunk of the freelist */
54563 MemPage *pTrunk = 0;
54564 MemPage *pPrevTrunk = 0;
54565 Pgno mxPage; /* Total size of the database file */
54567 assert( sqlite3_mutex_held(pBt->mutex) );
54568 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
54569 pPage1 = pBt->pPage1;
54570 mxPage = btreePagecount(pBt);
54571 n = get4byte(&pPage1->aData[36]);
54572 testcase( n==mxPage-1 );
54573 if( n>=mxPage ){
54574 return SQLITE_CORRUPT_BKPT;
54576 if( n>0 ){
54577 /* There are pages on the freelist. Reuse one of those pages. */
54578 Pgno iTrunk;
54579 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
54581 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
54582 ** shows that the page 'nearby' is somewhere on the free-list, then
54583 ** the entire-list will be searched for that page.
54585 #ifndef SQLITE_OMIT_AUTOVACUUM
54586 if( eMode==BTALLOC_EXACT ){
54587 if( nearby<=mxPage ){
54588 u8 eType;
54589 assert( nearby>0 );
54590 assert( pBt->autoVacuum );
54591 rc = ptrmapGet(pBt, nearby, &eType, 0);
54592 if( rc ) return rc;
54593 if( eType==PTRMAP_FREEPAGE ){
54594 searchList = 1;
54597 }else if( eMode==BTALLOC_LE ){
54598 searchList = 1;
54600 #endif
54602 /* Decrement the free-list count by 1. Set iTrunk to the index of the
54603 ** first free-list trunk page. iPrevTrunk is initially 1.
54605 rc = sqlite3PagerWrite(pPage1->pDbPage);
54606 if( rc ) return rc;
54607 put4byte(&pPage1->aData[36], n-1);
54609 /* The code within this loop is run only once if the 'searchList' variable
54610 ** is not true. Otherwise, it runs once for each trunk-page on the
54611 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
54612 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
54614 do {
54615 pPrevTrunk = pTrunk;
54616 if( pPrevTrunk ){
54617 iTrunk = get4byte(&pPrevTrunk->aData[0]);
54618 }else{
54619 iTrunk = get4byte(&pPage1->aData[32]);
54621 testcase( iTrunk==mxPage );
54622 if( iTrunk>mxPage ){
54623 rc = SQLITE_CORRUPT_BKPT;
54624 }else{
54625 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54627 if( rc ){
54628 pTrunk = 0;
54629 goto end_allocate_page;
54631 assert( pTrunk!=0 );
54632 assert( pTrunk->aData!=0 );
54634 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
54635 if( k==0 && !searchList ){
54636 /* The trunk has no leaves and the list is not being searched.
54637 ** So extract the trunk page itself and use it as the newly
54638 ** allocated page */
54639 assert( pPrevTrunk==0 );
54640 rc = sqlite3PagerWrite(pTrunk->pDbPage);
54641 if( rc ){
54642 goto end_allocate_page;
54644 *pPgno = iTrunk;
54645 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54646 *ppPage = pTrunk;
54647 pTrunk = 0;
54648 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54649 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
54650 /* Value of k is out of range. Database corruption */
54651 rc = SQLITE_CORRUPT_BKPT;
54652 goto end_allocate_page;
54653 #ifndef SQLITE_OMIT_AUTOVACUUM
54654 }else if( searchList
54655 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
54657 /* The list is being searched and this trunk page is the page
54658 ** to allocate, regardless of whether it has leaves.
54660 *pPgno = iTrunk;
54661 *ppPage = pTrunk;
54662 searchList = 0;
54663 rc = sqlite3PagerWrite(pTrunk->pDbPage);
54664 if( rc ){
54665 goto end_allocate_page;
54667 if( k==0 ){
54668 if( !pPrevTrunk ){
54669 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54670 }else{
54671 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54672 if( rc!=SQLITE_OK ){
54673 goto end_allocate_page;
54675 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
54677 }else{
54678 /* The trunk page is required by the caller but it contains
54679 ** pointers to free-list leaves. The first leaf becomes a trunk
54680 ** page in this case.
54682 MemPage *pNewTrunk;
54683 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
54684 if( iNewTrunk>mxPage ){
54685 rc = SQLITE_CORRUPT_BKPT;
54686 goto end_allocate_page;
54688 testcase( iNewTrunk==mxPage );
54689 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
54690 if( rc!=SQLITE_OK ){
54691 goto end_allocate_page;
54693 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
54694 if( rc!=SQLITE_OK ){
54695 releasePage(pNewTrunk);
54696 goto end_allocate_page;
54698 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
54699 put4byte(&pNewTrunk->aData[4], k-1);
54700 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
54701 releasePage(pNewTrunk);
54702 if( !pPrevTrunk ){
54703 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
54704 put4byte(&pPage1->aData[32], iNewTrunk);
54705 }else{
54706 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54707 if( rc ){
54708 goto end_allocate_page;
54710 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
54713 pTrunk = 0;
54714 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54715 #endif
54716 }else if( k>0 ){
54717 /* Extract a leaf from the trunk */
54718 u32 closest;
54719 Pgno iPage;
54720 unsigned char *aData = pTrunk->aData;
54721 if( nearby>0 ){
54722 u32 i;
54723 closest = 0;
54724 if( eMode==BTALLOC_LE ){
54725 for(i=0; i<k; i++){
54726 iPage = get4byte(&aData[8+i*4]);
54727 if( iPage<=nearby ){
54728 closest = i;
54729 break;
54732 }else{
54733 int dist;
54734 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
54735 for(i=1; i<k; i++){
54736 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
54737 if( d2<dist ){
54738 closest = i;
54739 dist = d2;
54743 }else{
54744 closest = 0;
54747 iPage = get4byte(&aData[8+closest*4]);
54748 testcase( iPage==mxPage );
54749 if( iPage>mxPage ){
54750 rc = SQLITE_CORRUPT_BKPT;
54751 goto end_allocate_page;
54753 testcase( iPage==mxPage );
54754 if( !searchList
54755 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
54757 int noContent;
54758 *pPgno = iPage;
54759 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
54760 ": %d more free pages\n",
54761 *pPgno, closest+1, k, pTrunk->pgno, n-1));
54762 rc = sqlite3PagerWrite(pTrunk->pDbPage);
54763 if( rc ) goto end_allocate_page;
54764 if( closest<k-1 ){
54765 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
54767 put4byte(&aData[4], k-1);
54768 noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
54769 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
54770 if( rc==SQLITE_OK ){
54771 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
54772 if( rc!=SQLITE_OK ){
54773 releasePage(*ppPage);
54776 searchList = 0;
54779 releasePage(pPrevTrunk);
54780 pPrevTrunk = 0;
54781 }while( searchList );
54782 }else{
54783 /* There are no pages on the freelist, so append a new page to the
54784 ** database image.
54786 ** Normally, new pages allocated by this block can be requested from the
54787 ** pager layer with the 'no-content' flag set. This prevents the pager
54788 ** from trying to read the pages content from disk. However, if the
54789 ** current transaction has already run one or more incremental-vacuum
54790 ** steps, then the page we are about to allocate may contain content
54791 ** that is required in the event of a rollback. In this case, do
54792 ** not set the no-content flag. This causes the pager to load and journal
54793 ** the current page content before overwriting it.
54795 ** Note that the pager will not actually attempt to load or journal
54796 ** content for any page that really does lie past the end of the database
54797 ** file on disk. So the effects of disabling the no-content optimization
54798 ** here are confined to those pages that lie between the end of the
54799 ** database image and the end of the database file.
54801 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
54803 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54804 if( rc ) return rc;
54805 pBt->nPage++;
54806 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
54808 #ifndef SQLITE_OMIT_AUTOVACUUM
54809 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
54810 /* If *pPgno refers to a pointer-map page, allocate two new pages
54811 ** at the end of the file instead of one. The first allocated page
54812 ** becomes a new pointer-map page, the second is used by the caller.
54814 MemPage *pPg = 0;
54815 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
54816 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
54817 rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
54818 if( rc==SQLITE_OK ){
54819 rc = sqlite3PagerWrite(pPg->pDbPage);
54820 releasePage(pPg);
54822 if( rc ) return rc;
54823 pBt->nPage++;
54824 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
54826 #endif
54827 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
54828 *pPgno = pBt->nPage;
54830 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54831 rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
54832 if( rc ) return rc;
54833 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
54834 if( rc!=SQLITE_OK ){
54835 releasePage(*ppPage);
54837 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
54840 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54842 end_allocate_page:
54843 releasePage(pTrunk);
54844 releasePage(pPrevTrunk);
54845 if( rc==SQLITE_OK ){
54846 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
54847 releasePage(*ppPage);
54848 return SQLITE_CORRUPT_BKPT;
54850 (*ppPage)->isInit = 0;
54851 }else{
54852 *ppPage = 0;
54854 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
54855 return rc;
54859 ** This function is used to add page iPage to the database file free-list.
54860 ** It is assumed that the page is not already a part of the free-list.
54862 ** The value passed as the second argument to this function is optional.
54863 ** If the caller happens to have a pointer to the MemPage object
54864 ** corresponding to page iPage handy, it may pass it as the second value.
54865 ** Otherwise, it may pass NULL.
54867 ** If a pointer to a MemPage object is passed as the second argument,
54868 ** its reference count is not altered by this function.
54870 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
54871 MemPage *pTrunk = 0; /* Free-list trunk page */
54872 Pgno iTrunk = 0; /* Page number of free-list trunk page */
54873 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
54874 MemPage *pPage; /* Page being freed. May be NULL. */
54875 int rc; /* Return Code */
54876 int nFree; /* Initial number of pages on free-list */
54878 assert( sqlite3_mutex_held(pBt->mutex) );
54879 assert( iPage>1 );
54880 assert( !pMemPage || pMemPage->pgno==iPage );
54882 if( pMemPage ){
54883 pPage = pMemPage;
54884 sqlite3PagerRef(pPage->pDbPage);
54885 }else{
54886 pPage = btreePageLookup(pBt, iPage);
54889 /* Increment the free page count on pPage1 */
54890 rc = sqlite3PagerWrite(pPage1->pDbPage);
54891 if( rc ) goto freepage_out;
54892 nFree = get4byte(&pPage1->aData[36]);
54893 put4byte(&pPage1->aData[36], nFree+1);
54895 if( pBt->btsFlags & BTS_SECURE_DELETE ){
54896 /* If the secure_delete option is enabled, then
54897 ** always fully overwrite deleted information with zeros.
54899 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
54900 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
54902 goto freepage_out;
54904 memset(pPage->aData, 0, pPage->pBt->pageSize);
54907 /* If the database supports auto-vacuum, write an entry in the pointer-map
54908 ** to indicate that the page is free.
54910 if( ISAUTOVACUUM ){
54911 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
54912 if( rc ) goto freepage_out;
54915 /* Now manipulate the actual database free-list structure. There are two
54916 ** possibilities. If the free-list is currently empty, or if the first
54917 ** trunk page in the free-list is full, then this page will become a
54918 ** new free-list trunk page. Otherwise, it will become a leaf of the
54919 ** first trunk page in the current free-list. This block tests if it
54920 ** is possible to add the page as a new free-list leaf.
54922 if( nFree!=0 ){
54923 u32 nLeaf; /* Initial number of leaf cells on trunk page */
54925 iTrunk = get4byte(&pPage1->aData[32]);
54926 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54927 if( rc!=SQLITE_OK ){
54928 goto freepage_out;
54931 nLeaf = get4byte(&pTrunk->aData[4]);
54932 assert( pBt->usableSize>32 );
54933 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
54934 rc = SQLITE_CORRUPT_BKPT;
54935 goto freepage_out;
54937 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
54938 /* In this case there is room on the trunk page to insert the page
54939 ** being freed as a new leaf.
54941 ** Note that the trunk page is not really full until it contains
54942 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
54943 ** coded. But due to a coding error in versions of SQLite prior to
54944 ** 3.6.0, databases with freelist trunk pages holding more than
54945 ** usableSize/4 - 8 entries will be reported as corrupt. In order
54946 ** to maintain backwards compatibility with older versions of SQLite,
54947 ** we will continue to restrict the number of entries to usableSize/4 - 8
54948 ** for now. At some point in the future (once everyone has upgraded
54949 ** to 3.6.0 or later) we should consider fixing the conditional above
54950 ** to read "usableSize/4-2" instead of "usableSize/4-8".
54952 rc = sqlite3PagerWrite(pTrunk->pDbPage);
54953 if( rc==SQLITE_OK ){
54954 put4byte(&pTrunk->aData[4], nLeaf+1);
54955 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
54956 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
54957 sqlite3PagerDontWrite(pPage->pDbPage);
54959 rc = btreeSetHasContent(pBt, iPage);
54961 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
54962 goto freepage_out;
54966 /* If control flows to this point, then it was not possible to add the
54967 ** the page being freed as a leaf page of the first trunk in the free-list.
54968 ** Possibly because the free-list is empty, or possibly because the
54969 ** first trunk in the free-list is full. Either way, the page being freed
54970 ** will become the new first trunk page in the free-list.
54972 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
54973 goto freepage_out;
54975 rc = sqlite3PagerWrite(pPage->pDbPage);
54976 if( rc!=SQLITE_OK ){
54977 goto freepage_out;
54979 put4byte(pPage->aData, iTrunk);
54980 put4byte(&pPage->aData[4], 0);
54981 put4byte(&pPage1->aData[32], iPage);
54982 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
54984 freepage_out:
54985 if( pPage ){
54986 pPage->isInit = 0;
54988 releasePage(pPage);
54989 releasePage(pTrunk);
54990 return rc;
54992 static void freePage(MemPage *pPage, int *pRC){
54993 if( (*pRC)==SQLITE_OK ){
54994 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
54999 ** Free any overflow pages associated with the given Cell.
55001 static int clearCell(MemPage *pPage, unsigned char *pCell){
55002 BtShared *pBt = pPage->pBt;
55003 CellInfo info;
55004 Pgno ovflPgno;
55005 int rc;
55006 int nOvfl;
55007 u32 ovflPageSize;
55009 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55010 btreeParseCellPtr(pPage, pCell, &info);
55011 if( info.iOverflow==0 ){
55012 return SQLITE_OK; /* No overflow pages. Return without doing anything */
55014 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
55015 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
55017 ovflPgno = get4byte(&pCell[info.iOverflow]);
55018 assert( pBt->usableSize > 4 );
55019 ovflPageSize = pBt->usableSize - 4;
55020 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
55021 assert( ovflPgno==0 || nOvfl>0 );
55022 while( nOvfl-- ){
55023 Pgno iNext = 0;
55024 MemPage *pOvfl = 0;
55025 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
55026 /* 0 is not a legal page number and page 1 cannot be an
55027 ** overflow page. Therefore if ovflPgno<2 or past the end of the
55028 ** file the database must be corrupt. */
55029 return SQLITE_CORRUPT_BKPT;
55031 if( nOvfl ){
55032 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
55033 if( rc ) return rc;
55036 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
55037 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
55039 /* There is no reason any cursor should have an outstanding reference
55040 ** to an overflow page belonging to a cell that is being deleted/updated.
55041 ** So if there exists more than one reference to this page, then it
55042 ** must not really be an overflow page and the database must be corrupt.
55043 ** It is helpful to detect this before calling freePage2(), as
55044 ** freePage2() may zero the page contents if secure-delete mode is
55045 ** enabled. If this 'overflow' page happens to be a page that the
55046 ** caller is iterating through or using in some other way, this
55047 ** can be problematic.
55049 rc = SQLITE_CORRUPT_BKPT;
55050 }else{
55051 rc = freePage2(pBt, pOvfl, ovflPgno);
55054 if( pOvfl ){
55055 sqlite3PagerUnref(pOvfl->pDbPage);
55057 if( rc ) return rc;
55058 ovflPgno = iNext;
55060 return SQLITE_OK;
55064 ** Create the byte sequence used to represent a cell on page pPage
55065 ** and write that byte sequence into pCell[]. Overflow pages are
55066 ** allocated and filled in as necessary. The calling procedure
55067 ** is responsible for making sure sufficient space has been allocated
55068 ** for pCell[].
55070 ** Note that pCell does not necessary need to point to the pPage->aData
55071 ** area. pCell might point to some temporary storage. The cell will
55072 ** be constructed in this temporary area then copied into pPage->aData
55073 ** later.
55075 static int fillInCell(
55076 MemPage *pPage, /* The page that contains the cell */
55077 unsigned char *pCell, /* Complete text of the cell */
55078 const void *pKey, i64 nKey, /* The key */
55079 const void *pData,int nData, /* The data */
55080 int nZero, /* Extra zero bytes to append to pData */
55081 int *pnSize /* Write cell size here */
55083 int nPayload;
55084 const u8 *pSrc;
55085 int nSrc, n, rc;
55086 int spaceLeft;
55087 MemPage *pOvfl = 0;
55088 MemPage *pToRelease = 0;
55089 unsigned char *pPrior;
55090 unsigned char *pPayload;
55091 BtShared *pBt = pPage->pBt;
55092 Pgno pgnoOvfl = 0;
55093 int nHeader;
55094 CellInfo info;
55096 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55098 /* pPage is not necessarily writeable since pCell might be auxiliary
55099 ** buffer space that is separate from the pPage buffer area */
55100 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
55101 || sqlite3PagerIswriteable(pPage->pDbPage) );
55103 /* Fill in the header. */
55104 nHeader = 0;
55105 if( !pPage->leaf ){
55106 nHeader += 4;
55108 if( pPage->hasData ){
55109 nHeader += putVarint(&pCell[nHeader], nData+nZero);
55110 }else{
55111 nData = nZero = 0;
55113 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
55114 btreeParseCellPtr(pPage, pCell, &info);
55115 assert( info.nHeader==nHeader );
55116 assert( info.nKey==nKey );
55117 assert( info.nData==(u32)(nData+nZero) );
55119 /* Fill in the payload */
55120 nPayload = nData + nZero;
55121 if( pPage->intKey ){
55122 pSrc = pData;
55123 nSrc = nData;
55124 nData = 0;
55125 }else{
55126 if( NEVER(nKey>0x7fffffff || pKey==0) ){
55127 return SQLITE_CORRUPT_BKPT;
55129 nPayload += (int)nKey;
55130 pSrc = pKey;
55131 nSrc = (int)nKey;
55133 *pnSize = info.nSize;
55134 spaceLeft = info.nLocal;
55135 pPayload = &pCell[nHeader];
55136 pPrior = &pCell[info.iOverflow];
55138 while( nPayload>0 ){
55139 if( spaceLeft==0 ){
55140 #ifndef SQLITE_OMIT_AUTOVACUUM
55141 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
55142 if( pBt->autoVacuum ){
55144 pgnoOvfl++;
55145 } while(
55146 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
55149 #endif
55150 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
55151 #ifndef SQLITE_OMIT_AUTOVACUUM
55152 /* If the database supports auto-vacuum, and the second or subsequent
55153 ** overflow page is being allocated, add an entry to the pointer-map
55154 ** for that page now.
55156 ** If this is the first overflow page, then write a partial entry
55157 ** to the pointer-map. If we write nothing to this pointer-map slot,
55158 ** then the optimistic overflow chain processing in clearCell()
55159 ** may misinterpret the uninitialized values and delete the
55160 ** wrong pages from the database.
55162 if( pBt->autoVacuum && rc==SQLITE_OK ){
55163 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
55164 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
55165 if( rc ){
55166 releasePage(pOvfl);
55169 #endif
55170 if( rc ){
55171 releasePage(pToRelease);
55172 return rc;
55175 /* If pToRelease is not zero than pPrior points into the data area
55176 ** of pToRelease. Make sure pToRelease is still writeable. */
55177 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
55179 /* If pPrior is part of the data area of pPage, then make sure pPage
55180 ** is still writeable */
55181 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
55182 || sqlite3PagerIswriteable(pPage->pDbPage) );
55184 put4byte(pPrior, pgnoOvfl);
55185 releasePage(pToRelease);
55186 pToRelease = pOvfl;
55187 pPrior = pOvfl->aData;
55188 put4byte(pPrior, 0);
55189 pPayload = &pOvfl->aData[4];
55190 spaceLeft = pBt->usableSize - 4;
55192 n = nPayload;
55193 if( n>spaceLeft ) n = spaceLeft;
55195 /* If pToRelease is not zero than pPayload points into the data area
55196 ** of pToRelease. Make sure pToRelease is still writeable. */
55197 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
55199 /* If pPayload is part of the data area of pPage, then make sure pPage
55200 ** is still writeable */
55201 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
55202 || sqlite3PagerIswriteable(pPage->pDbPage) );
55204 if( nSrc>0 ){
55205 if( n>nSrc ) n = nSrc;
55206 assert( pSrc );
55207 memcpy(pPayload, pSrc, n);
55208 }else{
55209 memset(pPayload, 0, n);
55211 nPayload -= n;
55212 pPayload += n;
55213 pSrc += n;
55214 nSrc -= n;
55215 spaceLeft -= n;
55216 if( nSrc==0 ){
55217 nSrc = nData;
55218 pSrc = pData;
55221 releasePage(pToRelease);
55222 return SQLITE_OK;
55226 ** Remove the i-th cell from pPage. This routine effects pPage only.
55227 ** The cell content is not freed or deallocated. It is assumed that
55228 ** the cell content has been copied someplace else. This routine just
55229 ** removes the reference to the cell from pPage.
55231 ** "sz" must be the number of bytes in the cell.
55233 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
55234 u32 pc; /* Offset to cell content of cell being deleted */
55235 u8 *data; /* pPage->aData */
55236 u8 *ptr; /* Used to move bytes around within data[] */
55237 u8 *endPtr; /* End of loop */
55238 int rc; /* The return code */
55239 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
55241 if( *pRC ) return;
55243 assert( idx>=0 && idx<pPage->nCell );
55244 assert( sz==cellSize(pPage, idx) );
55245 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55246 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55247 data = pPage->aData;
55248 ptr = &pPage->aCellIdx[2*idx];
55249 pc = get2byte(ptr);
55250 hdr = pPage->hdrOffset;
55251 testcase( pc==get2byte(&data[hdr+5]) );
55252 testcase( pc+sz==pPage->pBt->usableSize );
55253 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
55254 *pRC = SQLITE_CORRUPT_BKPT;
55255 return;
55257 rc = freeSpace(pPage, pc, sz);
55258 if( rc ){
55259 *pRC = rc;
55260 return;
55262 endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
55263 assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
55264 while( ptr<endPtr ){
55265 *(u16*)ptr = *(u16*)&ptr[2];
55266 ptr += 2;
55268 pPage->nCell--;
55269 put2byte(&data[hdr+3], pPage->nCell);
55270 pPage->nFree += 2;
55274 ** Insert a new cell on pPage at cell index "i". pCell points to the
55275 ** content of the cell.
55277 ** If the cell content will fit on the page, then put it there. If it
55278 ** will not fit, then make a copy of the cell content into pTemp if
55279 ** pTemp is not null. Regardless of pTemp, allocate a new entry
55280 ** in pPage->apOvfl[] and make it point to the cell content (either
55281 ** in pTemp or the original pCell) and also record its index.
55282 ** Allocating a new entry in pPage->aCell[] implies that
55283 ** pPage->nOverflow is incremented.
55285 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
55286 ** cell. The caller will overwrite them after this function returns. If
55287 ** nSkip is non-zero, then pCell may not point to an invalid memory location
55288 ** (but pCell+nSkip is always valid).
55290 static void insertCell(
55291 MemPage *pPage, /* Page into which we are copying */
55292 int i, /* New cell becomes the i-th cell of the page */
55293 u8 *pCell, /* Content of the new cell */
55294 int sz, /* Bytes of content in pCell */
55295 u8 *pTemp, /* Temp storage space for pCell, if needed */
55296 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
55297 int *pRC /* Read and write return code from here */
55299 int idx = 0; /* Where to write new cell content in data[] */
55300 int j; /* Loop counter */
55301 int end; /* First byte past the last cell pointer in data[] */
55302 int ins; /* Index in data[] where new cell pointer is inserted */
55303 int cellOffset; /* Address of first cell pointer in data[] */
55304 u8 *data; /* The content of the whole page */
55305 u8 *ptr; /* Used for moving information around in data[] */
55306 u8 *endPtr; /* End of the loop */
55308 int nSkip = (iChild ? 4 : 0);
55310 if( *pRC ) return;
55312 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
55313 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
55314 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
55315 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
55316 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55317 /* The cell should normally be sized correctly. However, when moving a
55318 ** malformed cell from a leaf page to an interior page, if the cell size
55319 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
55320 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
55321 ** the term after the || in the following assert(). */
55322 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
55323 if( pPage->nOverflow || sz+2>pPage->nFree ){
55324 if( pTemp ){
55325 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
55326 pCell = pTemp;
55328 if( iChild ){
55329 put4byte(pCell, iChild);
55331 j = pPage->nOverflow++;
55332 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
55333 pPage->apOvfl[j] = pCell;
55334 pPage->aiOvfl[j] = (u16)i;
55335 }else{
55336 int rc = sqlite3PagerWrite(pPage->pDbPage);
55337 if( rc!=SQLITE_OK ){
55338 *pRC = rc;
55339 return;
55341 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55342 data = pPage->aData;
55343 cellOffset = pPage->cellOffset;
55344 end = cellOffset + 2*pPage->nCell;
55345 ins = cellOffset + 2*i;
55346 rc = allocateSpace(pPage, sz, &idx);
55347 if( rc ){ *pRC = rc; return; }
55348 /* The allocateSpace() routine guarantees the following two properties
55349 ** if it returns success */
55350 assert( idx >= end+2 );
55351 assert( idx+sz <= (int)pPage->pBt->usableSize );
55352 pPage->nCell++;
55353 pPage->nFree -= (u16)(2 + sz);
55354 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
55355 if( iChild ){
55356 put4byte(&data[idx], iChild);
55358 ptr = &data[end];
55359 endPtr = &data[ins];
55360 assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
55361 while( ptr>endPtr ){
55362 *(u16*)ptr = *(u16*)&ptr[-2];
55363 ptr -= 2;
55365 put2byte(&data[ins], idx);
55366 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
55367 #ifndef SQLITE_OMIT_AUTOVACUUM
55368 if( pPage->pBt->autoVacuum ){
55369 /* The cell may contain a pointer to an overflow page. If so, write
55370 ** the entry for the overflow page into the pointer map.
55372 ptrmapPutOvflPtr(pPage, pCell, pRC);
55374 #endif
55379 ** Add a list of cells to a page. The page should be initially empty.
55380 ** The cells are guaranteed to fit on the page.
55382 static void assemblePage(
55383 MemPage *pPage, /* The page to be assemblied */
55384 int nCell, /* The number of cells to add to this page */
55385 u8 **apCell, /* Pointers to cell bodies */
55386 u16 *aSize /* Sizes of the cells */
55388 int i; /* Loop counter */
55389 u8 *pCellptr; /* Address of next cell pointer */
55390 int cellbody; /* Address of next cell body */
55391 u8 * const data = pPage->aData; /* Pointer to data for pPage */
55392 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
55393 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
55395 assert( pPage->nOverflow==0 );
55396 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55397 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
55398 && (int)MX_CELL(pPage->pBt)<=10921);
55399 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55401 /* Check that the page has just been zeroed by zeroPage() */
55402 assert( pPage->nCell==0 );
55403 assert( get2byteNotZero(&data[hdr+5])==nUsable );
55405 pCellptr = &pPage->aCellIdx[nCell*2];
55406 cellbody = nUsable;
55407 for(i=nCell-1; i>=0; i--){
55408 u16 sz = aSize[i];
55409 pCellptr -= 2;
55410 cellbody -= sz;
55411 put2byte(pCellptr, cellbody);
55412 memcpy(&data[cellbody], apCell[i], sz);
55414 put2byte(&data[hdr+3], nCell);
55415 put2byte(&data[hdr+5], cellbody);
55416 pPage->nFree -= (nCell*2 + nUsable - cellbody);
55417 pPage->nCell = (u16)nCell;
55421 ** The following parameters determine how many adjacent pages get involved
55422 ** in a balancing operation. NN is the number of neighbors on either side
55423 ** of the page that participate in the balancing operation. NB is the
55424 ** total number of pages that participate, including the target page and
55425 ** NN neighbors on either side.
55427 ** The minimum value of NN is 1 (of course). Increasing NN above 1
55428 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
55429 ** in exchange for a larger degradation in INSERT and UPDATE performance.
55430 ** The value of NN appears to give the best results overall.
55432 #define NN 1 /* Number of neighbors on either side of pPage */
55433 #define NB (NN*2+1) /* Total pages involved in the balance */
55436 #ifndef SQLITE_OMIT_QUICKBALANCE
55438 ** This version of balance() handles the common special case where
55439 ** a new entry is being inserted on the extreme right-end of the
55440 ** tree, in other words, when the new entry will become the largest
55441 ** entry in the tree.
55443 ** Instead of trying to balance the 3 right-most leaf pages, just add
55444 ** a new page to the right-hand side and put the one new entry in
55445 ** that page. This leaves the right side of the tree somewhat
55446 ** unbalanced. But odds are that we will be inserting new entries
55447 ** at the end soon afterwards so the nearly empty page will quickly
55448 ** fill up. On average.
55450 ** pPage is the leaf page which is the right-most page in the tree.
55451 ** pParent is its parent. pPage must have a single overflow entry
55452 ** which is also the right-most entry on the page.
55454 ** The pSpace buffer is used to store a temporary copy of the divider
55455 ** cell that will be inserted into pParent. Such a cell consists of a 4
55456 ** byte page number followed by a variable length integer. In other
55457 ** words, at most 13 bytes. Hence the pSpace buffer must be at
55458 ** least 13 bytes in size.
55460 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
55461 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
55462 MemPage *pNew; /* Newly allocated page */
55463 int rc; /* Return Code */
55464 Pgno pgnoNew; /* Page number of pNew */
55466 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55467 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55468 assert( pPage->nOverflow==1 );
55470 /* This error condition is now caught prior to reaching this function */
55471 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
55473 /* Allocate a new page. This page will become the right-sibling of
55474 ** pPage. Make the parent page writable, so that the new divider cell
55475 ** may be inserted. If both these operations are successful, proceed.
55477 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
55479 if( rc==SQLITE_OK ){
55481 u8 *pOut = &pSpace[4];
55482 u8 *pCell = pPage->apOvfl[0];
55483 u16 szCell = cellSizePtr(pPage, pCell);
55484 u8 *pStop;
55486 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
55487 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
55488 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
55489 assemblePage(pNew, 1, &pCell, &szCell);
55491 /* If this is an auto-vacuum database, update the pointer map
55492 ** with entries for the new page, and any pointer from the
55493 ** cell on the page to an overflow page. If either of these
55494 ** operations fails, the return code is set, but the contents
55495 ** of the parent page are still manipulated by thh code below.
55496 ** That is Ok, at this point the parent page is guaranteed to
55497 ** be marked as dirty. Returning an error code will cause a
55498 ** rollback, undoing any changes made to the parent page.
55500 if( ISAUTOVACUUM ){
55501 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
55502 if( szCell>pNew->minLocal ){
55503 ptrmapPutOvflPtr(pNew, pCell, &rc);
55507 /* Create a divider cell to insert into pParent. The divider cell
55508 ** consists of a 4-byte page number (the page number of pPage) and
55509 ** a variable length key value (which must be the same value as the
55510 ** largest key on pPage).
55512 ** To find the largest key value on pPage, first find the right-most
55513 ** cell on pPage. The first two fields of this cell are the
55514 ** record-length (a variable length integer at most 32-bits in size)
55515 ** and the key value (a variable length integer, may have any value).
55516 ** The first of the while(...) loops below skips over the record-length
55517 ** field. The second while(...) loop copies the key value from the
55518 ** cell on pPage into the pSpace buffer.
55520 pCell = findCell(pPage, pPage->nCell-1);
55521 pStop = &pCell[9];
55522 while( (*(pCell++)&0x80) && pCell<pStop );
55523 pStop = &pCell[9];
55524 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
55526 /* Insert the new divider cell into pParent. */
55527 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
55528 0, pPage->pgno, &rc);
55530 /* Set the right-child pointer of pParent to point to the new page. */
55531 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
55533 /* Release the reference to the new page. */
55534 releasePage(pNew);
55537 return rc;
55539 #endif /* SQLITE_OMIT_QUICKBALANCE */
55541 #if 0
55543 ** This function does not contribute anything to the operation of SQLite.
55544 ** it is sometimes activated temporarily while debugging code responsible
55545 ** for setting pointer-map entries.
55547 static int ptrmapCheckPages(MemPage **apPage, int nPage){
55548 int i, j;
55549 for(i=0; i<nPage; i++){
55550 Pgno n;
55551 u8 e;
55552 MemPage *pPage = apPage[i];
55553 BtShared *pBt = pPage->pBt;
55554 assert( pPage->isInit );
55556 for(j=0; j<pPage->nCell; j++){
55557 CellInfo info;
55558 u8 *z;
55560 z = findCell(pPage, j);
55561 btreeParseCellPtr(pPage, z, &info);
55562 if( info.iOverflow ){
55563 Pgno ovfl = get4byte(&z[info.iOverflow]);
55564 ptrmapGet(pBt, ovfl, &e, &n);
55565 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
55567 if( !pPage->leaf ){
55568 Pgno child = get4byte(z);
55569 ptrmapGet(pBt, child, &e, &n);
55570 assert( n==pPage->pgno && e==PTRMAP_BTREE );
55573 if( !pPage->leaf ){
55574 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55575 ptrmapGet(pBt, child, &e, &n);
55576 assert( n==pPage->pgno && e==PTRMAP_BTREE );
55579 return 1;
55581 #endif
55584 ** This function is used to copy the contents of the b-tree node stored
55585 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
55586 ** the pointer-map entries for each child page are updated so that the
55587 ** parent page stored in the pointer map is page pTo. If pFrom contained
55588 ** any cells with overflow page pointers, then the corresponding pointer
55589 ** map entries are also updated so that the parent page is page pTo.
55591 ** If pFrom is currently carrying any overflow cells (entries in the
55592 ** MemPage.apOvfl[] array), they are not copied to pTo.
55594 ** Before returning, page pTo is reinitialized using btreeInitPage().
55596 ** The performance of this function is not critical. It is only used by
55597 ** the balance_shallower() and balance_deeper() procedures, neither of
55598 ** which are called often under normal circumstances.
55600 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
55601 if( (*pRC)==SQLITE_OK ){
55602 BtShared * const pBt = pFrom->pBt;
55603 u8 * const aFrom = pFrom->aData;
55604 u8 * const aTo = pTo->aData;
55605 int const iFromHdr = pFrom->hdrOffset;
55606 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
55607 int rc;
55608 int iData;
55611 assert( pFrom->isInit );
55612 assert( pFrom->nFree>=iToHdr );
55613 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
55615 /* Copy the b-tree node content from page pFrom to page pTo. */
55616 iData = get2byte(&aFrom[iFromHdr+5]);
55617 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
55618 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
55620 /* Reinitialize page pTo so that the contents of the MemPage structure
55621 ** match the new data. The initialization of pTo can actually fail under
55622 ** fairly obscure circumstances, even though it is a copy of initialized
55623 ** page pFrom.
55625 pTo->isInit = 0;
55626 rc = btreeInitPage(pTo);
55627 if( rc!=SQLITE_OK ){
55628 *pRC = rc;
55629 return;
55632 /* If this is an auto-vacuum database, update the pointer-map entries
55633 ** for any b-tree or overflow pages that pTo now contains the pointers to.
55635 if( ISAUTOVACUUM ){
55636 *pRC = setChildPtrmaps(pTo);
55642 ** This routine redistributes cells on the iParentIdx'th child of pParent
55643 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
55644 ** same amount of free space. Usually a single sibling on either side of the
55645 ** page are used in the balancing, though both siblings might come from one
55646 ** side if the page is the first or last child of its parent. If the page
55647 ** has fewer than 2 siblings (something which can only happen if the page
55648 ** is a root page or a child of a root page) then all available siblings
55649 ** participate in the balancing.
55651 ** The number of siblings of the page might be increased or decreased by
55652 ** one or two in an effort to keep pages nearly full but not over full.
55654 ** Note that when this routine is called, some of the cells on the page
55655 ** might not actually be stored in MemPage.aData[]. This can happen
55656 ** if the page is overfull. This routine ensures that all cells allocated
55657 ** to the page and its siblings fit into MemPage.aData[] before returning.
55659 ** In the course of balancing the page and its siblings, cells may be
55660 ** inserted into or removed from the parent page (pParent). Doing so
55661 ** may cause the parent page to become overfull or underfull. If this
55662 ** happens, it is the responsibility of the caller to invoke the correct
55663 ** balancing routine to fix this problem (see the balance() routine).
55665 ** If this routine fails for any reason, it might leave the database
55666 ** in a corrupted state. So if this routine fails, the database should
55667 ** be rolled back.
55669 ** The third argument to this function, aOvflSpace, is a pointer to a
55670 ** buffer big enough to hold one page. If while inserting cells into the parent
55671 ** page (pParent) the parent page becomes overfull, this buffer is
55672 ** used to store the parent's overflow cells. Because this function inserts
55673 ** a maximum of four divider cells into the parent page, and the maximum
55674 ** size of a cell stored within an internal node is always less than 1/4
55675 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
55676 ** enough for all overflow cells.
55678 ** If aOvflSpace is set to a null pointer, this function returns
55679 ** SQLITE_NOMEM.
55681 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
55682 #pragma optimize("", off)
55683 #endif
55684 static int balance_nonroot(
55685 MemPage *pParent, /* Parent page of siblings being balanced */
55686 int iParentIdx, /* Index of "the page" in pParent */
55687 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
55688 int isRoot, /* True if pParent is a root-page */
55689 int bBulk /* True if this call is part of a bulk load */
55691 BtShared *pBt; /* The whole database */
55692 int nCell = 0; /* Number of cells in apCell[] */
55693 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
55694 int nNew = 0; /* Number of pages in apNew[] */
55695 int nOld; /* Number of pages in apOld[] */
55696 int i, j, k; /* Loop counters */
55697 int nxDiv; /* Next divider slot in pParent->aCell[] */
55698 int rc = SQLITE_OK; /* The return code */
55699 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
55700 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
55701 int usableSpace; /* Bytes in pPage beyond the header */
55702 int pageFlags; /* Value of pPage->aData[0] */
55703 int subtotal; /* Subtotal of bytes in cells on one page */
55704 int iSpace1 = 0; /* First unused byte of aSpace1[] */
55705 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
55706 int szScratch; /* Size of scratch memory requested */
55707 MemPage *apOld[NB]; /* pPage and up to two siblings */
55708 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
55709 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
55710 u8 *pRight; /* Location in parent of right-sibling pointer */
55711 u8 *apDiv[NB-1]; /* Divider cells in pParent */
55712 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
55713 int szNew[NB+2]; /* Combined size of cells place on i-th page */
55714 u8 **apCell = 0; /* All cells begin balanced */
55715 u16 *szCell; /* Local size of all cells in apCell[] */
55716 u8 *aSpace1; /* Space for copies of dividers cells */
55717 Pgno pgno; /* Temp var to store a page number in */
55719 pBt = pParent->pBt;
55720 assert( sqlite3_mutex_held(pBt->mutex) );
55721 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55723 #if 0
55724 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
55725 #endif
55727 /* At this point pParent may have at most one overflow cell. And if
55728 ** this overflow cell is present, it must be the cell with
55729 ** index iParentIdx. This scenario comes about when this function
55730 ** is called (indirectly) from sqlite3BtreeDelete().
55732 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
55733 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
55735 if( !aOvflSpace ){
55736 return SQLITE_NOMEM;
55739 /* Find the sibling pages to balance. Also locate the cells in pParent
55740 ** that divide the siblings. An attempt is made to find NN siblings on
55741 ** either side of pPage. More siblings are taken from one side, however,
55742 ** if there are fewer than NN siblings on the other side. If pParent
55743 ** has NB or fewer children then all children of pParent are taken.
55745 ** This loop also drops the divider cells from the parent page. This
55746 ** way, the remainder of the function does not have to deal with any
55747 ** overflow cells in the parent page, since if any existed they will
55748 ** have already been removed.
55750 i = pParent->nOverflow + pParent->nCell;
55751 if( i<2 ){
55752 nxDiv = 0;
55753 }else{
55754 assert( bBulk==0 || bBulk==1 );
55755 if( iParentIdx==0 ){
55756 nxDiv = 0;
55757 }else if( iParentIdx==i ){
55758 nxDiv = i-2+bBulk;
55759 }else{
55760 assert( bBulk==0 );
55761 nxDiv = iParentIdx-1;
55763 i = 2-bBulk;
55765 nOld = i+1;
55766 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
55767 pRight = &pParent->aData[pParent->hdrOffset+8];
55768 }else{
55769 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
55771 pgno = get4byte(pRight);
55772 while( 1 ){
55773 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
55774 if( rc ){
55775 memset(apOld, 0, (i+1)*sizeof(MemPage*));
55776 goto balance_cleanup;
55778 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
55779 if( (i--)==0 ) break;
55781 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
55782 apDiv[i] = pParent->apOvfl[0];
55783 pgno = get4byte(apDiv[i]);
55784 szNew[i] = cellSizePtr(pParent, apDiv[i]);
55785 pParent->nOverflow = 0;
55786 }else{
55787 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
55788 pgno = get4byte(apDiv[i]);
55789 szNew[i] = cellSizePtr(pParent, apDiv[i]);
55791 /* Drop the cell from the parent page. apDiv[i] still points to
55792 ** the cell within the parent, even though it has been dropped.
55793 ** This is safe because dropping a cell only overwrites the first
55794 ** four bytes of it, and this function does not need the first
55795 ** four bytes of the divider cell. So the pointer is safe to use
55796 ** later on.
55798 ** But not if we are in secure-delete mode. In secure-delete mode,
55799 ** the dropCell() routine will overwrite the entire cell with zeroes.
55800 ** In this case, temporarily copy the cell into the aOvflSpace[]
55801 ** buffer. It will be copied out again as soon as the aSpace[] buffer
55802 ** is allocated. */
55803 if( pBt->btsFlags & BTS_SECURE_DELETE ){
55804 int iOff;
55806 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
55807 if( (iOff+szNew[i])>(int)pBt->usableSize ){
55808 rc = SQLITE_CORRUPT_BKPT;
55809 memset(apOld, 0, (i+1)*sizeof(MemPage*));
55810 goto balance_cleanup;
55811 }else{
55812 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
55813 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
55816 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
55820 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
55821 ** alignment */
55822 nMaxCells = (nMaxCells + 3)&~3;
55825 ** Allocate space for memory structures
55827 k = pBt->pageSize + ROUND8(sizeof(MemPage));
55828 szScratch =
55829 nMaxCells*sizeof(u8*) /* apCell */
55830 + nMaxCells*sizeof(u16) /* szCell */
55831 + pBt->pageSize /* aSpace1 */
55832 + k*nOld; /* Page copies (apCopy) */
55833 apCell = sqlite3ScratchMalloc( szScratch );
55834 if( apCell==0 ){
55835 rc = SQLITE_NOMEM;
55836 goto balance_cleanup;
55838 szCell = (u16*)&apCell[nMaxCells];
55839 aSpace1 = (u8*)&szCell[nMaxCells];
55840 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
55843 ** Load pointers to all cells on sibling pages and the divider cells
55844 ** into the local apCell[] array. Make copies of the divider cells
55845 ** into space obtained from aSpace1[] and remove the divider cells
55846 ** from pParent.
55848 ** If the siblings are on leaf pages, then the child pointers of the
55849 ** divider cells are stripped from the cells before they are copied
55850 ** into aSpace1[]. In this way, all cells in apCell[] are without
55851 ** child pointers. If siblings are not leaves, then all cell in
55852 ** apCell[] include child pointers. Either way, all cells in apCell[]
55853 ** are alike.
55855 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
55856 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
55858 leafCorrection = apOld[0]->leaf*4;
55859 leafData = apOld[0]->hasData;
55860 for(i=0; i<nOld; i++){
55861 int limit;
55863 /* Before doing anything else, take a copy of the i'th original sibling
55864 ** The rest of this function will use data from the copies rather
55865 ** that the original pages since the original pages will be in the
55866 ** process of being overwritten. */
55867 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
55868 memcpy(pOld, apOld[i], sizeof(MemPage));
55869 pOld->aData = (void*)&pOld[1];
55870 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
55872 limit = pOld->nCell+pOld->nOverflow;
55873 if( pOld->nOverflow>0 ){
55874 for(j=0; j<limit; j++){
55875 assert( nCell<nMaxCells );
55876 apCell[nCell] = findOverflowCell(pOld, j);
55877 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55878 nCell++;
55880 }else{
55881 u8 *aData = pOld->aData;
55882 u16 maskPage = pOld->maskPage;
55883 u16 cellOffset = pOld->cellOffset;
55884 for(j=0; j<limit; j++){
55885 assert( nCell<nMaxCells );
55886 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
55887 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55888 nCell++;
55891 if( i<nOld-1 && !leafData){
55892 u16 sz = (u16)szNew[i];
55893 u8 *pTemp;
55894 assert( nCell<nMaxCells );
55895 szCell[nCell] = sz;
55896 pTemp = &aSpace1[iSpace1];
55897 iSpace1 += sz;
55898 assert( sz<=pBt->maxLocal+23 );
55899 assert( iSpace1 <= (int)pBt->pageSize );
55900 memcpy(pTemp, apDiv[i], sz);
55901 apCell[nCell] = pTemp+leafCorrection;
55902 assert( leafCorrection==0 || leafCorrection==4 );
55903 szCell[nCell] = szCell[nCell] - leafCorrection;
55904 if( !pOld->leaf ){
55905 assert( leafCorrection==0 );
55906 assert( pOld->hdrOffset==0 );
55907 /* The right pointer of the child page pOld becomes the left
55908 ** pointer of the divider cell */
55909 memcpy(apCell[nCell], &pOld->aData[8], 4);
55910 }else{
55911 assert( leafCorrection==4 );
55912 if( szCell[nCell]<4 ){
55913 /* Do not allow any cells smaller than 4 bytes. */
55914 szCell[nCell] = 4;
55917 nCell++;
55922 ** Figure out the number of pages needed to hold all nCell cells.
55923 ** Store this number in "k". Also compute szNew[] which is the total
55924 ** size of all cells on the i-th page and cntNew[] which is the index
55925 ** in apCell[] of the cell that divides page i from page i+1.
55926 ** cntNew[k] should equal nCell.
55928 ** Values computed by this block:
55930 ** k: The total number of sibling pages
55931 ** szNew[i]: Spaced used on the i-th sibling page.
55932 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
55933 ** the right of the i-th sibling page.
55934 ** usableSpace: Number of bytes of space available on each sibling.
55937 usableSpace = pBt->usableSize - 12 + leafCorrection;
55938 for(subtotal=k=i=0; i<nCell; i++){
55939 assert( i<nMaxCells );
55940 subtotal += szCell[i] + 2;
55941 if( subtotal > usableSpace ){
55942 szNew[k] = subtotal - szCell[i];
55943 cntNew[k] = i;
55944 if( leafData ){ i--; }
55945 subtotal = 0;
55946 k++;
55947 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
55950 szNew[k] = subtotal;
55951 cntNew[k] = nCell;
55952 k++;
55955 ** The packing computed by the previous block is biased toward the siblings
55956 ** on the left side. The left siblings are always nearly full, while the
55957 ** right-most sibling might be nearly empty. This block of code attempts
55958 ** to adjust the packing of siblings to get a better balance.
55960 ** This adjustment is more than an optimization. The packing above might
55961 ** be so out of balance as to be illegal. For example, the right-most
55962 ** sibling might be completely empty. This adjustment is not optional.
55964 for(i=k-1; i>0; i--){
55965 int szRight = szNew[i]; /* Size of sibling on the right */
55966 int szLeft = szNew[i-1]; /* Size of sibling on the left */
55967 int r; /* Index of right-most cell in left sibling */
55968 int d; /* Index of first cell to the left of right sibling */
55970 r = cntNew[i-1] - 1;
55971 d = r + 1 - leafData;
55972 assert( d<nMaxCells );
55973 assert( r<nMaxCells );
55974 while( szRight==0
55975 || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
55977 szRight += szCell[d] + 2;
55978 szLeft -= szCell[r] + 2;
55979 cntNew[i-1]--;
55980 r = cntNew[i-1] - 1;
55981 d = r + 1 - leafData;
55983 szNew[i] = szRight;
55984 szNew[i-1] = szLeft;
55987 /* Either we found one or more cells (cntnew[0])>0) or pPage is
55988 ** a virtual root page. A virtual root page is when the real root
55989 ** page is page 1 and we are the only child of that page.
55991 ** UPDATE: The assert() below is not necessarily true if the database
55992 ** file is corrupt. The corruption will be detected and reported later
55993 ** in this procedure so there is no need to act upon it now.
55995 #if 0
55996 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
55997 #endif
55999 TRACE(("BALANCE: old: %d %d %d ",
56000 apOld[0]->pgno,
56001 nOld>=2 ? apOld[1]->pgno : 0,
56002 nOld>=3 ? apOld[2]->pgno : 0
56006 ** Allocate k new pages. Reuse old pages where possible.
56008 if( apOld[0]->pgno<=1 ){
56009 rc = SQLITE_CORRUPT_BKPT;
56010 goto balance_cleanup;
56012 pageFlags = apOld[0]->aData[0];
56013 for(i=0; i<k; i++){
56014 MemPage *pNew;
56015 if( i<nOld ){
56016 pNew = apNew[i] = apOld[i];
56017 apOld[i] = 0;
56018 rc = sqlite3PagerWrite(pNew->pDbPage);
56019 nNew++;
56020 if( rc ) goto balance_cleanup;
56021 }else{
56022 assert( i>0 );
56023 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
56024 if( rc ) goto balance_cleanup;
56025 apNew[i] = pNew;
56026 nNew++;
56028 /* Set the pointer-map entry for the new sibling page. */
56029 if( ISAUTOVACUUM ){
56030 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
56031 if( rc!=SQLITE_OK ){
56032 goto balance_cleanup;
56038 /* Free any old pages that were not reused as new pages.
56040 while( i<nOld ){
56041 freePage(apOld[i], &rc);
56042 if( rc ) goto balance_cleanup;
56043 releasePage(apOld[i]);
56044 apOld[i] = 0;
56045 i++;
56049 ** Put the new pages in accending order. This helps to
56050 ** keep entries in the disk file in order so that a scan
56051 ** of the table is a linear scan through the file. That
56052 ** in turn helps the operating system to deliver pages
56053 ** from the disk more rapidly.
56055 ** An O(n^2) insertion sort algorithm is used, but since
56056 ** n is never more than NB (a small constant), that should
56057 ** not be a problem.
56059 ** When NB==3, this one optimization makes the database
56060 ** about 25% faster for large insertions and deletions.
56062 for(i=0; i<k-1; i++){
56063 int minV = apNew[i]->pgno;
56064 int minI = i;
56065 for(j=i+1; j<k; j++){
56066 if( apNew[j]->pgno<(unsigned)minV ){
56067 minI = j;
56068 minV = apNew[j]->pgno;
56071 if( minI>i ){
56072 MemPage *pT;
56073 pT = apNew[i];
56074 apNew[i] = apNew[minI];
56075 apNew[minI] = pT;
56078 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
56079 apNew[0]->pgno, szNew[0],
56080 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
56081 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
56082 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
56083 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
56085 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56086 put4byte(pRight, apNew[nNew-1]->pgno);
56089 ** Evenly distribute the data in apCell[] across the new pages.
56090 ** Insert divider cells into pParent as necessary.
56092 j = 0;
56093 for(i=0; i<nNew; i++){
56094 /* Assemble the new sibling page. */
56095 MemPage *pNew = apNew[i];
56096 assert( j<nMaxCells );
56097 zeroPage(pNew, pageFlags);
56098 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
56099 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
56100 assert( pNew->nOverflow==0 );
56102 j = cntNew[i];
56104 /* If the sibling page assembled above was not the right-most sibling,
56105 ** insert a divider cell into the parent page.
56107 assert( i<nNew-1 || j==nCell );
56108 if( j<nCell ){
56109 u8 *pCell;
56110 u8 *pTemp;
56111 int sz;
56113 assert( j<nMaxCells );
56114 pCell = apCell[j];
56115 sz = szCell[j] + leafCorrection;
56116 pTemp = &aOvflSpace[iOvflSpace];
56117 if( !pNew->leaf ){
56118 memcpy(&pNew->aData[8], pCell, 4);
56119 }else if( leafData ){
56120 /* If the tree is a leaf-data tree, and the siblings are leaves,
56121 ** then there is no divider cell in apCell[]. Instead, the divider
56122 ** cell consists of the integer key for the right-most cell of
56123 ** the sibling-page assembled above only.
56125 CellInfo info;
56126 j--;
56127 btreeParseCellPtr(pNew, apCell[j], &info);
56128 pCell = pTemp;
56129 sz = 4 + putVarint(&pCell[4], info.nKey);
56130 pTemp = 0;
56131 }else{
56132 pCell -= 4;
56133 /* Obscure case for non-leaf-data trees: If the cell at pCell was
56134 ** previously stored on a leaf node, and its reported size was 4
56135 ** bytes, then it may actually be smaller than this
56136 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
56137 ** any cell). But it is important to pass the correct size to
56138 ** insertCell(), so reparse the cell now.
56140 ** Note that this can never happen in an SQLite data file, as all
56141 ** cells are at least 4 bytes. It only happens in b-trees used
56142 ** to evaluate "IN (SELECT ...)" and similar clauses.
56144 if( szCell[j]==4 ){
56145 assert(leafCorrection==4);
56146 sz = cellSizePtr(pParent, pCell);
56149 iOvflSpace += sz;
56150 assert( sz<=pBt->maxLocal+23 );
56151 assert( iOvflSpace <= (int)pBt->pageSize );
56152 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
56153 if( rc!=SQLITE_OK ) goto balance_cleanup;
56154 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56156 j++;
56157 nxDiv++;
56160 assert( j==nCell );
56161 assert( nOld>0 );
56162 assert( nNew>0 );
56163 if( (pageFlags & PTF_LEAF)==0 ){
56164 u8 *zChild = &apCopy[nOld-1]->aData[8];
56165 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
56168 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
56169 /* The root page of the b-tree now contains no cells. The only sibling
56170 ** page is the right-child of the parent. Copy the contents of the
56171 ** child page into the parent, decreasing the overall height of the
56172 ** b-tree structure by one. This is described as the "balance-shallower"
56173 ** sub-algorithm in some documentation.
56175 ** If this is an auto-vacuum database, the call to copyNodeContent()
56176 ** sets all pointer-map entries corresponding to database image pages
56177 ** for which the pointer is stored within the content being copied.
56179 ** The second assert below verifies that the child page is defragmented
56180 ** (it must be, as it was just reconstructed using assemblePage()). This
56181 ** is important if the parent page happens to be page 1 of the database
56182 ** image. */
56183 assert( nNew==1 );
56184 assert( apNew[0]->nFree ==
56185 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
56187 copyNodeContent(apNew[0], pParent, &rc);
56188 freePage(apNew[0], &rc);
56189 }else if( ISAUTOVACUUM ){
56190 /* Fix the pointer-map entries for all the cells that were shifted around.
56191 ** There are several different types of pointer-map entries that need to
56192 ** be dealt with by this routine. Some of these have been set already, but
56193 ** many have not. The following is a summary:
56195 ** 1) The entries associated with new sibling pages that were not
56196 ** siblings when this function was called. These have already
56197 ** been set. We don't need to worry about old siblings that were
56198 ** moved to the free-list - the freePage() code has taken care
56199 ** of those.
56201 ** 2) The pointer-map entries associated with the first overflow
56202 ** page in any overflow chains used by new divider cells. These
56203 ** have also already been taken care of by the insertCell() code.
56205 ** 3) If the sibling pages are not leaves, then the child pages of
56206 ** cells stored on the sibling pages may need to be updated.
56208 ** 4) If the sibling pages are not internal intkey nodes, then any
56209 ** overflow pages used by these cells may need to be updated
56210 ** (internal intkey nodes never contain pointers to overflow pages).
56212 ** 5) If the sibling pages are not leaves, then the pointer-map
56213 ** entries for the right-child pages of each sibling may need
56214 ** to be updated.
56216 ** Cases 1 and 2 are dealt with above by other code. The next
56217 ** block deals with cases 3 and 4 and the one after that, case 5. Since
56218 ** setting a pointer map entry is a relatively expensive operation, this
56219 ** code only sets pointer map entries for child or overflow pages that have
56220 ** actually moved between pages. */
56221 MemPage *pNew = apNew[0];
56222 MemPage *pOld = apCopy[0];
56223 int nOverflow = pOld->nOverflow;
56224 int iNextOld = pOld->nCell + nOverflow;
56225 int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
56226 j = 0; /* Current 'old' sibling page */
56227 k = 0; /* Current 'new' sibling page */
56228 for(i=0; i<nCell; i++){
56229 int isDivider = 0;
56230 while( i==iNextOld ){
56231 /* Cell i is the cell immediately following the last cell on old
56232 ** sibling page j. If the siblings are not leaf pages of an
56233 ** intkey b-tree, then cell i was a divider cell. */
56234 assert( j+1 < ArraySize(apCopy) );
56235 assert( j+1 < nOld );
56236 pOld = apCopy[++j];
56237 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
56238 if( pOld->nOverflow ){
56239 nOverflow = pOld->nOverflow;
56240 iOverflow = i + !leafData + pOld->aiOvfl[0];
56242 isDivider = !leafData;
56245 assert(nOverflow>0 || iOverflow<i );
56246 assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
56247 assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
56248 if( i==iOverflow ){
56249 isDivider = 1;
56250 if( (--nOverflow)>0 ){
56251 iOverflow++;
56255 if( i==cntNew[k] ){
56256 /* Cell i is the cell immediately following the last cell on new
56257 ** sibling page k. If the siblings are not leaf pages of an
56258 ** intkey b-tree, then cell i is a divider cell. */
56259 pNew = apNew[++k];
56260 if( !leafData ) continue;
56262 assert( j<nOld );
56263 assert( k<nNew );
56265 /* If the cell was originally divider cell (and is not now) or
56266 ** an overflow cell, or if the cell was located on a different sibling
56267 ** page before the balancing, then the pointer map entries associated
56268 ** with any child or overflow pages need to be updated. */
56269 if( isDivider || pOld->pgno!=pNew->pgno ){
56270 if( !leafCorrection ){
56271 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
56273 if( szCell[i]>pNew->minLocal ){
56274 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
56279 if( !leafCorrection ){
56280 for(i=0; i<nNew; i++){
56281 u32 key = get4byte(&apNew[i]->aData[8]);
56282 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
56286 #if 0
56287 /* The ptrmapCheckPages() contains assert() statements that verify that
56288 ** all pointer map pages are set correctly. This is helpful while
56289 ** debugging. This is usually disabled because a corrupt database may
56290 ** cause an assert() statement to fail. */
56291 ptrmapCheckPages(apNew, nNew);
56292 ptrmapCheckPages(&pParent, 1);
56293 #endif
56296 assert( pParent->isInit );
56297 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
56298 nOld, nNew, nCell));
56301 ** Cleanup before returning.
56303 balance_cleanup:
56304 sqlite3ScratchFree(apCell);
56305 for(i=0; i<nOld; i++){
56306 releasePage(apOld[i]);
56308 for(i=0; i<nNew; i++){
56309 releasePage(apNew[i]);
56312 return rc;
56314 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
56315 #pragma optimize("", on)
56316 #endif
56320 ** This function is called when the root page of a b-tree structure is
56321 ** overfull (has one or more overflow pages).
56323 ** A new child page is allocated and the contents of the current root
56324 ** page, including overflow cells, are copied into the child. The root
56325 ** page is then overwritten to make it an empty page with the right-child
56326 ** pointer pointing to the new page.
56328 ** Before returning, all pointer-map entries corresponding to pages
56329 ** that the new child-page now contains pointers to are updated. The
56330 ** entry corresponding to the new right-child pointer of the root
56331 ** page is also updated.
56333 ** If successful, *ppChild is set to contain a reference to the child
56334 ** page and SQLITE_OK is returned. In this case the caller is required
56335 ** to call releasePage() on *ppChild exactly once. If an error occurs,
56336 ** an error code is returned and *ppChild is set to 0.
56338 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
56339 int rc; /* Return value from subprocedures */
56340 MemPage *pChild = 0; /* Pointer to a new child page */
56341 Pgno pgnoChild = 0; /* Page number of the new child page */
56342 BtShared *pBt = pRoot->pBt; /* The BTree */
56344 assert( pRoot->nOverflow>0 );
56345 assert( sqlite3_mutex_held(pBt->mutex) );
56347 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
56348 ** page that will become the new right-child of pPage. Copy the contents
56349 ** of the node stored on pRoot into the new child page.
56351 rc = sqlite3PagerWrite(pRoot->pDbPage);
56352 if( rc==SQLITE_OK ){
56353 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
56354 copyNodeContent(pRoot, pChild, &rc);
56355 if( ISAUTOVACUUM ){
56356 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
56359 if( rc ){
56360 *ppChild = 0;
56361 releasePage(pChild);
56362 return rc;
56364 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
56365 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
56366 assert( pChild->nCell==pRoot->nCell );
56368 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
56370 /* Copy the overflow cells from pRoot to pChild */
56371 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
56372 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
56373 memcpy(pChild->apOvfl, pRoot->apOvfl,
56374 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
56375 pChild->nOverflow = pRoot->nOverflow;
56377 /* Zero the contents of pRoot. Then install pChild as the right-child. */
56378 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
56379 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
56381 *ppChild = pChild;
56382 return SQLITE_OK;
56386 ** The page that pCur currently points to has just been modified in
56387 ** some way. This function figures out if this modification means the
56388 ** tree needs to be balanced, and if so calls the appropriate balancing
56389 ** routine. Balancing routines are:
56391 ** balance_quick()
56392 ** balance_deeper()
56393 ** balance_nonroot()
56395 static int balance(BtCursor *pCur){
56396 int rc = SQLITE_OK;
56397 const int nMin = pCur->pBt->usableSize * 2 / 3;
56398 u8 aBalanceQuickSpace[13];
56399 u8 *pFree = 0;
56401 TESTONLY( int balance_quick_called = 0 );
56402 TESTONLY( int balance_deeper_called = 0 );
56404 do {
56405 int iPage = pCur->iPage;
56406 MemPage *pPage = pCur->apPage[iPage];
56408 if( iPage==0 ){
56409 if( pPage->nOverflow ){
56410 /* The root page of the b-tree is overfull. In this case call the
56411 ** balance_deeper() function to create a new child for the root-page
56412 ** and copy the current contents of the root-page to it. The
56413 ** next iteration of the do-loop will balance the child page.
56415 assert( (balance_deeper_called++)==0 );
56416 rc = balance_deeper(pPage, &pCur->apPage[1]);
56417 if( rc==SQLITE_OK ){
56418 pCur->iPage = 1;
56419 pCur->aiIdx[0] = 0;
56420 pCur->aiIdx[1] = 0;
56421 assert( pCur->apPage[1]->nOverflow );
56423 }else{
56424 break;
56426 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
56427 break;
56428 }else{
56429 MemPage * const pParent = pCur->apPage[iPage-1];
56430 int const iIdx = pCur->aiIdx[iPage-1];
56432 rc = sqlite3PagerWrite(pParent->pDbPage);
56433 if( rc==SQLITE_OK ){
56434 #ifndef SQLITE_OMIT_QUICKBALANCE
56435 if( pPage->hasData
56436 && pPage->nOverflow==1
56437 && pPage->aiOvfl[0]==pPage->nCell
56438 && pParent->pgno!=1
56439 && pParent->nCell==iIdx
56441 /* Call balance_quick() to create a new sibling of pPage on which
56442 ** to store the overflow cell. balance_quick() inserts a new cell
56443 ** into pParent, which may cause pParent overflow. If this
56444 ** happens, the next interation of the do-loop will balance pParent
56445 ** use either balance_nonroot() or balance_deeper(). Until this
56446 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
56447 ** buffer.
56449 ** The purpose of the following assert() is to check that only a
56450 ** single call to balance_quick() is made for each call to this
56451 ** function. If this were not verified, a subtle bug involving reuse
56452 ** of the aBalanceQuickSpace[] might sneak in.
56454 assert( (balance_quick_called++)==0 );
56455 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
56456 }else
56457 #endif
56459 /* In this case, call balance_nonroot() to redistribute cells
56460 ** between pPage and up to 2 of its sibling pages. This involves
56461 ** modifying the contents of pParent, which may cause pParent to
56462 ** become overfull or underfull. The next iteration of the do-loop
56463 ** will balance the parent page to correct this.
56465 ** If the parent page becomes overfull, the overflow cell or cells
56466 ** are stored in the pSpace buffer allocated immediately below.
56467 ** A subsequent iteration of the do-loop will deal with this by
56468 ** calling balance_nonroot() (balance_deeper() may be called first,
56469 ** but it doesn't deal with overflow cells - just moves them to a
56470 ** different page). Once this subsequent call to balance_nonroot()
56471 ** has completed, it is safe to release the pSpace buffer used by
56472 ** the previous call, as the overflow cell data will have been
56473 ** copied either into the body of a database page or into the new
56474 ** pSpace buffer passed to the latter call to balance_nonroot().
56476 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
56477 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
56478 if( pFree ){
56479 /* If pFree is not NULL, it points to the pSpace buffer used
56480 ** by a previous call to balance_nonroot(). Its contents are
56481 ** now stored either on real database pages or within the
56482 ** new pSpace buffer, so it may be safely freed here. */
56483 sqlite3PageFree(pFree);
56486 /* The pSpace buffer will be freed after the next call to
56487 ** balance_nonroot(), or just before this function returns, whichever
56488 ** comes first. */
56489 pFree = pSpace;
56493 pPage->nOverflow = 0;
56495 /* The next iteration of the do-loop balances the parent page. */
56496 releasePage(pPage);
56497 pCur->iPage--;
56499 }while( rc==SQLITE_OK );
56501 if( pFree ){
56502 sqlite3PageFree(pFree);
56504 return rc;
56509 ** Insert a new record into the BTree. The key is given by (pKey,nKey)
56510 ** and the data is given by (pData,nData). The cursor is used only to
56511 ** define what table the record should be inserted into. The cursor
56512 ** is left pointing at a random location.
56514 ** For an INTKEY table, only the nKey value of the key is used. pKey is
56515 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
56517 ** If the seekResult parameter is non-zero, then a successful call to
56518 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
56519 ** been performed. seekResult is the search result returned (a negative
56520 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
56521 ** a positive value if pCur points at an etry that is larger than
56522 ** (pKey, nKey)).
56524 ** If the seekResult parameter is non-zero, then the caller guarantees that
56525 ** cursor pCur is pointing at the existing copy of a row that is to be
56526 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
56527 ** point to any entry or to no entry at all and so this function has to seek
56528 ** the cursor before the new key can be inserted.
56530 SQLITE_PRIVATE int sqlite3BtreeInsert(
56531 BtCursor *pCur, /* Insert data into the table of this cursor */
56532 const void *pKey, i64 nKey, /* The key of the new record */
56533 const void *pData, int nData, /* The data of the new record */
56534 int nZero, /* Number of extra 0 bytes to append to data */
56535 int appendBias, /* True if this is likely an append */
56536 int seekResult /* Result of prior MovetoUnpacked() call */
56538 int rc;
56539 int loc = seekResult; /* -1: before desired location +1: after */
56540 int szNew = 0;
56541 int idx;
56542 MemPage *pPage;
56543 Btree *p = pCur->pBtree;
56544 BtShared *pBt = p->pBt;
56545 unsigned char *oldCell;
56546 unsigned char *newCell = 0;
56548 if( pCur->eState==CURSOR_FAULT ){
56549 assert( pCur->skipNext!=SQLITE_OK );
56550 return pCur->skipNext;
56553 assert( cursorHoldsMutex(pCur) );
56554 assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
56555 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
56556 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56558 /* Assert that the caller has been consistent. If this cursor was opened
56559 ** expecting an index b-tree, then the caller should be inserting blob
56560 ** keys with no associated data. If the cursor was opened expecting an
56561 ** intkey table, the caller should be inserting integer keys with a
56562 ** blob of associated data. */
56563 assert( (pKey==0)==(pCur->pKeyInfo==0) );
56565 /* Save the positions of any other cursors open on this table.
56567 ** In some cases, the call to btreeMoveto() below is a no-op. For
56568 ** example, when inserting data into a table with auto-generated integer
56569 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
56570 ** integer key to use. It then calls this function to actually insert the
56571 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
56572 ** that the cursor is already where it needs to be and returns without
56573 ** doing any work. To avoid thwarting these optimizations, it is important
56574 ** not to clear the cursor here.
56576 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56577 if( rc ) return rc;
56579 /* If this is an insert into a table b-tree, invalidate any incrblob
56580 ** cursors open on the row being replaced (assuming this is a replace
56581 ** operation - if it is not, the following is a no-op). */
56582 if( pCur->pKeyInfo==0 ){
56583 invalidateIncrblobCursors(p, nKey, 0);
56586 if( !loc ){
56587 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
56588 if( rc ) return rc;
56590 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
56592 pPage = pCur->apPage[pCur->iPage];
56593 assert( pPage->intKey || nKey>=0 );
56594 assert( pPage->leaf || !pPage->intKey );
56596 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
56597 pCur->pgnoRoot, nKey, nData, pPage->pgno,
56598 loc==0 ? "overwrite" : "new entry"));
56599 assert( pPage->isInit );
56600 allocateTempSpace(pBt);
56601 newCell = pBt->pTmpSpace;
56602 if( newCell==0 ) return SQLITE_NOMEM;
56603 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
56604 if( rc ) goto end_insert;
56605 assert( szNew==cellSizePtr(pPage, newCell) );
56606 assert( szNew <= MX_CELL_SIZE(pBt) );
56607 idx = pCur->aiIdx[pCur->iPage];
56608 if( loc==0 ){
56609 u16 szOld;
56610 assert( idx<pPage->nCell );
56611 rc = sqlite3PagerWrite(pPage->pDbPage);
56612 if( rc ){
56613 goto end_insert;
56615 oldCell = findCell(pPage, idx);
56616 if( !pPage->leaf ){
56617 memcpy(newCell, oldCell, 4);
56619 szOld = cellSizePtr(pPage, oldCell);
56620 rc = clearCell(pPage, oldCell);
56621 dropCell(pPage, idx, szOld, &rc);
56622 if( rc ) goto end_insert;
56623 }else if( loc<0 && pPage->nCell>0 ){
56624 assert( pPage->leaf );
56625 idx = ++pCur->aiIdx[pCur->iPage];
56626 }else{
56627 assert( pPage->leaf );
56629 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
56630 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
56632 /* If no error has occurred and pPage has an overflow cell, call balance()
56633 ** to redistribute the cells within the tree. Since balance() may move
56634 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
56635 ** variables.
56637 ** Previous versions of SQLite called moveToRoot() to move the cursor
56638 ** back to the root page as balance() used to invalidate the contents
56639 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
56640 ** set the cursor state to "invalid". This makes common insert operations
56641 ** slightly faster.
56643 ** There is a subtle but important optimization here too. When inserting
56644 ** multiple records into an intkey b-tree using a single cursor (as can
56645 ** happen while processing an "INSERT INTO ... SELECT" statement), it
56646 ** is advantageous to leave the cursor pointing to the last entry in
56647 ** the b-tree if possible. If the cursor is left pointing to the last
56648 ** entry in the table, and the next row inserted has an integer key
56649 ** larger than the largest existing key, it is possible to insert the
56650 ** row without seeking the cursor. This can be a big performance boost.
56652 pCur->info.nSize = 0;
56653 pCur->validNKey = 0;
56654 if( rc==SQLITE_OK && pPage->nOverflow ){
56655 rc = balance(pCur);
56657 /* Must make sure nOverflow is reset to zero even if the balance()
56658 ** fails. Internal data structure corruption will result otherwise.
56659 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
56660 ** from trying to save the current position of the cursor. */
56661 pCur->apPage[pCur->iPage]->nOverflow = 0;
56662 pCur->eState = CURSOR_INVALID;
56664 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
56666 end_insert:
56667 return rc;
56671 ** Delete the entry that the cursor is pointing to. The cursor
56672 ** is left pointing at a arbitrary location.
56674 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
56675 Btree *p = pCur->pBtree;
56676 BtShared *pBt = p->pBt;
56677 int rc; /* Return code */
56678 MemPage *pPage; /* Page to delete cell from */
56679 unsigned char *pCell; /* Pointer to cell to delete */
56680 int iCellIdx; /* Index of cell to delete */
56681 int iCellDepth; /* Depth of node containing pCell */
56683 assert( cursorHoldsMutex(pCur) );
56684 assert( pBt->inTransaction==TRANS_WRITE );
56685 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56686 assert( pCur->wrFlag );
56687 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56688 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
56690 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
56691 || NEVER(pCur->eState!=CURSOR_VALID)
56693 return SQLITE_ERROR; /* Something has gone awry. */
56696 iCellDepth = pCur->iPage;
56697 iCellIdx = pCur->aiIdx[iCellDepth];
56698 pPage = pCur->apPage[iCellDepth];
56699 pCell = findCell(pPage, iCellIdx);
56701 /* If the page containing the entry to delete is not a leaf page, move
56702 ** the cursor to the largest entry in the tree that is smaller than
56703 ** the entry being deleted. This cell will replace the cell being deleted
56704 ** from the internal node. The 'previous' entry is used for this instead
56705 ** of the 'next' entry, as the previous entry is always a part of the
56706 ** sub-tree headed by the child page of the cell being deleted. This makes
56707 ** balancing the tree following the delete operation easier. */
56708 if( !pPage->leaf ){
56709 int notUsed;
56710 rc = sqlite3BtreePrevious(pCur, &notUsed);
56711 if( rc ) return rc;
56714 /* Save the positions of any other cursors open on this table before
56715 ** making any modifications. Make the page containing the entry to be
56716 ** deleted writable. Then free any overflow pages associated with the
56717 ** entry and finally remove the cell itself from within the page.
56719 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56720 if( rc ) return rc;
56722 /* If this is a delete operation to remove a row from a table b-tree,
56723 ** invalidate any incrblob cursors open on the row being deleted. */
56724 if( pCur->pKeyInfo==0 ){
56725 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
56728 rc = sqlite3PagerWrite(pPage->pDbPage);
56729 if( rc ) return rc;
56730 rc = clearCell(pPage, pCell);
56731 dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
56732 if( rc ) return rc;
56734 /* If the cell deleted was not located on a leaf page, then the cursor
56735 ** is currently pointing to the largest entry in the sub-tree headed
56736 ** by the child-page of the cell that was just deleted from an internal
56737 ** node. The cell from the leaf node needs to be moved to the internal
56738 ** node to replace the deleted cell. */
56739 if( !pPage->leaf ){
56740 MemPage *pLeaf = pCur->apPage[pCur->iPage];
56741 int nCell;
56742 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
56743 unsigned char *pTmp;
56745 pCell = findCell(pLeaf, pLeaf->nCell-1);
56746 nCell = cellSizePtr(pLeaf, pCell);
56747 assert( MX_CELL_SIZE(pBt) >= nCell );
56749 allocateTempSpace(pBt);
56750 pTmp = pBt->pTmpSpace;
56752 rc = sqlite3PagerWrite(pLeaf->pDbPage);
56753 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
56754 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
56755 if( rc ) return rc;
56758 /* Balance the tree. If the entry deleted was located on a leaf page,
56759 ** then the cursor still points to that page. In this case the first
56760 ** call to balance() repairs the tree, and the if(...) condition is
56761 ** never true.
56763 ** Otherwise, if the entry deleted was on an internal node page, then
56764 ** pCur is pointing to the leaf page from which a cell was removed to
56765 ** replace the cell deleted from the internal node. This is slightly
56766 ** tricky as the leaf node may be underfull, and the internal node may
56767 ** be either under or overfull. In this case run the balancing algorithm
56768 ** on the leaf node first. If the balance proceeds far enough up the
56769 ** tree that we can be sure that any problem in the internal node has
56770 ** been corrected, so be it. Otherwise, after balancing the leaf node,
56771 ** walk the cursor up the tree to the internal node and balance it as
56772 ** well. */
56773 rc = balance(pCur);
56774 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
56775 while( pCur->iPage>iCellDepth ){
56776 releasePage(pCur->apPage[pCur->iPage--]);
56778 rc = balance(pCur);
56781 if( rc==SQLITE_OK ){
56782 moveToRoot(pCur);
56784 return rc;
56788 ** Create a new BTree table. Write into *piTable the page
56789 ** number for the root page of the new table.
56791 ** The type of type is determined by the flags parameter. Only the
56792 ** following values of flags are currently in use. Other values for
56793 ** flags might not work:
56795 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
56796 ** BTREE_ZERODATA Used for SQL indices
56798 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
56799 BtShared *pBt = p->pBt;
56800 MemPage *pRoot;
56801 Pgno pgnoRoot;
56802 int rc;
56803 int ptfFlags; /* Page-type flage for the root page of new table */
56805 assert( sqlite3BtreeHoldsMutex(p) );
56806 assert( pBt->inTransaction==TRANS_WRITE );
56807 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56809 #ifdef SQLITE_OMIT_AUTOVACUUM
56810 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56811 if( rc ){
56812 return rc;
56814 #else
56815 if( pBt->autoVacuum ){
56816 Pgno pgnoMove; /* Move a page here to make room for the root-page */
56817 MemPage *pPageMove; /* The page to move to. */
56819 /* Creating a new table may probably require moving an existing database
56820 ** to make room for the new tables root page. In case this page turns
56821 ** out to be an overflow page, delete all overflow page-map caches
56822 ** held by open cursors.
56824 invalidateAllOverflowCache(pBt);
56826 /* Read the value of meta[3] from the database to determine where the
56827 ** root page of the new table should go. meta[3] is the largest root-page
56828 ** created so far, so the new root-page is (meta[3]+1).
56830 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
56831 pgnoRoot++;
56833 /* The new root-page may not be allocated on a pointer-map page, or the
56834 ** PENDING_BYTE page.
56836 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
56837 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
56838 pgnoRoot++;
56840 assert( pgnoRoot>=3 );
56842 /* Allocate a page. The page that currently resides at pgnoRoot will
56843 ** be moved to the allocated page (unless the allocated page happens
56844 ** to reside at pgnoRoot).
56846 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
56847 if( rc!=SQLITE_OK ){
56848 return rc;
56851 if( pgnoMove!=pgnoRoot ){
56852 /* pgnoRoot is the page that will be used for the root-page of
56853 ** the new table (assuming an error did not occur). But we were
56854 ** allocated pgnoMove. If required (i.e. if it was not allocated
56855 ** by extending the file), the current page at position pgnoMove
56856 ** is already journaled.
56858 u8 eType = 0;
56859 Pgno iPtrPage = 0;
56861 /* Save the positions of any open cursors. This is required in
56862 ** case they are holding a reference to an xFetch reference
56863 ** corresponding to page pgnoRoot. */
56864 rc = saveAllCursors(pBt, 0, 0);
56865 releasePage(pPageMove);
56866 if( rc!=SQLITE_OK ){
56867 return rc;
56870 /* Move the page currently at pgnoRoot to pgnoMove. */
56871 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
56872 if( rc!=SQLITE_OK ){
56873 return rc;
56875 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
56876 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
56877 rc = SQLITE_CORRUPT_BKPT;
56879 if( rc!=SQLITE_OK ){
56880 releasePage(pRoot);
56881 return rc;
56883 assert( eType!=PTRMAP_ROOTPAGE );
56884 assert( eType!=PTRMAP_FREEPAGE );
56885 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
56886 releasePage(pRoot);
56888 /* Obtain the page at pgnoRoot */
56889 if( rc!=SQLITE_OK ){
56890 return rc;
56892 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
56893 if( rc!=SQLITE_OK ){
56894 return rc;
56896 rc = sqlite3PagerWrite(pRoot->pDbPage);
56897 if( rc!=SQLITE_OK ){
56898 releasePage(pRoot);
56899 return rc;
56901 }else{
56902 pRoot = pPageMove;
56905 /* Update the pointer-map and meta-data with the new root-page number. */
56906 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
56907 if( rc ){
56908 releasePage(pRoot);
56909 return rc;
56912 /* When the new root page was allocated, page 1 was made writable in
56913 ** order either to increase the database filesize, or to decrement the
56914 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
56916 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
56917 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
56918 if( NEVER(rc) ){
56919 releasePage(pRoot);
56920 return rc;
56923 }else{
56924 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56925 if( rc ) return rc;
56927 #endif
56928 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
56929 if( createTabFlags & BTREE_INTKEY ){
56930 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
56931 }else{
56932 ptfFlags = PTF_ZERODATA | PTF_LEAF;
56934 zeroPage(pRoot, ptfFlags);
56935 sqlite3PagerUnref(pRoot->pDbPage);
56936 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
56937 *piTable = (int)pgnoRoot;
56938 return SQLITE_OK;
56940 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
56941 int rc;
56942 sqlite3BtreeEnter(p);
56943 rc = btreeCreateTable(p, piTable, flags);
56944 sqlite3BtreeLeave(p);
56945 return rc;
56949 ** Erase the given database page and all its children. Return
56950 ** the page to the freelist.
56952 static int clearDatabasePage(
56953 BtShared *pBt, /* The BTree that contains the table */
56954 Pgno pgno, /* Page number to clear */
56955 int freePageFlag, /* Deallocate page if true */
56956 int *pnChange /* Add number of Cells freed to this counter */
56958 MemPage *pPage;
56959 int rc;
56960 unsigned char *pCell;
56961 int i;
56963 assert( sqlite3_mutex_held(pBt->mutex) );
56964 if( pgno>btreePagecount(pBt) ){
56965 return SQLITE_CORRUPT_BKPT;
56968 rc = getAndInitPage(pBt, pgno, &pPage, 0);
56969 if( rc ) return rc;
56970 for(i=0; i<pPage->nCell; i++){
56971 pCell = findCell(pPage, i);
56972 if( !pPage->leaf ){
56973 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
56974 if( rc ) goto cleardatabasepage_out;
56976 rc = clearCell(pPage, pCell);
56977 if( rc ) goto cleardatabasepage_out;
56979 if( !pPage->leaf ){
56980 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
56981 if( rc ) goto cleardatabasepage_out;
56982 }else if( pnChange ){
56983 assert( pPage->intKey );
56984 *pnChange += pPage->nCell;
56986 if( freePageFlag ){
56987 freePage(pPage, &rc);
56988 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
56989 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
56992 cleardatabasepage_out:
56993 releasePage(pPage);
56994 return rc;
56998 ** Delete all information from a single table in the database. iTable is
56999 ** the page number of the root of the table. After this routine returns,
57000 ** the root page is empty, but still exists.
57002 ** This routine will fail with SQLITE_LOCKED if there are any open
57003 ** read cursors on the table. Open write cursors are moved to the
57004 ** root of the table.
57006 ** If pnChange is not NULL, then table iTable must be an intkey table. The
57007 ** integer value pointed to by pnChange is incremented by the number of
57008 ** entries in the table.
57010 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
57011 int rc;
57012 BtShared *pBt = p->pBt;
57013 sqlite3BtreeEnter(p);
57014 assert( p->inTrans==TRANS_WRITE );
57016 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
57018 if( SQLITE_OK==rc ){
57019 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
57020 ** is the root of a table b-tree - if it is not, the following call is
57021 ** a no-op). */
57022 invalidateIncrblobCursors(p, 0, 1);
57023 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
57025 sqlite3BtreeLeave(p);
57026 return rc;
57030 ** Erase all information in a table and add the root of the table to
57031 ** the freelist. Except, the root of the principle table (the one on
57032 ** page 1) is never added to the freelist.
57034 ** This routine will fail with SQLITE_LOCKED if there are any open
57035 ** cursors on the table.
57037 ** If AUTOVACUUM is enabled and the page at iTable is not the last
57038 ** root page in the database file, then the last root page
57039 ** in the database file is moved into the slot formerly occupied by
57040 ** iTable and that last slot formerly occupied by the last root page
57041 ** is added to the freelist instead of iTable. In this say, all
57042 ** root pages are kept at the beginning of the database file, which
57043 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
57044 ** page number that used to be the last root page in the file before
57045 ** the move. If no page gets moved, *piMoved is set to 0.
57046 ** The last root page is recorded in meta[3] and the value of
57047 ** meta[3] is updated by this procedure.
57049 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
57050 int rc;
57051 MemPage *pPage = 0;
57052 BtShared *pBt = p->pBt;
57054 assert( sqlite3BtreeHoldsMutex(p) );
57055 assert( p->inTrans==TRANS_WRITE );
57057 /* It is illegal to drop a table if any cursors are open on the
57058 ** database. This is because in auto-vacuum mode the backend may
57059 ** need to move another root-page to fill a gap left by the deleted
57060 ** root page. If an open cursor was using this page a problem would
57061 ** occur.
57063 ** This error is caught long before control reaches this point.
57065 if( NEVER(pBt->pCursor) ){
57066 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
57067 return SQLITE_LOCKED_SHAREDCACHE;
57070 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
57071 if( rc ) return rc;
57072 rc = sqlite3BtreeClearTable(p, iTable, 0);
57073 if( rc ){
57074 releasePage(pPage);
57075 return rc;
57078 *piMoved = 0;
57080 if( iTable>1 ){
57081 #ifdef SQLITE_OMIT_AUTOVACUUM
57082 freePage(pPage, &rc);
57083 releasePage(pPage);
57084 #else
57085 if( pBt->autoVacuum ){
57086 Pgno maxRootPgno;
57087 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
57089 if( iTable==maxRootPgno ){
57090 /* If the table being dropped is the table with the largest root-page
57091 ** number in the database, put the root page on the free list.
57093 freePage(pPage, &rc);
57094 releasePage(pPage);
57095 if( rc!=SQLITE_OK ){
57096 return rc;
57098 }else{
57099 /* The table being dropped does not have the largest root-page
57100 ** number in the database. So move the page that does into the
57101 ** gap left by the deleted root-page.
57103 MemPage *pMove;
57104 releasePage(pPage);
57105 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
57106 if( rc!=SQLITE_OK ){
57107 return rc;
57109 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
57110 releasePage(pMove);
57111 if( rc!=SQLITE_OK ){
57112 return rc;
57114 pMove = 0;
57115 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
57116 freePage(pMove, &rc);
57117 releasePage(pMove);
57118 if( rc!=SQLITE_OK ){
57119 return rc;
57121 *piMoved = maxRootPgno;
57124 /* Set the new 'max-root-page' value in the database header. This
57125 ** is the old value less one, less one more if that happens to
57126 ** be a root-page number, less one again if that is the
57127 ** PENDING_BYTE_PAGE.
57129 maxRootPgno--;
57130 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
57131 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
57132 maxRootPgno--;
57134 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
57136 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
57137 }else{
57138 freePage(pPage, &rc);
57139 releasePage(pPage);
57141 #endif
57142 }else{
57143 /* If sqlite3BtreeDropTable was called on page 1.
57144 ** This really never should happen except in a corrupt
57145 ** database.
57147 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
57148 releasePage(pPage);
57150 return rc;
57152 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
57153 int rc;
57154 sqlite3BtreeEnter(p);
57155 rc = btreeDropTable(p, iTable, piMoved);
57156 sqlite3BtreeLeave(p);
57157 return rc;
57162 ** This function may only be called if the b-tree connection already
57163 ** has a read or write transaction open on the database.
57165 ** Read the meta-information out of a database file. Meta[0]
57166 ** is the number of free pages currently in the database. Meta[1]
57167 ** through meta[15] are available for use by higher layers. Meta[0]
57168 ** is read-only, the others are read/write.
57170 ** The schema layer numbers meta values differently. At the schema
57171 ** layer (and the SetCookie and ReadCookie opcodes) the number of
57172 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
57174 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
57175 BtShared *pBt = p->pBt;
57177 sqlite3BtreeEnter(p);
57178 assert( p->inTrans>TRANS_NONE );
57179 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
57180 assert( pBt->pPage1 );
57181 assert( idx>=0 && idx<=15 );
57183 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
57185 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
57186 ** database, mark the database as read-only. */
57187 #ifdef SQLITE_OMIT_AUTOVACUUM
57188 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
57189 pBt->btsFlags |= BTS_READ_ONLY;
57191 #endif
57193 sqlite3BtreeLeave(p);
57197 ** Write meta-information back into the database. Meta[0] is
57198 ** read-only and may not be written.
57200 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
57201 BtShared *pBt = p->pBt;
57202 unsigned char *pP1;
57203 int rc;
57204 assert( idx>=1 && idx<=15 );
57205 sqlite3BtreeEnter(p);
57206 assert( p->inTrans==TRANS_WRITE );
57207 assert( pBt->pPage1!=0 );
57208 pP1 = pBt->pPage1->aData;
57209 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
57210 if( rc==SQLITE_OK ){
57211 put4byte(&pP1[36 + idx*4], iMeta);
57212 #ifndef SQLITE_OMIT_AUTOVACUUM
57213 if( idx==BTREE_INCR_VACUUM ){
57214 assert( pBt->autoVacuum || iMeta==0 );
57215 assert( iMeta==0 || iMeta==1 );
57216 pBt->incrVacuum = (u8)iMeta;
57218 #endif
57220 sqlite3BtreeLeave(p);
57221 return rc;
57224 #ifndef SQLITE_OMIT_BTREECOUNT
57226 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
57227 ** number of entries in the b-tree and write the result to *pnEntry.
57229 ** SQLITE_OK is returned if the operation is successfully executed.
57230 ** Otherwise, if an error is encountered (i.e. an IO error or database
57231 ** corruption) an SQLite error code is returned.
57233 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
57234 i64 nEntry = 0; /* Value to return in *pnEntry */
57235 int rc; /* Return code */
57237 if( pCur->pgnoRoot==0 ){
57238 *pnEntry = 0;
57239 return SQLITE_OK;
57241 rc = moveToRoot(pCur);
57243 /* Unless an error occurs, the following loop runs one iteration for each
57244 ** page in the B-Tree structure (not including overflow pages).
57246 while( rc==SQLITE_OK ){
57247 int iIdx; /* Index of child node in parent */
57248 MemPage *pPage; /* Current page of the b-tree */
57250 /* If this is a leaf page or the tree is not an int-key tree, then
57251 ** this page contains countable entries. Increment the entry counter
57252 ** accordingly.
57254 pPage = pCur->apPage[pCur->iPage];
57255 if( pPage->leaf || !pPage->intKey ){
57256 nEntry += pPage->nCell;
57259 /* pPage is a leaf node. This loop navigates the cursor so that it
57260 ** points to the first interior cell that it points to the parent of
57261 ** the next page in the tree that has not yet been visited. The
57262 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
57263 ** of the page, or to the number of cells in the page if the next page
57264 ** to visit is the right-child of its parent.
57266 ** If all pages in the tree have been visited, return SQLITE_OK to the
57267 ** caller.
57269 if( pPage->leaf ){
57270 do {
57271 if( pCur->iPage==0 ){
57272 /* All pages of the b-tree have been visited. Return successfully. */
57273 *pnEntry = nEntry;
57274 return SQLITE_OK;
57276 moveToParent(pCur);
57277 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
57279 pCur->aiIdx[pCur->iPage]++;
57280 pPage = pCur->apPage[pCur->iPage];
57283 /* Descend to the child node of the cell that the cursor currently
57284 ** points at. This is the right-child if (iIdx==pPage->nCell).
57286 iIdx = pCur->aiIdx[pCur->iPage];
57287 if( iIdx==pPage->nCell ){
57288 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
57289 }else{
57290 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
57294 /* An error has occurred. Return an error code. */
57295 return rc;
57297 #endif
57300 ** Return the pager associated with a BTree. This routine is used for
57301 ** testing and debugging only.
57303 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
57304 return p->pBt->pPager;
57307 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57309 ** Append a message to the error message string.
57311 static void checkAppendMsg(
57312 IntegrityCk *pCheck,
57313 char *zMsg1,
57314 const char *zFormat,
57317 va_list ap;
57318 if( !pCheck->mxErr ) return;
57319 pCheck->mxErr--;
57320 pCheck->nErr++;
57321 va_start(ap, zFormat);
57322 if( pCheck->errMsg.nChar ){
57323 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
57325 if( zMsg1 ){
57326 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
57328 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
57329 va_end(ap);
57330 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
57331 pCheck->mallocFailed = 1;
57334 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57336 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57339 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
57340 ** corresponds to page iPg is already set.
57342 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
57343 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
57344 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
57348 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
57350 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
57351 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
57352 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
57357 ** Add 1 to the reference count for page iPage. If this is the second
57358 ** reference to the page, add an error message to pCheck->zErrMsg.
57359 ** Return 1 if there are 2 ore more references to the page and 0 if
57360 ** if this is the first reference to the page.
57362 ** Also check that the page number is in bounds.
57364 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
57365 if( iPage==0 ) return 1;
57366 if( iPage>pCheck->nPage ){
57367 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
57368 return 1;
57370 if( getPageReferenced(pCheck, iPage) ){
57371 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
57372 return 1;
57374 setPageReferenced(pCheck, iPage);
57375 return 0;
57378 #ifndef SQLITE_OMIT_AUTOVACUUM
57380 ** Check that the entry in the pointer-map for page iChild maps to
57381 ** page iParent, pointer type ptrType. If not, append an error message
57382 ** to pCheck.
57384 static void checkPtrmap(
57385 IntegrityCk *pCheck, /* Integrity check context */
57386 Pgno iChild, /* Child page number */
57387 u8 eType, /* Expected pointer map type */
57388 Pgno iParent, /* Expected pointer map parent page number */
57389 char *zContext /* Context description (used for error msg) */
57391 int rc;
57392 u8 ePtrmapType;
57393 Pgno iPtrmapParent;
57395 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
57396 if( rc!=SQLITE_OK ){
57397 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
57398 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
57399 return;
57402 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
57403 checkAppendMsg(pCheck, zContext,
57404 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
57405 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
57408 #endif
57411 ** Check the integrity of the freelist or of an overflow page list.
57412 ** Verify that the number of pages on the list is N.
57414 static void checkList(
57415 IntegrityCk *pCheck, /* Integrity checking context */
57416 int isFreeList, /* True for a freelist. False for overflow page list */
57417 int iPage, /* Page number for first page in the list */
57418 int N, /* Expected number of pages in the list */
57419 char *zContext /* Context for error messages */
57421 int i;
57422 int expected = N;
57423 int iFirst = iPage;
57424 while( N-- > 0 && pCheck->mxErr ){
57425 DbPage *pOvflPage;
57426 unsigned char *pOvflData;
57427 if( iPage<1 ){
57428 checkAppendMsg(pCheck, zContext,
57429 "%d of %d pages missing from overflow list starting at %d",
57430 N+1, expected, iFirst);
57431 break;
57433 if( checkRef(pCheck, iPage, zContext) ) break;
57434 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
57435 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
57436 break;
57438 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
57439 if( isFreeList ){
57440 int n = get4byte(&pOvflData[4]);
57441 #ifndef SQLITE_OMIT_AUTOVACUUM
57442 if( pCheck->pBt->autoVacuum ){
57443 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
57445 #endif
57446 if( n>(int)pCheck->pBt->usableSize/4-2 ){
57447 checkAppendMsg(pCheck, zContext,
57448 "freelist leaf count too big on page %d", iPage);
57449 N--;
57450 }else{
57451 for(i=0; i<n; i++){
57452 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
57453 #ifndef SQLITE_OMIT_AUTOVACUUM
57454 if( pCheck->pBt->autoVacuum ){
57455 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
57457 #endif
57458 checkRef(pCheck, iFreePage, zContext);
57460 N -= n;
57463 #ifndef SQLITE_OMIT_AUTOVACUUM
57464 else{
57465 /* If this database supports auto-vacuum and iPage is not the last
57466 ** page in this overflow list, check that the pointer-map entry for
57467 ** the following page matches iPage.
57469 if( pCheck->pBt->autoVacuum && N>0 ){
57470 i = get4byte(pOvflData);
57471 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
57474 #endif
57475 iPage = get4byte(pOvflData);
57476 sqlite3PagerUnref(pOvflPage);
57479 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57481 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57483 ** Do various sanity checks on a single page of a tree. Return
57484 ** the tree depth. Root pages return 0. Parents of root pages
57485 ** return 1, and so forth.
57487 ** These checks are done:
57489 ** 1. Make sure that cells and freeblocks do not overlap
57490 ** but combine to completely cover the page.
57491 ** NO 2. Make sure cell keys are in order.
57492 ** NO 3. Make sure no key is less than or equal to zLowerBound.
57493 ** NO 4. Make sure no key is greater than or equal to zUpperBound.
57494 ** 5. Check the integrity of overflow pages.
57495 ** 6. Recursively call checkTreePage on all children.
57496 ** 7. Verify that the depth of all children is the same.
57497 ** 8. Make sure this page is at least 33% full or else it is
57498 ** the root of the tree.
57500 static int checkTreePage(
57501 IntegrityCk *pCheck, /* Context for the sanity check */
57502 int iPage, /* Page number of the page to check */
57503 char *zParentContext, /* Parent context */
57504 i64 *pnParentMinKey,
57505 i64 *pnParentMaxKey
57507 MemPage *pPage;
57508 int i, rc, depth, d2, pgno, cnt;
57509 int hdr, cellStart;
57510 int nCell;
57511 u8 *data;
57512 BtShared *pBt;
57513 int usableSize;
57514 char zContext[100];
57515 char *hit = 0;
57516 i64 nMinKey = 0;
57517 i64 nMaxKey = 0;
57519 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
57521 /* Check that the page exists
57523 pBt = pCheck->pBt;
57524 usableSize = pBt->usableSize;
57525 if( iPage==0 ) return 0;
57526 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
57527 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
57528 checkAppendMsg(pCheck, zContext,
57529 "unable to get the page. error code=%d", rc);
57530 return 0;
57533 /* Clear MemPage.isInit to make sure the corruption detection code in
57534 ** btreeInitPage() is executed. */
57535 pPage->isInit = 0;
57536 if( (rc = btreeInitPage(pPage))!=0 ){
57537 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
57538 checkAppendMsg(pCheck, zContext,
57539 "btreeInitPage() returns error code %d", rc);
57540 releasePage(pPage);
57541 return 0;
57544 /* Check out all the cells.
57546 depth = 0;
57547 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
57548 u8 *pCell;
57549 u32 sz;
57550 CellInfo info;
57552 /* Check payload overflow pages
57554 sqlite3_snprintf(sizeof(zContext), zContext,
57555 "On tree page %d cell %d: ", iPage, i);
57556 pCell = findCell(pPage,i);
57557 btreeParseCellPtr(pPage, pCell, &info);
57558 sz = info.nData;
57559 if( !pPage->intKey ) sz += (int)info.nKey;
57560 /* For intKey pages, check that the keys are in order.
57562 else if( i==0 ) nMinKey = nMaxKey = info.nKey;
57563 else{
57564 if( info.nKey <= nMaxKey ){
57565 checkAppendMsg(pCheck, zContext,
57566 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
57568 nMaxKey = info.nKey;
57570 assert( sz==info.nPayload );
57571 if( (sz>info.nLocal)
57572 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
57574 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
57575 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
57576 #ifndef SQLITE_OMIT_AUTOVACUUM
57577 if( pBt->autoVacuum ){
57578 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
57580 #endif
57581 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
57584 /* Check sanity of left child page.
57586 if( !pPage->leaf ){
57587 pgno = get4byte(pCell);
57588 #ifndef SQLITE_OMIT_AUTOVACUUM
57589 if( pBt->autoVacuum ){
57590 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57592 #endif
57593 d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
57594 if( i>0 && d2!=depth ){
57595 checkAppendMsg(pCheck, zContext, "Child page depth differs");
57597 depth = d2;
57601 if( !pPage->leaf ){
57602 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57603 sqlite3_snprintf(sizeof(zContext), zContext,
57604 "On page %d at right child: ", iPage);
57605 #ifndef SQLITE_OMIT_AUTOVACUUM
57606 if( pBt->autoVacuum ){
57607 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57609 #endif
57610 checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
57613 /* For intKey leaf pages, check that the min/max keys are in order
57614 ** with any left/parent/right pages.
57616 if( pPage->leaf && pPage->intKey ){
57617 /* if we are a left child page */
57618 if( pnParentMinKey ){
57619 /* if we are the left most child page */
57620 if( !pnParentMaxKey ){
57621 if( nMaxKey > *pnParentMinKey ){
57622 checkAppendMsg(pCheck, zContext,
57623 "Rowid %lld out of order (max larger than parent min of %lld)",
57624 nMaxKey, *pnParentMinKey);
57626 }else{
57627 if( nMinKey <= *pnParentMinKey ){
57628 checkAppendMsg(pCheck, zContext,
57629 "Rowid %lld out of order (min less than parent min of %lld)",
57630 nMinKey, *pnParentMinKey);
57632 if( nMaxKey > *pnParentMaxKey ){
57633 checkAppendMsg(pCheck, zContext,
57634 "Rowid %lld out of order (max larger than parent max of %lld)",
57635 nMaxKey, *pnParentMaxKey);
57637 *pnParentMinKey = nMaxKey;
57639 /* else if we're a right child page */
57640 } else if( pnParentMaxKey ){
57641 if( nMinKey <= *pnParentMaxKey ){
57642 checkAppendMsg(pCheck, zContext,
57643 "Rowid %lld out of order (min less than parent max of %lld)",
57644 nMinKey, *pnParentMaxKey);
57649 /* Check for complete coverage of the page
57651 data = pPage->aData;
57652 hdr = pPage->hdrOffset;
57653 hit = sqlite3PageMalloc( pBt->pageSize );
57654 if( hit==0 ){
57655 pCheck->mallocFailed = 1;
57656 }else{
57657 int contentOffset = get2byteNotZero(&data[hdr+5]);
57658 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
57659 memset(hit+contentOffset, 0, usableSize-contentOffset);
57660 memset(hit, 1, contentOffset);
57661 nCell = get2byte(&data[hdr+3]);
57662 cellStart = hdr + 12 - 4*pPage->leaf;
57663 for(i=0; i<nCell; i++){
57664 int pc = get2byte(&data[cellStart+i*2]);
57665 u32 size = 65536;
57666 int j;
57667 if( pc<=usableSize-4 ){
57668 size = cellSizePtr(pPage, &data[pc]);
57670 if( (int)(pc+size-1)>=usableSize ){
57671 checkAppendMsg(pCheck, 0,
57672 "Corruption detected in cell %d on page %d",i,iPage);
57673 }else{
57674 for(j=pc+size-1; j>=pc; j--) hit[j]++;
57677 i = get2byte(&data[hdr+1]);
57678 while( i>0 ){
57679 int size, j;
57680 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
57681 size = get2byte(&data[i+2]);
57682 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
57683 for(j=i+size-1; j>=i; j--) hit[j]++;
57684 j = get2byte(&data[i]);
57685 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
57686 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
57687 i = j;
57689 for(i=cnt=0; i<usableSize; i++){
57690 if( hit[i]==0 ){
57691 cnt++;
57692 }else if( hit[i]>1 ){
57693 checkAppendMsg(pCheck, 0,
57694 "Multiple uses for byte %d of page %d", i, iPage);
57695 break;
57698 if( cnt!=data[hdr+7] ){
57699 checkAppendMsg(pCheck, 0,
57700 "Fragmentation of %d bytes reported as %d on page %d",
57701 cnt, data[hdr+7], iPage);
57704 sqlite3PageFree(hit);
57705 releasePage(pPage);
57706 return depth+1;
57708 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57710 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57712 ** This routine does a complete check of the given BTree file. aRoot[] is
57713 ** an array of pages numbers were each page number is the root page of
57714 ** a table. nRoot is the number of entries in aRoot.
57716 ** A read-only or read-write transaction must be opened before calling
57717 ** this function.
57719 ** Write the number of error seen in *pnErr. Except for some memory
57720 ** allocation errors, an error message held in memory obtained from
57721 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
57722 ** returned. If a memory allocation error occurs, NULL is returned.
57724 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
57725 Btree *p, /* The btree to be checked */
57726 int *aRoot, /* An array of root pages numbers for individual trees */
57727 int nRoot, /* Number of entries in aRoot[] */
57728 int mxErr, /* Stop reporting errors after this many */
57729 int *pnErr /* Write number of errors seen to this variable */
57731 Pgno i;
57732 int nRef;
57733 IntegrityCk sCheck;
57734 BtShared *pBt = p->pBt;
57735 char zErr[100];
57737 sqlite3BtreeEnter(p);
57738 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
57739 nRef = sqlite3PagerRefcount(pBt->pPager);
57740 sCheck.pBt = pBt;
57741 sCheck.pPager = pBt->pPager;
57742 sCheck.nPage = btreePagecount(sCheck.pBt);
57743 sCheck.mxErr = mxErr;
57744 sCheck.nErr = 0;
57745 sCheck.mallocFailed = 0;
57746 *pnErr = 0;
57747 if( sCheck.nPage==0 ){
57748 sqlite3BtreeLeave(p);
57749 return 0;
57752 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
57753 if( !sCheck.aPgRef ){
57754 *pnErr = 1;
57755 sqlite3BtreeLeave(p);
57756 return 0;
57758 i = PENDING_BYTE_PAGE(pBt);
57759 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
57760 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
57761 sCheck.errMsg.useMalloc = 2;
57763 /* Check the integrity of the freelist
57765 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
57766 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
57768 /* Check all the tables.
57770 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
57771 if( aRoot[i]==0 ) continue;
57772 #ifndef SQLITE_OMIT_AUTOVACUUM
57773 if( pBt->autoVacuum && aRoot[i]>1 ){
57774 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
57776 #endif
57777 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
57780 /* Make sure every page in the file is referenced
57782 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
57783 #ifdef SQLITE_OMIT_AUTOVACUUM
57784 if( getPageReferenced(&sCheck, i)==0 ){
57785 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57787 #else
57788 /* If the database supports auto-vacuum, make sure no tables contain
57789 ** references to pointer-map pages.
57791 if( getPageReferenced(&sCheck, i)==0 &&
57792 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
57793 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57795 if( getPageReferenced(&sCheck, i)!=0 &&
57796 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
57797 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
57799 #endif
57802 /* Make sure this analysis did not leave any unref() pages.
57803 ** This is an internal consistency check; an integrity check
57804 ** of the integrity check.
57806 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
57807 checkAppendMsg(&sCheck, 0,
57808 "Outstanding page count goes from %d to %d during this analysis",
57809 nRef, sqlite3PagerRefcount(pBt->pPager)
57813 /* Clean up and report errors.
57815 sqlite3BtreeLeave(p);
57816 sqlite3_free(sCheck.aPgRef);
57817 if( sCheck.mallocFailed ){
57818 sqlite3StrAccumReset(&sCheck.errMsg);
57819 *pnErr = sCheck.nErr+1;
57820 return 0;
57822 *pnErr = sCheck.nErr;
57823 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
57824 return sqlite3StrAccumFinish(&sCheck.errMsg);
57826 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57829 ** Return the full pathname of the underlying database file. Return
57830 ** an empty string if the database is in-memory or a TEMP database.
57832 ** The pager filename is invariant as long as the pager is
57833 ** open so it is safe to access without the BtShared mutex.
57835 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
57836 assert( p->pBt->pPager!=0 );
57837 return sqlite3PagerFilename(p->pBt->pPager, 1);
57841 ** Return the pathname of the journal file for this database. The return
57842 ** value of this routine is the same regardless of whether the journal file
57843 ** has been created or not.
57845 ** The pager journal filename is invariant as long as the pager is
57846 ** open so it is safe to access without the BtShared mutex.
57848 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
57849 assert( p->pBt->pPager!=0 );
57850 return sqlite3PagerJournalname(p->pBt->pPager);
57854 ** Return non-zero if a transaction is active.
57856 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
57857 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
57858 return (p && (p->inTrans==TRANS_WRITE));
57861 #ifndef SQLITE_OMIT_WAL
57863 ** Run a checkpoint on the Btree passed as the first argument.
57865 ** Return SQLITE_LOCKED if this or any other connection has an open
57866 ** transaction on the shared-cache the argument Btree is connected to.
57868 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
57870 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
57871 int rc = SQLITE_OK;
57872 if( p ){
57873 BtShared *pBt = p->pBt;
57874 sqlite3BtreeEnter(p);
57875 if( pBt->inTransaction!=TRANS_NONE ){
57876 rc = SQLITE_LOCKED;
57877 }else{
57878 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
57880 sqlite3BtreeLeave(p);
57882 return rc;
57884 #endif
57887 ** Return non-zero if a read (or write) transaction is active.
57889 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
57890 assert( p );
57891 assert( sqlite3_mutex_held(p->db->mutex) );
57892 return p->inTrans!=TRANS_NONE;
57895 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
57896 assert( p );
57897 assert( sqlite3_mutex_held(p->db->mutex) );
57898 return p->nBackup!=0;
57902 ** This function returns a pointer to a blob of memory associated with
57903 ** a single shared-btree. The memory is used by client code for its own
57904 ** purposes (for example, to store a high-level schema associated with
57905 ** the shared-btree). The btree layer manages reference counting issues.
57907 ** The first time this is called on a shared-btree, nBytes bytes of memory
57908 ** are allocated, zeroed, and returned to the caller. For each subsequent
57909 ** call the nBytes parameter is ignored and a pointer to the same blob
57910 ** of memory returned.
57912 ** If the nBytes parameter is 0 and the blob of memory has not yet been
57913 ** allocated, a null pointer is returned. If the blob has already been
57914 ** allocated, it is returned as normal.
57916 ** Just before the shared-btree is closed, the function passed as the
57917 ** xFree argument when the memory allocation was made is invoked on the
57918 ** blob of allocated memory. The xFree function should not call sqlite3_free()
57919 ** on the memory, the btree layer does that.
57921 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
57922 BtShared *pBt = p->pBt;
57923 sqlite3BtreeEnter(p);
57924 if( !pBt->pSchema && nBytes ){
57925 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
57926 pBt->xFreeSchema = xFree;
57928 sqlite3BtreeLeave(p);
57929 return pBt->pSchema;
57933 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
57934 ** btree as the argument handle holds an exclusive lock on the
57935 ** sqlite_master table. Otherwise SQLITE_OK.
57937 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
57938 int rc;
57939 assert( sqlite3_mutex_held(p->db->mutex) );
57940 sqlite3BtreeEnter(p);
57941 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
57942 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
57943 sqlite3BtreeLeave(p);
57944 return rc;
57948 #ifndef SQLITE_OMIT_SHARED_CACHE
57950 ** Obtain a lock on the table whose root page is iTab. The
57951 ** lock is a write lock if isWritelock is true or a read lock
57952 ** if it is false.
57954 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
57955 int rc = SQLITE_OK;
57956 assert( p->inTrans!=TRANS_NONE );
57957 if( p->sharable ){
57958 u8 lockType = READ_LOCK + isWriteLock;
57959 assert( READ_LOCK+1==WRITE_LOCK );
57960 assert( isWriteLock==0 || isWriteLock==1 );
57962 sqlite3BtreeEnter(p);
57963 rc = querySharedCacheTableLock(p, iTab, lockType);
57964 if( rc==SQLITE_OK ){
57965 rc = setSharedCacheTableLock(p, iTab, lockType);
57967 sqlite3BtreeLeave(p);
57969 return rc;
57971 #endif
57973 #ifndef SQLITE_OMIT_INCRBLOB
57975 ** Argument pCsr must be a cursor opened for writing on an
57976 ** INTKEY table currently pointing at a valid table entry.
57977 ** This function modifies the data stored as part of that entry.
57979 ** Only the data content may only be modified, it is not possible to
57980 ** change the length of the data stored. If this function is called with
57981 ** parameters that attempt to write past the end of the existing data,
57982 ** no modifications are made and SQLITE_CORRUPT is returned.
57984 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
57985 int rc;
57986 assert( cursorHoldsMutex(pCsr) );
57987 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
57988 assert( pCsr->isIncrblobHandle );
57990 rc = restoreCursorPosition(pCsr);
57991 if( rc!=SQLITE_OK ){
57992 return rc;
57994 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
57995 if( pCsr->eState!=CURSOR_VALID ){
57996 return SQLITE_ABORT;
57999 /* Save the positions of all other cursors open on this table. This is
58000 ** required in case any of them are holding references to an xFetch
58001 ** version of the b-tree page modified by the accessPayload call below.
58003 ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
58004 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
58005 ** saveAllCursors can only return SQLITE_OK.
58007 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
58008 assert( rc==SQLITE_OK );
58010 /* Check some assumptions:
58011 ** (a) the cursor is open for writing,
58012 ** (b) there is a read/write transaction open,
58013 ** (c) the connection holds a write-lock on the table (if required),
58014 ** (d) there are no conflicting read-locks, and
58015 ** (e) the cursor points at a valid row of an intKey table.
58017 if( !pCsr->wrFlag ){
58018 return SQLITE_READONLY;
58020 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
58021 && pCsr->pBt->inTransaction==TRANS_WRITE );
58022 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
58023 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
58024 assert( pCsr->apPage[pCsr->iPage]->intKey );
58026 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
58030 ** Set a flag on this cursor to cache the locations of pages from the
58031 ** overflow list for the current row. This is used by cursors opened
58032 ** for incremental blob IO only.
58034 ** This function sets a flag only. The actual page location cache
58035 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
58036 ** accessPayload() (the worker function for sqlite3BtreeData() and
58037 ** sqlite3BtreePutData()).
58039 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
58040 assert( cursorHoldsMutex(pCur) );
58041 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
58042 invalidateOverflowCache(pCur);
58043 pCur->isIncrblobHandle = 1;
58045 #endif
58048 ** Set both the "read version" (single byte at byte offset 18) and
58049 ** "write version" (single byte at byte offset 19) fields in the database
58050 ** header to iVersion.
58052 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
58053 BtShared *pBt = pBtree->pBt;
58054 int rc; /* Return code */
58056 assert( iVersion==1 || iVersion==2 );
58058 /* If setting the version fields to 1, do not automatically open the
58059 ** WAL connection, even if the version fields are currently set to 2.
58061 pBt->btsFlags &= ~BTS_NO_WAL;
58062 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
58064 rc = sqlite3BtreeBeginTrans(pBtree, 0);
58065 if( rc==SQLITE_OK ){
58066 u8 *aData = pBt->pPage1->aData;
58067 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
58068 rc = sqlite3BtreeBeginTrans(pBtree, 2);
58069 if( rc==SQLITE_OK ){
58070 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58071 if( rc==SQLITE_OK ){
58072 aData[18] = (u8)iVersion;
58073 aData[19] = (u8)iVersion;
58079 pBt->btsFlags &= ~BTS_NO_WAL;
58080 return rc;
58084 ** set the mask of hint flags for cursor pCsr. Currently the only valid
58085 ** values are 0 and BTREE_BULKLOAD.
58087 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
58088 assert( mask==BTREE_BULKLOAD || mask==0 );
58089 pCsr->hints = mask;
58092 /************** End of btree.c ***********************************************/
58093 /************** Begin file backup.c ******************************************/
58095 ** 2009 January 28
58097 ** The author disclaims copyright to this source code. In place of
58098 ** a legal notice, here is a blessing:
58100 ** May you do good and not evil.
58101 ** May you find forgiveness for yourself and forgive others.
58102 ** May you share freely, never taking more than you give.
58104 *************************************************************************
58105 ** This file contains the implementation of the sqlite3_backup_XXX()
58106 ** API functions and the related features.
58110 ** Structure allocated for each backup operation.
58112 struct sqlite3_backup {
58113 sqlite3* pDestDb; /* Destination database handle */
58114 Btree *pDest; /* Destination b-tree file */
58115 u32 iDestSchema; /* Original schema cookie in destination */
58116 int bDestLocked; /* True once a write-transaction is open on pDest */
58118 Pgno iNext; /* Page number of the next source page to copy */
58119 sqlite3* pSrcDb; /* Source database handle */
58120 Btree *pSrc; /* Source b-tree file */
58122 int rc; /* Backup process error code */
58124 /* These two variables are set by every call to backup_step(). They are
58125 ** read by calls to backup_remaining() and backup_pagecount().
58127 Pgno nRemaining; /* Number of pages left to copy */
58128 Pgno nPagecount; /* Total number of pages to copy */
58130 int isAttached; /* True once backup has been registered with pager */
58131 sqlite3_backup *pNext; /* Next backup associated with source pager */
58135 ** THREAD SAFETY NOTES:
58137 ** Once it has been created using backup_init(), a single sqlite3_backup
58138 ** structure may be accessed via two groups of thread-safe entry points:
58140 ** * Via the sqlite3_backup_XXX() API function backup_step() and
58141 ** backup_finish(). Both these functions obtain the source database
58142 ** handle mutex and the mutex associated with the source BtShared
58143 ** structure, in that order.
58145 ** * Via the BackupUpdate() and BackupRestart() functions, which are
58146 ** invoked by the pager layer to report various state changes in
58147 ** the page cache associated with the source database. The mutex
58148 ** associated with the source database BtShared structure will always
58149 ** be held when either of these functions are invoked.
58151 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
58152 ** backup_pagecount() are not thread-safe functions. If they are called
58153 ** while some other thread is calling backup_step() or backup_finish(),
58154 ** the values returned may be invalid. There is no way for a call to
58155 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
58156 ** or backup_pagecount().
58158 ** Depending on the SQLite configuration, the database handles and/or
58159 ** the Btree objects may have their own mutexes that require locking.
58160 ** Non-sharable Btrees (in-memory databases for example), do not have
58161 ** associated mutexes.
58165 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
58166 ** in connection handle pDb. If such a database cannot be found, return
58167 ** a NULL pointer and write an error message to pErrorDb.
58169 ** If the "temp" database is requested, it may need to be opened by this
58170 ** function. If an error occurs while doing so, return 0 and write an
58171 ** error message to pErrorDb.
58173 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
58174 int i = sqlite3FindDbName(pDb, zDb);
58176 if( i==1 ){
58177 Parse *pParse;
58178 int rc = 0;
58179 pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
58180 if( pParse==0 ){
58181 sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
58182 rc = SQLITE_NOMEM;
58183 }else{
58184 pParse->db = pDb;
58185 if( sqlite3OpenTempDatabase(pParse) ){
58186 sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
58187 rc = SQLITE_ERROR;
58189 sqlite3DbFree(pErrorDb, pParse->zErrMsg);
58190 sqlite3StackFree(pErrorDb, pParse);
58192 if( rc ){
58193 return 0;
58197 if( i<0 ){
58198 sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
58199 return 0;
58202 return pDb->aDb[i].pBt;
58206 ** Attempt to set the page size of the destination to match the page size
58207 ** of the source.
58209 static int setDestPgsz(sqlite3_backup *p){
58210 int rc;
58211 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
58212 return rc;
58216 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
58217 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
58218 ** a pointer to the new sqlite3_backup object.
58220 ** If an error occurs, NULL is returned and an error code and error message
58221 ** stored in database handle pDestDb.
58223 SQLITE_API sqlite3_backup *sqlite3_backup_init(
58224 sqlite3* pDestDb, /* Database to write to */
58225 const char *zDestDb, /* Name of database within pDestDb */
58226 sqlite3* pSrcDb, /* Database connection to read from */
58227 const char *zSrcDb /* Name of database within pSrcDb */
58229 sqlite3_backup *p; /* Value to return */
58231 /* Lock the source database handle. The destination database
58232 ** handle is not locked in this routine, but it is locked in
58233 ** sqlite3_backup_step(). The user is required to ensure that no
58234 ** other thread accesses the destination handle for the duration
58235 ** of the backup operation. Any attempt to use the destination
58236 ** database connection while a backup is in progress may cause
58237 ** a malfunction or a deadlock.
58239 sqlite3_mutex_enter(pSrcDb->mutex);
58240 sqlite3_mutex_enter(pDestDb->mutex);
58242 if( pSrcDb==pDestDb ){
58243 sqlite3Error(
58244 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
58246 p = 0;
58247 }else {
58248 /* Allocate space for a new sqlite3_backup object...
58249 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58250 ** call to sqlite3_backup_init() and is destroyed by a call to
58251 ** sqlite3_backup_finish(). */
58252 p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
58253 if( !p ){
58254 sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
58258 /* If the allocation succeeded, populate the new object. */
58259 if( p ){
58260 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
58261 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
58262 p->pDestDb = pDestDb;
58263 p->pSrcDb = pSrcDb;
58264 p->iNext = 1;
58265 p->isAttached = 0;
58267 if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
58268 /* One (or both) of the named databases did not exist or an OOM
58269 ** error was hit. The error has already been written into the
58270 ** pDestDb handle. All that is left to do here is free the
58271 ** sqlite3_backup structure.
58273 sqlite3_free(p);
58274 p = 0;
58277 if( p ){
58278 p->pSrc->nBackup++;
58281 sqlite3_mutex_leave(pDestDb->mutex);
58282 sqlite3_mutex_leave(pSrcDb->mutex);
58283 return p;
58287 ** Argument rc is an SQLite error code. Return true if this error is
58288 ** considered fatal if encountered during a backup operation. All errors
58289 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
58291 static int isFatalError(int rc){
58292 return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
58296 ** Parameter zSrcData points to a buffer containing the data for
58297 ** page iSrcPg from the source database. Copy this data into the
58298 ** destination database.
58300 static int backupOnePage(
58301 sqlite3_backup *p, /* Backup handle */
58302 Pgno iSrcPg, /* Source database page to backup */
58303 const u8 *zSrcData, /* Source database page data */
58304 int bUpdate /* True for an update, false otherwise */
58306 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
58307 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
58308 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
58309 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
58310 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
58311 #ifdef SQLITE_HAS_CODEC
58312 /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
58313 ** guaranteed that the shared-mutex is held by this thread, handle
58314 ** p->pSrc may not actually be the owner. */
58315 int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
58316 int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
58317 #endif
58318 int rc = SQLITE_OK;
58319 i64 iOff;
58321 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
58322 assert( p->bDestLocked );
58323 assert( !isFatalError(p->rc) );
58324 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
58325 assert( zSrcData );
58327 /* Catch the case where the destination is an in-memory database and the
58328 ** page sizes of the source and destination differ.
58330 if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
58331 rc = SQLITE_READONLY;
58334 #ifdef SQLITE_HAS_CODEC
58335 /* Backup is not possible if the page size of the destination is changing
58336 ** and a codec is in use.
58338 if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
58339 rc = SQLITE_READONLY;
58342 /* Backup is not possible if the number of bytes of reserve space differ
58343 ** between source and destination. If there is a difference, try to
58344 ** fix the destination to agree with the source. If that is not possible,
58345 ** then the backup cannot proceed.
58347 if( nSrcReserve!=nDestReserve ){
58348 u32 newPgsz = nSrcPgsz;
58349 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
58350 if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
58352 #endif
58354 /* This loop runs once for each destination page spanned by the source
58355 ** page. For each iteration, variable iOff is set to the byte offset
58356 ** of the destination page.
58358 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
58359 DbPage *pDestPg = 0;
58360 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
58361 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
58362 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
58363 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
58365 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
58366 u8 *zDestData = sqlite3PagerGetData(pDestPg);
58367 u8 *zOut = &zDestData[iOff%nDestPgsz];
58369 /* Copy the data from the source page into the destination page.
58370 ** Then clear the Btree layer MemPage.isInit flag. Both this module
58371 ** and the pager code use this trick (clearing the first byte
58372 ** of the page 'extra' space to invalidate the Btree layers
58373 ** cached parse of the page). MemPage.isInit is marked
58374 ** "MUST BE FIRST" for this purpose.
58376 memcpy(zOut, zIn, nCopy);
58377 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
58378 if( iOff==0 && bUpdate==0 ){
58379 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
58382 sqlite3PagerUnref(pDestPg);
58385 return rc;
58389 ** If pFile is currently larger than iSize bytes, then truncate it to
58390 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
58391 ** this function is a no-op.
58393 ** Return SQLITE_OK if everything is successful, or an SQLite error
58394 ** code if an error occurs.
58396 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
58397 i64 iCurrent;
58398 int rc = sqlite3OsFileSize(pFile, &iCurrent);
58399 if( rc==SQLITE_OK && iCurrent>iSize ){
58400 rc = sqlite3OsTruncate(pFile, iSize);
58402 return rc;
58406 ** Register this backup object with the associated source pager for
58407 ** callbacks when pages are changed or the cache invalidated.
58409 static void attachBackupObject(sqlite3_backup *p){
58410 sqlite3_backup **pp;
58411 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
58412 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58413 p->pNext = *pp;
58414 *pp = p;
58415 p->isAttached = 1;
58419 ** Copy nPage pages from the source b-tree to the destination.
58421 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
58422 int rc;
58423 int destMode; /* Destination journal mode */
58424 int pgszSrc = 0; /* Source page size */
58425 int pgszDest = 0; /* Destination page size */
58427 sqlite3_mutex_enter(p->pSrcDb->mutex);
58428 sqlite3BtreeEnter(p->pSrc);
58429 if( p->pDestDb ){
58430 sqlite3_mutex_enter(p->pDestDb->mutex);
58433 rc = p->rc;
58434 if( !isFatalError(rc) ){
58435 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
58436 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
58437 int ii; /* Iterator variable */
58438 int nSrcPage = -1; /* Size of source db in pages */
58439 int bCloseTrans = 0; /* True if src db requires unlocking */
58441 /* If the source pager is currently in a write-transaction, return
58442 ** SQLITE_BUSY immediately.
58444 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
58445 rc = SQLITE_BUSY;
58446 }else{
58447 rc = SQLITE_OK;
58450 /* Lock the destination database, if it is not locked already. */
58451 if( SQLITE_OK==rc && p->bDestLocked==0
58452 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
58454 p->bDestLocked = 1;
58455 sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
58458 /* If there is no open read-transaction on the source database, open
58459 ** one now. If a transaction is opened here, then it will be closed
58460 ** before this function exits.
58462 if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
58463 rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
58464 bCloseTrans = 1;
58467 /* Do not allow backup if the destination database is in WAL mode
58468 ** and the page sizes are different between source and destination */
58469 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
58470 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
58471 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
58472 if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
58473 rc = SQLITE_READONLY;
58476 /* Now that there is a read-lock on the source database, query the
58477 ** source pager for the number of pages in the database.
58479 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
58480 assert( nSrcPage>=0 );
58481 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
58482 const Pgno iSrcPg = p->iNext; /* Source page number */
58483 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
58484 DbPage *pSrcPg; /* Source page object */
58485 rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
58486 PAGER_GET_READONLY);
58487 if( rc==SQLITE_OK ){
58488 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
58489 sqlite3PagerUnref(pSrcPg);
58492 p->iNext++;
58494 if( rc==SQLITE_OK ){
58495 p->nPagecount = nSrcPage;
58496 p->nRemaining = nSrcPage+1-p->iNext;
58497 if( p->iNext>(Pgno)nSrcPage ){
58498 rc = SQLITE_DONE;
58499 }else if( !p->isAttached ){
58500 attachBackupObject(p);
58504 /* Update the schema version field in the destination database. This
58505 ** is to make sure that the schema-version really does change in
58506 ** the case where the source and destination databases have the
58507 ** same schema version.
58509 if( rc==SQLITE_DONE ){
58510 if( nSrcPage==0 ){
58511 rc = sqlite3BtreeNewDb(p->pDest);
58512 nSrcPage = 1;
58514 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
58515 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
58517 if( rc==SQLITE_OK ){
58518 if( p->pDestDb ){
58519 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
58521 if( destMode==PAGER_JOURNALMODE_WAL ){
58522 rc = sqlite3BtreeSetVersion(p->pDest, 2);
58525 if( rc==SQLITE_OK ){
58526 int nDestTruncate;
58527 /* Set nDestTruncate to the final number of pages in the destination
58528 ** database. The complication here is that the destination page
58529 ** size may be different to the source page size.
58531 ** If the source page size is smaller than the destination page size,
58532 ** round up. In this case the call to sqlite3OsTruncate() below will
58533 ** fix the size of the file. However it is important to call
58534 ** sqlite3PagerTruncateImage() here so that any pages in the
58535 ** destination file that lie beyond the nDestTruncate page mark are
58536 ** journalled by PagerCommitPhaseOne() before they are destroyed
58537 ** by the file truncation.
58539 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
58540 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
58541 if( pgszSrc<pgszDest ){
58542 int ratio = pgszDest/pgszSrc;
58543 nDestTruncate = (nSrcPage+ratio-1)/ratio;
58544 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
58545 nDestTruncate--;
58547 }else{
58548 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
58550 assert( nDestTruncate>0 );
58552 if( pgszSrc<pgszDest ){
58553 /* If the source page-size is smaller than the destination page-size,
58554 ** two extra things may need to happen:
58556 ** * The destination may need to be truncated, and
58558 ** * Data stored on the pages immediately following the
58559 ** pending-byte page in the source database may need to be
58560 ** copied into the destination database.
58562 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
58563 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
58564 Pgno iPg;
58565 int nDstPage;
58566 i64 iOff;
58567 i64 iEnd;
58569 assert( pFile );
58570 assert( nDestTruncate==0
58571 || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
58572 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
58573 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
58576 /* This block ensures that all data required to recreate the original
58577 ** database has been stored in the journal for pDestPager and the
58578 ** journal synced to disk. So at this point we may safely modify
58579 ** the database file in any way, knowing that if a power failure
58580 ** occurs, the original database will be reconstructed from the
58581 ** journal file. */
58582 sqlite3PagerPagecount(pDestPager, &nDstPage);
58583 for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
58584 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
58585 DbPage *pPg;
58586 rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
58587 if( rc==SQLITE_OK ){
58588 rc = sqlite3PagerWrite(pPg);
58589 sqlite3PagerUnref(pPg);
58593 if( rc==SQLITE_OK ){
58594 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
58597 /* Write the extra pages and truncate the database file as required */
58598 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
58599 for(
58600 iOff=PENDING_BYTE+pgszSrc;
58601 rc==SQLITE_OK && iOff<iEnd;
58602 iOff+=pgszSrc
58604 PgHdr *pSrcPg = 0;
58605 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
58606 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58607 if( rc==SQLITE_OK ){
58608 u8 *zData = sqlite3PagerGetData(pSrcPg);
58609 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
58611 sqlite3PagerUnref(pSrcPg);
58613 if( rc==SQLITE_OK ){
58614 rc = backupTruncateFile(pFile, iSize);
58617 /* Sync the database file to disk. */
58618 if( rc==SQLITE_OK ){
58619 rc = sqlite3PagerSync(pDestPager);
58621 }else{
58622 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
58623 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
58626 /* Finish committing the transaction to the destination database. */
58627 if( SQLITE_OK==rc
58628 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
58630 rc = SQLITE_DONE;
58635 /* If bCloseTrans is true, then this function opened a read transaction
58636 ** on the source database. Close the read transaction here. There is
58637 ** no need to check the return values of the btree methods here, as
58638 ** "committing" a read-only transaction cannot fail.
58640 if( bCloseTrans ){
58641 TESTONLY( int rc2 );
58642 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
58643 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
58644 assert( rc2==SQLITE_OK );
58647 if( rc==SQLITE_IOERR_NOMEM ){
58648 rc = SQLITE_NOMEM;
58650 p->rc = rc;
58652 if( p->pDestDb ){
58653 sqlite3_mutex_leave(p->pDestDb->mutex);
58655 sqlite3BtreeLeave(p->pSrc);
58656 sqlite3_mutex_leave(p->pSrcDb->mutex);
58657 return rc;
58661 ** Release all resources associated with an sqlite3_backup* handle.
58663 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
58664 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
58665 sqlite3 *pSrcDb; /* Source database connection */
58666 int rc; /* Value to return */
58668 /* Enter the mutexes */
58669 if( p==0 ) return SQLITE_OK;
58670 pSrcDb = p->pSrcDb;
58671 sqlite3_mutex_enter(pSrcDb->mutex);
58672 sqlite3BtreeEnter(p->pSrc);
58673 if( p->pDestDb ){
58674 sqlite3_mutex_enter(p->pDestDb->mutex);
58677 /* Detach this backup from the source pager. */
58678 if( p->pDestDb ){
58679 p->pSrc->nBackup--;
58681 if( p->isAttached ){
58682 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58683 while( *pp!=p ){
58684 pp = &(*pp)->pNext;
58686 *pp = p->pNext;
58689 /* If a transaction is still open on the Btree, roll it back. */
58690 sqlite3BtreeRollback(p->pDest, SQLITE_OK);
58692 /* Set the error code of the destination database handle. */
58693 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
58694 sqlite3Error(p->pDestDb, rc, 0);
58696 /* Exit the mutexes and free the backup context structure. */
58697 if( p->pDestDb ){
58698 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
58700 sqlite3BtreeLeave(p->pSrc);
58701 if( p->pDestDb ){
58702 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58703 ** call to sqlite3_backup_init() and is destroyed by a call to
58704 ** sqlite3_backup_finish(). */
58705 sqlite3_free(p);
58707 sqlite3LeaveMutexAndCloseZombie(pSrcDb);
58708 return rc;
58712 ** Return the number of pages still to be backed up as of the most recent
58713 ** call to sqlite3_backup_step().
58715 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
58716 return p->nRemaining;
58720 ** Return the total number of pages in the source database as of the most
58721 ** recent call to sqlite3_backup_step().
58723 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
58724 return p->nPagecount;
58728 ** This function is called after the contents of page iPage of the
58729 ** source database have been modified. If page iPage has already been
58730 ** copied into the destination database, then the data written to the
58731 ** destination is now invalidated. The destination copy of iPage needs
58732 ** to be updated with the new data before the backup operation is
58733 ** complete.
58735 ** It is assumed that the mutex associated with the BtShared object
58736 ** corresponding to the source database is held when this function is
58737 ** called.
58739 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
58740 sqlite3_backup *p; /* Iterator variable */
58741 for(p=pBackup; p; p=p->pNext){
58742 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58743 if( !isFatalError(p->rc) && iPage<p->iNext ){
58744 /* The backup process p has already copied page iPage. But now it
58745 ** has been modified by a transaction on the source pager. Copy
58746 ** the new data into the backup.
58748 int rc;
58749 assert( p->pDestDb );
58750 sqlite3_mutex_enter(p->pDestDb->mutex);
58751 rc = backupOnePage(p, iPage, aData, 1);
58752 sqlite3_mutex_leave(p->pDestDb->mutex);
58753 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
58754 if( rc!=SQLITE_OK ){
58755 p->rc = rc;
58762 ** Restart the backup process. This is called when the pager layer
58763 ** detects that the database has been modified by an external database
58764 ** connection. In this case there is no way of knowing which of the
58765 ** pages that have been copied into the destination database are still
58766 ** valid and which are not, so the entire process needs to be restarted.
58768 ** It is assumed that the mutex associated with the BtShared object
58769 ** corresponding to the source database is held when this function is
58770 ** called.
58772 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
58773 sqlite3_backup *p; /* Iterator variable */
58774 for(p=pBackup; p; p=p->pNext){
58775 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58776 p->iNext = 1;
58780 #ifndef SQLITE_OMIT_VACUUM
58782 ** Copy the complete content of pBtFrom into pBtTo. A transaction
58783 ** must be active for both files.
58785 ** The size of file pTo may be reduced by this operation. If anything
58786 ** goes wrong, the transaction on pTo is rolled back. If successful, the
58787 ** transaction is committed before returning.
58789 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
58790 int rc;
58791 sqlite3_file *pFd; /* File descriptor for database pTo */
58792 sqlite3_backup b;
58793 sqlite3BtreeEnter(pTo);
58794 sqlite3BtreeEnter(pFrom);
58796 assert( sqlite3BtreeIsInTrans(pTo) );
58797 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
58798 if( pFd->pMethods ){
58799 i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
58800 rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
58801 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
58802 if( rc ) goto copy_finished;
58805 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
58806 ** to 0. This is used by the implementations of sqlite3_backup_step()
58807 ** and sqlite3_backup_finish() to detect that they are being called
58808 ** from this function, not directly by the user.
58810 memset(&b, 0, sizeof(b));
58811 b.pSrcDb = pFrom->db;
58812 b.pSrc = pFrom;
58813 b.pDest = pTo;
58814 b.iNext = 1;
58816 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
58817 ** file. By passing this as the number of pages to copy to
58818 ** sqlite3_backup_step(), we can guarantee that the copy finishes
58819 ** within a single call (unless an error occurs). The assert() statement
58820 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
58821 ** or an error code.
58823 sqlite3_backup_step(&b, 0x7FFFFFFF);
58824 assert( b.rc!=SQLITE_OK );
58825 rc = sqlite3_backup_finish(&b);
58826 if( rc==SQLITE_OK ){
58827 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
58828 }else{
58829 sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
58832 assert( sqlite3BtreeIsInTrans(pTo)==0 );
58833 copy_finished:
58834 sqlite3BtreeLeave(pFrom);
58835 sqlite3BtreeLeave(pTo);
58836 return rc;
58838 #endif /* SQLITE_OMIT_VACUUM */
58840 /************** End of backup.c **********************************************/
58841 /************** Begin file vdbemem.c *****************************************/
58843 ** 2004 May 26
58845 ** The author disclaims copyright to this source code. In place of
58846 ** a legal notice, here is a blessing:
58848 ** May you do good and not evil.
58849 ** May you find forgiveness for yourself and forgive others.
58850 ** May you share freely, never taking more than you give.
58852 *************************************************************************
58854 ** This file contains code use to manipulate "Mem" structure. A "Mem"
58855 ** stores a single value in the VDBE. Mem is an opaque structure visible
58856 ** only within the VDBE. Interface routines refer to a Mem using the
58857 ** name sqlite_value
58861 ** If pMem is an object with a valid string representation, this routine
58862 ** ensures the internal encoding for the string representation is
58863 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
58865 ** If pMem is not a string object, or the encoding of the string
58866 ** representation is already stored using the requested encoding, then this
58867 ** routine is a no-op.
58869 ** SQLITE_OK is returned if the conversion is successful (or not required).
58870 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
58871 ** between formats.
58873 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
58874 #ifndef SQLITE_OMIT_UTF16
58875 int rc;
58876 #endif
58877 assert( (pMem->flags&MEM_RowSet)==0 );
58878 assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
58879 || desiredEnc==SQLITE_UTF16BE );
58880 if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
58881 return SQLITE_OK;
58883 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58884 #ifdef SQLITE_OMIT_UTF16
58885 return SQLITE_ERROR;
58886 #else
58888 /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
58889 ** then the encoding of the value may not have changed.
58891 rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
58892 assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
58893 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
58894 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
58895 return rc;
58896 #endif
58900 ** Make sure pMem->z points to a writable allocation of at least
58901 ** n bytes.
58903 ** If the third argument passed to this function is true, then memory
58904 ** cell pMem must contain a string or blob. In this case the content is
58905 ** preserved. Otherwise, if the third parameter to this function is false,
58906 ** any current string or blob value may be discarded.
58908 ** This function sets the MEM_Dyn flag and clears any xDel callback.
58909 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
58910 ** not set, Mem.n is zeroed.
58912 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
58913 assert( 1 >=
58914 ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
58915 (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
58916 ((pMem->flags&MEM_Ephem) ? 1 : 0) +
58917 ((pMem->flags&MEM_Static) ? 1 : 0)
58919 assert( (pMem->flags&MEM_RowSet)==0 );
58921 /* If the preserve flag is set to true, then the memory cell must already
58922 ** contain a valid string or blob value. */
58923 assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
58925 if( n<32 ) n = 32;
58926 if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
58927 if( preserve && pMem->z==pMem->zMalloc ){
58928 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
58929 preserve = 0;
58930 }else{
58931 sqlite3DbFree(pMem->db, pMem->zMalloc);
58932 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
58936 if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
58937 memcpy(pMem->zMalloc, pMem->z, pMem->n);
58939 if( pMem->flags&MEM_Dyn && pMem->xDel ){
58940 assert( pMem->xDel!=SQLITE_DYNAMIC );
58941 pMem->xDel((void *)(pMem->z));
58944 pMem->z = pMem->zMalloc;
58945 if( pMem->z==0 ){
58946 pMem->flags = MEM_Null;
58947 }else{
58948 pMem->flags &= ~(MEM_Ephem|MEM_Static);
58950 pMem->xDel = 0;
58951 return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
58955 ** Make the given Mem object MEM_Dyn. In other words, make it so
58956 ** that any TEXT or BLOB content is stored in memory obtained from
58957 ** malloc(). In this way, we know that the memory is safe to be
58958 ** overwritten or altered.
58960 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
58962 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
58963 int f;
58964 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58965 assert( (pMem->flags&MEM_RowSet)==0 );
58966 ExpandBlob(pMem);
58967 f = pMem->flags;
58968 if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
58969 if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
58970 return SQLITE_NOMEM;
58972 pMem->z[pMem->n] = 0;
58973 pMem->z[pMem->n+1] = 0;
58974 pMem->flags |= MEM_Term;
58975 #ifdef SQLITE_DEBUG
58976 pMem->pScopyFrom = 0;
58977 #endif
58980 return SQLITE_OK;
58984 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
58985 ** blob stored in dynamically allocated space.
58987 #ifndef SQLITE_OMIT_INCRBLOB
58988 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
58989 if( pMem->flags & MEM_Zero ){
58990 int nByte;
58991 assert( pMem->flags&MEM_Blob );
58992 assert( (pMem->flags&MEM_RowSet)==0 );
58993 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58995 /* Set nByte to the number of bytes required to store the expanded blob. */
58996 nByte = pMem->n + pMem->u.nZero;
58997 if( nByte<=0 ){
58998 nByte = 1;
59000 if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
59001 return SQLITE_NOMEM;
59004 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
59005 pMem->n += pMem->u.nZero;
59006 pMem->flags &= ~(MEM_Zero|MEM_Term);
59008 return SQLITE_OK;
59010 #endif
59014 ** Make sure the given Mem is \u0000 terminated.
59016 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
59017 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59018 if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
59019 return SQLITE_OK; /* Nothing to do */
59021 if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
59022 return SQLITE_NOMEM;
59024 pMem->z[pMem->n] = 0;
59025 pMem->z[pMem->n+1] = 0;
59026 pMem->flags |= MEM_Term;
59027 return SQLITE_OK;
59031 ** Add MEM_Str to the set of representations for the given Mem. Numbers
59032 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
59033 ** is a no-op.
59035 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
59037 ** A MEM_Null value will never be passed to this function. This function is
59038 ** used for converting values to text for returning to the user (i.e. via
59039 ** sqlite3_value_text()), or for ensuring that values to be used as btree
59040 ** keys are strings. In the former case a NULL pointer is returned the
59041 ** user and the later is an internal programming error.
59043 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
59044 int rc = SQLITE_OK;
59045 int fg = pMem->flags;
59046 const int nByte = 32;
59048 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59049 assert( !(fg&MEM_Zero) );
59050 assert( !(fg&(MEM_Str|MEM_Blob)) );
59051 assert( fg&(MEM_Int|MEM_Real) );
59052 assert( (pMem->flags&MEM_RowSet)==0 );
59053 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59056 if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
59057 return SQLITE_NOMEM;
59060 /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
59061 ** string representation of the value. Then, if the required encoding
59062 ** is UTF-16le or UTF-16be do a translation.
59064 ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
59066 if( fg & MEM_Int ){
59067 sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
59068 }else{
59069 assert( fg & MEM_Real );
59070 sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
59072 pMem->n = sqlite3Strlen30(pMem->z);
59073 pMem->enc = SQLITE_UTF8;
59074 pMem->flags |= MEM_Str|MEM_Term;
59075 sqlite3VdbeChangeEncoding(pMem, enc);
59076 return rc;
59080 ** Memory cell pMem contains the context of an aggregate function.
59081 ** This routine calls the finalize method for that function. The
59082 ** result of the aggregate is stored back into pMem.
59084 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
59085 ** otherwise.
59087 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
59088 int rc = SQLITE_OK;
59089 if( ALWAYS(pFunc && pFunc->xFinalize) ){
59090 sqlite3_context ctx;
59091 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
59092 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59093 memset(&ctx, 0, sizeof(ctx));
59094 ctx.s.flags = MEM_Null;
59095 ctx.s.db = pMem->db;
59096 ctx.pMem = pMem;
59097 ctx.pFunc = pFunc;
59098 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
59099 assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
59100 sqlite3DbFree(pMem->db, pMem->zMalloc);
59101 memcpy(pMem, &ctx.s, sizeof(ctx.s));
59102 rc = ctx.isError;
59104 return rc;
59108 ** If the memory cell contains a string value that must be freed by
59109 ** invoking an external callback, free it now. Calling this function
59110 ** does not free any Mem.zMalloc buffer.
59112 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
59113 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
59114 if( p->flags&MEM_Agg ){
59115 sqlite3VdbeMemFinalize(p, p->u.pDef);
59116 assert( (p->flags & MEM_Agg)==0 );
59117 sqlite3VdbeMemRelease(p);
59118 }else if( p->flags&MEM_Dyn && p->xDel ){
59119 assert( (p->flags&MEM_RowSet)==0 );
59120 assert( p->xDel!=SQLITE_DYNAMIC );
59121 p->xDel((void *)p->z);
59122 p->xDel = 0;
59123 }else if( p->flags&MEM_RowSet ){
59124 sqlite3RowSetClear(p->u.pRowSet);
59125 }else if( p->flags&MEM_Frame ){
59126 sqlite3VdbeMemSetNull(p);
59131 ** Release any memory held by the Mem. This may leave the Mem in an
59132 ** inconsistent state, for example with (Mem.z==0) and
59133 ** (Mem.type==SQLITE_TEXT).
59135 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
59136 VdbeMemRelease(p);
59137 sqlite3DbFree(p->db, p->zMalloc);
59138 p->z = 0;
59139 p->zMalloc = 0;
59140 p->xDel = 0;
59144 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
59145 ** If the double is too large, return 0x8000000000000000.
59147 ** Most systems appear to do this simply by assigning
59148 ** variables and without the extra range tests. But
59149 ** there are reports that windows throws an expection
59150 ** if the floating point value is out of range. (See ticket #2880.)
59151 ** Because we do not completely understand the problem, we will
59152 ** take the conservative approach and always do range tests
59153 ** before attempting the conversion.
59155 static i64 doubleToInt64(double r){
59156 #ifdef SQLITE_OMIT_FLOATING_POINT
59157 /* When floating-point is omitted, double and int64 are the same thing */
59158 return r;
59159 #else
59161 ** Many compilers we encounter do not define constants for the
59162 ** minimum and maximum 64-bit integers, or they define them
59163 ** inconsistently. And many do not understand the "LL" notation.
59164 ** So we define our own static constants here using nothing
59165 ** larger than a 32-bit integer constant.
59167 static const i64 maxInt = LARGEST_INT64;
59168 static const i64 minInt = SMALLEST_INT64;
59170 if( r<(double)minInt ){
59171 return minInt;
59172 }else if( r>(double)maxInt ){
59173 /* minInt is correct here - not maxInt. It turns out that assigning
59174 ** a very large positive number to an integer results in a very large
59175 ** negative integer. This makes no sense, but it is what x86 hardware
59176 ** does so for compatibility we will do the same in software. */
59177 return minInt;
59178 }else{
59179 return (i64)r;
59181 #endif
59185 ** Return some kind of integer value which is the best we can do
59186 ** at representing the value that *pMem describes as an integer.
59187 ** If pMem is an integer, then the value is exact. If pMem is
59188 ** a floating-point then the value returned is the integer part.
59189 ** If pMem is a string or blob, then we make an attempt to convert
59190 ** it into a integer and return that. If pMem represents an
59191 ** an SQL-NULL value, return 0.
59193 ** If pMem represents a string value, its encoding might be changed.
59195 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
59196 int flags;
59197 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59198 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59199 flags = pMem->flags;
59200 if( flags & MEM_Int ){
59201 return pMem->u.i;
59202 }else if( flags & MEM_Real ){
59203 return doubleToInt64(pMem->r);
59204 }else if( flags & (MEM_Str|MEM_Blob) ){
59205 i64 value = 0;
59206 assert( pMem->z || pMem->n==0 );
59207 testcase( pMem->z==0 );
59208 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
59209 return value;
59210 }else{
59211 return 0;
59216 ** Return the best representation of pMem that we can get into a
59217 ** double. If pMem is already a double or an integer, return its
59218 ** value. If it is a string or blob, try to convert it to a double.
59219 ** If it is a NULL, return 0.0.
59221 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
59222 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59223 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59224 if( pMem->flags & MEM_Real ){
59225 return pMem->r;
59226 }else if( pMem->flags & MEM_Int ){
59227 return (double)pMem->u.i;
59228 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
59229 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59230 double val = (double)0;
59231 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
59232 return val;
59233 }else{
59234 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59235 return (double)0;
59240 ** The MEM structure is already a MEM_Real. Try to also make it a
59241 ** MEM_Int if we can.
59243 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
59244 assert( pMem->flags & MEM_Real );
59245 assert( (pMem->flags & MEM_RowSet)==0 );
59246 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59247 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59249 pMem->u.i = doubleToInt64(pMem->r);
59251 /* Only mark the value as an integer if
59253 ** (1) the round-trip conversion real->int->real is a no-op, and
59254 ** (2) The integer is neither the largest nor the smallest
59255 ** possible integer (ticket #3922)
59257 ** The second and third terms in the following conditional enforces
59258 ** the second condition under the assumption that addition overflow causes
59259 ** values to wrap around. On x86 hardware, the third term is always
59260 ** true and could be omitted. But we leave it in because other
59261 ** architectures might behave differently.
59263 if( pMem->r==(double)pMem->u.i
59264 && pMem->u.i>SMALLEST_INT64
59265 #if defined(__i486__) || defined(__x86_64__)
59266 && ALWAYS(pMem->u.i<LARGEST_INT64)
59267 #else
59268 && pMem->u.i<LARGEST_INT64
59269 #endif
59271 pMem->flags |= MEM_Int;
59276 ** Convert pMem to type integer. Invalidate any prior representations.
59278 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
59279 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59280 assert( (pMem->flags & MEM_RowSet)==0 );
59281 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59283 pMem->u.i = sqlite3VdbeIntValue(pMem);
59284 MemSetTypeFlag(pMem, MEM_Int);
59285 return SQLITE_OK;
59289 ** Convert pMem so that it is of type MEM_Real.
59290 ** Invalidate any prior representations.
59292 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
59293 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59294 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59296 pMem->r = sqlite3VdbeRealValue(pMem);
59297 MemSetTypeFlag(pMem, MEM_Real);
59298 return SQLITE_OK;
59302 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
59303 ** Invalidate any prior representations.
59305 ** Every effort is made to force the conversion, even if the input
59306 ** is a string that does not look completely like a number. Convert
59307 ** as much of the string as we can and ignore the rest.
59309 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
59310 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
59311 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
59312 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59313 if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
59314 MemSetTypeFlag(pMem, MEM_Int);
59315 }else{
59316 pMem->r = sqlite3VdbeRealValue(pMem);
59317 MemSetTypeFlag(pMem, MEM_Real);
59318 sqlite3VdbeIntegerAffinity(pMem);
59321 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
59322 pMem->flags &= ~(MEM_Str|MEM_Blob);
59323 return SQLITE_OK;
59327 ** Delete any previous value and set the value stored in *pMem to NULL.
59329 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
59330 if( pMem->flags & MEM_Frame ){
59331 VdbeFrame *pFrame = pMem->u.pFrame;
59332 pFrame->pParent = pFrame->v->pDelFrame;
59333 pFrame->v->pDelFrame = pFrame;
59335 if( pMem->flags & MEM_RowSet ){
59336 sqlite3RowSetClear(pMem->u.pRowSet);
59338 MemSetTypeFlag(pMem, MEM_Null);
59339 pMem->type = SQLITE_NULL;
59343 ** Delete any previous value and set the value to be a BLOB of length
59344 ** n containing all zeros.
59346 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
59347 sqlite3VdbeMemRelease(pMem);
59348 pMem->flags = MEM_Blob|MEM_Zero;
59349 pMem->type = SQLITE_BLOB;
59350 pMem->n = 0;
59351 if( n<0 ) n = 0;
59352 pMem->u.nZero = n;
59353 pMem->enc = SQLITE_UTF8;
59355 #ifdef SQLITE_OMIT_INCRBLOB
59356 sqlite3VdbeMemGrow(pMem, n, 0);
59357 if( pMem->z ){
59358 pMem->n = n;
59359 memset(pMem->z, 0, n);
59361 #endif
59365 ** Delete any previous value and set the value stored in *pMem to val,
59366 ** manifest type INTEGER.
59368 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
59369 sqlite3VdbeMemRelease(pMem);
59370 pMem->u.i = val;
59371 pMem->flags = MEM_Int;
59372 pMem->type = SQLITE_INTEGER;
59375 #ifndef SQLITE_OMIT_FLOATING_POINT
59377 ** Delete any previous value and set the value stored in *pMem to val,
59378 ** manifest type REAL.
59380 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
59381 if( sqlite3IsNaN(val) ){
59382 sqlite3VdbeMemSetNull(pMem);
59383 }else{
59384 sqlite3VdbeMemRelease(pMem);
59385 pMem->r = val;
59386 pMem->flags = MEM_Real;
59387 pMem->type = SQLITE_FLOAT;
59390 #endif
59393 ** Delete any previous value and set the value of pMem to be an
59394 ** empty boolean index.
59396 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
59397 sqlite3 *db = pMem->db;
59398 assert( db!=0 );
59399 assert( (pMem->flags & MEM_RowSet)==0 );
59400 sqlite3VdbeMemRelease(pMem);
59401 pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
59402 if( db->mallocFailed ){
59403 pMem->flags = MEM_Null;
59404 }else{
59405 assert( pMem->zMalloc );
59406 pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
59407 sqlite3DbMallocSize(db, pMem->zMalloc));
59408 assert( pMem->u.pRowSet!=0 );
59409 pMem->flags = MEM_RowSet;
59414 ** Return true if the Mem object contains a TEXT or BLOB that is
59415 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
59417 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
59418 assert( p->db!=0 );
59419 if( p->flags & (MEM_Str|MEM_Blob) ){
59420 int n = p->n;
59421 if( p->flags & MEM_Zero ){
59422 n += p->u.nZero;
59424 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
59426 return 0;
59429 #ifdef SQLITE_DEBUG
59431 ** This routine prepares a memory cell for modication by breaking
59432 ** its link to a shallow copy and by marking any current shallow
59433 ** copies of this cell as invalid.
59435 ** This is used for testing and debugging only - to make sure shallow
59436 ** copies are not misused.
59438 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
59439 int i;
59440 Mem *pX;
59441 for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
59442 if( pX->pScopyFrom==pMem ){
59443 pX->flags |= MEM_Invalid;
59444 pX->pScopyFrom = 0;
59447 pMem->pScopyFrom = 0;
59449 #endif /* SQLITE_DEBUG */
59452 ** Size of struct Mem not including the Mem.zMalloc member.
59454 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
59457 ** Make an shallow copy of pFrom into pTo. Prior contents of
59458 ** pTo are freed. The pFrom->z field is not duplicated. If
59459 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
59460 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
59462 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
59463 assert( (pFrom->flags & MEM_RowSet)==0 );
59464 VdbeMemRelease(pTo);
59465 memcpy(pTo, pFrom, MEMCELLSIZE);
59466 pTo->xDel = 0;
59467 if( (pFrom->flags&MEM_Static)==0 ){
59468 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
59469 assert( srcType==MEM_Ephem || srcType==MEM_Static );
59470 pTo->flags |= srcType;
59475 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
59476 ** freed before the copy is made.
59478 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
59479 int rc = SQLITE_OK;
59481 assert( (pFrom->flags & MEM_RowSet)==0 );
59482 VdbeMemRelease(pTo);
59483 memcpy(pTo, pFrom, MEMCELLSIZE);
59484 pTo->flags &= ~MEM_Dyn;
59486 if( pTo->flags&(MEM_Str|MEM_Blob) ){
59487 if( 0==(pFrom->flags&MEM_Static) ){
59488 pTo->flags |= MEM_Ephem;
59489 rc = sqlite3VdbeMemMakeWriteable(pTo);
59493 return rc;
59497 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
59498 ** freed. If pFrom contains ephemeral data, a copy is made.
59500 ** pFrom contains an SQL NULL when this routine returns.
59502 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
59503 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
59504 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
59505 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
59507 sqlite3VdbeMemRelease(pTo);
59508 memcpy(pTo, pFrom, sizeof(Mem));
59509 pFrom->flags = MEM_Null;
59510 pFrom->xDel = 0;
59511 pFrom->zMalloc = 0;
59515 ** Change the value of a Mem to be a string or a BLOB.
59517 ** The memory management strategy depends on the value of the xDel
59518 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
59519 ** string is copied into a (possibly existing) buffer managed by the
59520 ** Mem structure. Otherwise, any existing buffer is freed and the
59521 ** pointer copied.
59523 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
59524 ** size limit) then no memory allocation occurs. If the string can be
59525 ** stored without allocating memory, then it is. If a memory allocation
59526 ** is required to store the string, then value of pMem is unchanged. In
59527 ** either case, SQLITE_TOOBIG is returned.
59529 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
59530 Mem *pMem, /* Memory cell to set to string value */
59531 const char *z, /* String pointer */
59532 int n, /* Bytes in string, or negative */
59533 u8 enc, /* Encoding of z. 0 for BLOBs */
59534 void (*xDel)(void*) /* Destructor function */
59536 int nByte = n; /* New value for pMem->n */
59537 int iLimit; /* Maximum allowed string or blob size */
59538 u16 flags = 0; /* New value for pMem->flags */
59540 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59541 assert( (pMem->flags & MEM_RowSet)==0 );
59543 /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
59544 if( !z ){
59545 sqlite3VdbeMemSetNull(pMem);
59546 return SQLITE_OK;
59549 if( pMem->db ){
59550 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
59551 }else{
59552 iLimit = SQLITE_MAX_LENGTH;
59554 flags = (enc==0?MEM_Blob:MEM_Str);
59555 if( nByte<0 ){
59556 assert( enc!=0 );
59557 if( enc==SQLITE_UTF8 ){
59558 for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
59559 }else{
59560 for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
59562 flags |= MEM_Term;
59565 /* The following block sets the new values of Mem.z and Mem.xDel. It
59566 ** also sets a flag in local variable "flags" to indicate the memory
59567 ** management (one of MEM_Dyn or MEM_Static).
59569 if( xDel==SQLITE_TRANSIENT ){
59570 int nAlloc = nByte;
59571 if( flags&MEM_Term ){
59572 nAlloc += (enc==SQLITE_UTF8?1:2);
59574 if( nByte>iLimit ){
59575 return SQLITE_TOOBIG;
59577 if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
59578 return SQLITE_NOMEM;
59580 memcpy(pMem->z, z, nAlloc);
59581 }else if( xDel==SQLITE_DYNAMIC ){
59582 sqlite3VdbeMemRelease(pMem);
59583 pMem->zMalloc = pMem->z = (char *)z;
59584 pMem->xDel = 0;
59585 }else{
59586 sqlite3VdbeMemRelease(pMem);
59587 pMem->z = (char *)z;
59588 pMem->xDel = xDel;
59589 flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
59592 pMem->n = nByte;
59593 pMem->flags = flags;
59594 pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
59595 pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
59597 #ifndef SQLITE_OMIT_UTF16
59598 if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
59599 return SQLITE_NOMEM;
59601 #endif
59603 if( nByte>iLimit ){
59604 return SQLITE_TOOBIG;
59607 return SQLITE_OK;
59611 ** Compare the values contained by the two memory cells, returning
59612 ** negative, zero or positive if pMem1 is less than, equal to, or greater
59613 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
59614 ** and reals) sorted numerically, followed by text ordered by the collating
59615 ** sequence pColl and finally blob's ordered by memcmp().
59617 ** Two NULL values are considered equal by this function.
59619 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
59620 int rc;
59621 int f1, f2;
59622 int combined_flags;
59624 f1 = pMem1->flags;
59625 f2 = pMem2->flags;
59626 combined_flags = f1|f2;
59627 assert( (combined_flags & MEM_RowSet)==0 );
59629 /* If one value is NULL, it is less than the other. If both values
59630 ** are NULL, return 0.
59632 if( combined_flags&MEM_Null ){
59633 return (f2&MEM_Null) - (f1&MEM_Null);
59636 /* If one value is a number and the other is not, the number is less.
59637 ** If both are numbers, compare as reals if one is a real, or as integers
59638 ** if both values are integers.
59640 if( combined_flags&(MEM_Int|MEM_Real) ){
59641 double r1, r2;
59642 if( (f1 & f2 & MEM_Int)!=0 ){
59643 if( pMem1->u.i < pMem2->u.i ) return -1;
59644 if( pMem1->u.i > pMem2->u.i ) return 1;
59645 return 0;
59647 if( (f1&MEM_Real)!=0 ){
59648 r1 = pMem1->r;
59649 }else if( (f1&MEM_Int)!=0 ){
59650 r1 = (double)pMem1->u.i;
59651 }else{
59652 return 1;
59654 if( (f2&MEM_Real)!=0 ){
59655 r2 = pMem2->r;
59656 }else if( (f2&MEM_Int)!=0 ){
59657 r2 = (double)pMem2->u.i;
59658 }else{
59659 return -1;
59661 if( r1<r2 ) return -1;
59662 if( r1>r2 ) return 1;
59663 return 0;
59666 /* If one value is a string and the other is a blob, the string is less.
59667 ** If both are strings, compare using the collating functions.
59669 if( combined_flags&MEM_Str ){
59670 if( (f1 & MEM_Str)==0 ){
59671 return 1;
59673 if( (f2 & MEM_Str)==0 ){
59674 return -1;
59677 assert( pMem1->enc==pMem2->enc );
59678 assert( pMem1->enc==SQLITE_UTF8 ||
59679 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
59681 /* The collation sequence must be defined at this point, even if
59682 ** the user deletes the collation sequence after the vdbe program is
59683 ** compiled (this was not always the case).
59685 assert( !pColl || pColl->xCmp );
59687 if( pColl ){
59688 if( pMem1->enc==pColl->enc ){
59689 /* The strings are already in the correct encoding. Call the
59690 ** comparison function directly */
59691 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
59692 }else{
59693 const void *v1, *v2;
59694 int n1, n2;
59695 Mem c1;
59696 Mem c2;
59697 memset(&c1, 0, sizeof(c1));
59698 memset(&c2, 0, sizeof(c2));
59699 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
59700 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
59701 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
59702 n1 = v1==0 ? 0 : c1.n;
59703 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
59704 n2 = v2==0 ? 0 : c2.n;
59705 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
59706 sqlite3VdbeMemRelease(&c1);
59707 sqlite3VdbeMemRelease(&c2);
59708 return rc;
59711 /* If a NULL pointer was passed as the collate function, fall through
59712 ** to the blob case and use memcmp(). */
59715 /* Both values must be blobs. Compare using memcmp(). */
59716 rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
59717 if( rc==0 ){
59718 rc = pMem1->n - pMem2->n;
59720 return rc;
59724 ** Move data out of a btree key or data field and into a Mem structure.
59725 ** The data or key is taken from the entry that pCur is currently pointing
59726 ** to. offset and amt determine what portion of the data or key to retrieve.
59727 ** key is true to get the key or false to get data. The result is written
59728 ** into the pMem element.
59730 ** The pMem structure is assumed to be uninitialized. Any prior content
59731 ** is overwritten without being freed.
59733 ** If this routine fails for any reason (malloc returns NULL or unable
59734 ** to read from the disk) then the pMem is left in an inconsistent state.
59736 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
59737 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
59738 int offset, /* Offset from the start of data to return bytes from. */
59739 int amt, /* Number of bytes to return. */
59740 int key, /* If true, retrieve from the btree key, not data. */
59741 Mem *pMem /* OUT: Return data in this Mem structure. */
59743 char *zData; /* Data from the btree layer */
59744 int available = 0; /* Number of bytes available on the local btree page */
59745 int rc = SQLITE_OK; /* Return code */
59747 assert( sqlite3BtreeCursorIsValid(pCur) );
59749 /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
59750 ** that both the BtShared and database handle mutexes are held. */
59751 assert( (pMem->flags & MEM_RowSet)==0 );
59752 if( key ){
59753 zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
59754 }else{
59755 zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
59757 assert( zData!=0 );
59759 if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
59760 sqlite3VdbeMemRelease(pMem);
59761 pMem->z = &zData[offset];
59762 pMem->flags = MEM_Blob|MEM_Ephem;
59763 }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
59764 pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
59765 pMem->enc = 0;
59766 pMem->type = SQLITE_BLOB;
59767 if( key ){
59768 rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
59769 }else{
59770 rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
59772 pMem->z[amt] = 0;
59773 pMem->z[amt+1] = 0;
59774 if( rc!=SQLITE_OK ){
59775 sqlite3VdbeMemRelease(pMem);
59778 pMem->n = amt;
59780 return rc;
59783 /* This function is only available internally, it is not part of the
59784 ** external API. It works in a similar way to sqlite3_value_text(),
59785 ** except the data returned is in the encoding specified by the second
59786 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
59787 ** SQLITE_UTF8.
59789 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
59790 ** If that is the case, then the result must be aligned on an even byte
59791 ** boundary.
59793 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
59794 if( !pVal ) return 0;
59796 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
59797 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
59798 assert( (pVal->flags & MEM_RowSet)==0 );
59800 if( pVal->flags&MEM_Null ){
59801 return 0;
59803 assert( (MEM_Blob>>3) == MEM_Str );
59804 pVal->flags |= (pVal->flags & MEM_Blob)>>3;
59805 ExpandBlob(pVal);
59806 if( pVal->flags&MEM_Str ){
59807 sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
59808 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
59809 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
59810 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
59811 return 0;
59814 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
59815 }else{
59816 assert( (pVal->flags&MEM_Blob)==0 );
59817 sqlite3VdbeMemStringify(pVal, enc);
59818 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
59820 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
59821 || pVal->db->mallocFailed );
59822 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
59823 return pVal->z;
59824 }else{
59825 return 0;
59830 ** Create a new sqlite3_value object.
59832 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
59833 Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
59834 if( p ){
59835 p->flags = MEM_Null;
59836 p->type = SQLITE_NULL;
59837 p->db = db;
59839 return p;
59843 ** Create a new sqlite3_value object, containing the value of pExpr.
59845 ** This only works for very simple expressions that consist of one constant
59846 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
59847 ** be converted directly into a value, then the value is allocated and
59848 ** a pointer written to *ppVal. The caller is responsible for deallocating
59849 ** the value by passing it to sqlite3ValueFree() later on. If the expression
59850 ** cannot be converted to a value, then *ppVal is set to NULL.
59852 SQLITE_PRIVATE int sqlite3ValueFromExpr(
59853 sqlite3 *db, /* The database connection */
59854 Expr *pExpr, /* The expression to evaluate */
59855 u8 enc, /* Encoding to use */
59856 u8 affinity, /* Affinity to use */
59857 sqlite3_value **ppVal /* Write the new value here */
59859 int op;
59860 char *zVal = 0;
59861 sqlite3_value *pVal = 0;
59862 int negInt = 1;
59863 const char *zNeg = "";
59865 if( !pExpr ){
59866 *ppVal = 0;
59867 return SQLITE_OK;
59869 op = pExpr->op;
59871 /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
59872 ** The ifdef here is to enable us to achieve 100% branch test coverage even
59873 ** when SQLITE_ENABLE_STAT3 is omitted.
59875 #ifdef SQLITE_ENABLE_STAT3
59876 if( op==TK_REGISTER ) op = pExpr->op2;
59877 #else
59878 if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
59879 #endif
59881 /* Handle negative integers in a single step. This is needed in the
59882 ** case when the value is -9223372036854775808.
59884 if( op==TK_UMINUS
59885 && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
59886 pExpr = pExpr->pLeft;
59887 op = pExpr->op;
59888 negInt = -1;
59889 zNeg = "-";
59892 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
59893 pVal = sqlite3ValueNew(db);
59894 if( pVal==0 ) goto no_mem;
59895 if( ExprHasProperty(pExpr, EP_IntValue) ){
59896 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
59897 }else{
59898 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
59899 if( zVal==0 ) goto no_mem;
59900 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
59901 if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
59903 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
59904 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
59905 }else{
59906 sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
59908 if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
59909 if( enc!=SQLITE_UTF8 ){
59910 sqlite3VdbeChangeEncoding(pVal, enc);
59912 }else if( op==TK_UMINUS ) {
59913 /* This branch happens for multiple negative signs. Ex: -(-5) */
59914 if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
59915 sqlite3VdbeMemNumerify(pVal);
59916 if( pVal->u.i==SMALLEST_INT64 ){
59917 pVal->flags &= MEM_Int;
59918 pVal->flags |= MEM_Real;
59919 pVal->r = (double)LARGEST_INT64;
59920 }else{
59921 pVal->u.i = -pVal->u.i;
59923 pVal->r = -pVal->r;
59924 sqlite3ValueApplyAffinity(pVal, affinity, enc);
59926 }else if( op==TK_NULL ){
59927 pVal = sqlite3ValueNew(db);
59928 if( pVal==0 ) goto no_mem;
59930 #ifndef SQLITE_OMIT_BLOB_LITERAL
59931 else if( op==TK_BLOB ){
59932 int nVal;
59933 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
59934 assert( pExpr->u.zToken[1]=='\'' );
59935 pVal = sqlite3ValueNew(db);
59936 if( !pVal ) goto no_mem;
59937 zVal = &pExpr->u.zToken[2];
59938 nVal = sqlite3Strlen30(zVal)-1;
59939 assert( zVal[nVal]=='\'' );
59940 sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
59941 0, SQLITE_DYNAMIC);
59943 #endif
59945 if( pVal ){
59946 sqlite3VdbeMemStoreType(pVal);
59948 *ppVal = pVal;
59949 return SQLITE_OK;
59951 no_mem:
59952 db->mallocFailed = 1;
59953 sqlite3DbFree(db, zVal);
59954 sqlite3ValueFree(pVal);
59955 *ppVal = 0;
59956 return SQLITE_NOMEM;
59960 ** Change the string value of an sqlite3_value object
59962 SQLITE_PRIVATE void sqlite3ValueSetStr(
59963 sqlite3_value *v, /* Value to be set */
59964 int n, /* Length of string z */
59965 const void *z, /* Text of the new string */
59966 u8 enc, /* Encoding to use */
59967 void (*xDel)(void*) /* Destructor for the string */
59969 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
59973 ** Free an sqlite3_value object
59975 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
59976 if( !v ) return;
59977 sqlite3VdbeMemRelease((Mem *)v);
59978 sqlite3DbFree(((Mem*)v)->db, v);
59982 ** Return the number of bytes in the sqlite3_value object assuming
59983 ** that it uses the encoding "enc"
59985 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
59986 Mem *p = (Mem*)pVal;
59987 if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
59988 if( p->flags & MEM_Zero ){
59989 return p->n + p->u.nZero;
59990 }else{
59991 return p->n;
59994 return 0;
59997 /************** End of vdbemem.c *********************************************/
59998 /************** Begin file vdbeaux.c *****************************************/
60000 ** 2003 September 6
60002 ** The author disclaims copyright to this source code. In place of
60003 ** a legal notice, here is a blessing:
60005 ** May you do good and not evil.
60006 ** May you find forgiveness for yourself and forgive others.
60007 ** May you share freely, never taking more than you give.
60009 *************************************************************************
60010 ** This file contains code used for creating, destroying, and populating
60011 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
60012 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
60013 ** But that file was getting too big so this subroutines were split out.
60017 ** Create a new virtual database engine.
60019 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
60020 Vdbe *p;
60021 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
60022 if( p==0 ) return 0;
60023 p->db = db;
60024 if( db->pVdbe ){
60025 db->pVdbe->pPrev = p;
60027 p->pNext = db->pVdbe;
60028 p->pPrev = 0;
60029 db->pVdbe = p;
60030 p->magic = VDBE_MAGIC_INIT;
60031 return p;
60035 ** Remember the SQL string for a prepared statement.
60037 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
60038 assert( isPrepareV2==1 || isPrepareV2==0 );
60039 if( p==0 ) return;
60040 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
60041 if( !isPrepareV2 ) return;
60042 #endif
60043 assert( p->zSql==0 );
60044 p->zSql = sqlite3DbStrNDup(p->db, z, n);
60045 p->isPrepareV2 = (u8)isPrepareV2;
60049 ** Return the SQL associated with a prepared statement
60051 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
60052 Vdbe *p = (Vdbe *)pStmt;
60053 return (p && p->isPrepareV2) ? p->zSql : 0;
60057 ** Swap all content between two VDBE structures.
60059 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
60060 Vdbe tmp, *pTmp;
60061 char *zTmp;
60062 tmp = *pA;
60063 *pA = *pB;
60064 *pB = tmp;
60065 pTmp = pA->pNext;
60066 pA->pNext = pB->pNext;
60067 pB->pNext = pTmp;
60068 pTmp = pA->pPrev;
60069 pA->pPrev = pB->pPrev;
60070 pB->pPrev = pTmp;
60071 zTmp = pA->zSql;
60072 pA->zSql = pB->zSql;
60073 pB->zSql = zTmp;
60074 pB->isPrepareV2 = pA->isPrepareV2;
60077 #ifdef SQLITE_DEBUG
60079 ** Turn tracing on or off
60081 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
60082 p->trace = trace;
60084 #endif
60087 ** Resize the Vdbe.aOp array so that it is at least one op larger than
60088 ** it was.
60090 ** If an out-of-memory error occurs while resizing the array, return
60091 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
60092 ** unchanged (this is so that any opcodes already allocated can be
60093 ** correctly deallocated along with the rest of the Vdbe).
60095 static int growOpArray(Vdbe *p){
60096 VdbeOp *pNew;
60097 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
60098 pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
60099 if( pNew ){
60100 p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
60101 p->aOp = pNew;
60103 return (pNew ? SQLITE_OK : SQLITE_NOMEM);
60107 ** Add a new instruction to the list of instructions current in the
60108 ** VDBE. Return the address of the new instruction.
60110 ** Parameters:
60112 ** p Pointer to the VDBE
60114 ** op The opcode for this instruction
60116 ** p1, p2, p3 Operands
60118 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
60119 ** the sqlite3VdbeChangeP4() function to change the value of the P4
60120 ** operand.
60122 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
60123 int i;
60124 VdbeOp *pOp;
60126 i = p->nOp;
60127 assert( p->magic==VDBE_MAGIC_INIT );
60128 assert( op>0 && op<0xff );
60129 if( p->nOpAlloc<=i ){
60130 if( growOpArray(p) ){
60131 return 1;
60134 p->nOp++;
60135 pOp = &p->aOp[i];
60136 pOp->opcode = (u8)op;
60137 pOp->p5 = 0;
60138 pOp->p1 = p1;
60139 pOp->p2 = p2;
60140 pOp->p3 = p3;
60141 pOp->p4.p = 0;
60142 pOp->p4type = P4_NOTUSED;
60143 #ifdef SQLITE_DEBUG
60144 pOp->zComment = 0;
60145 if( p->db->flags & SQLITE_VdbeAddopTrace ){
60146 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
60148 #endif
60149 #ifdef VDBE_PROFILE
60150 pOp->cycles = 0;
60151 pOp->cnt = 0;
60152 #endif
60153 return i;
60155 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
60156 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
60158 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
60159 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
60161 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
60162 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
60167 ** Add an opcode that includes the p4 value as a pointer.
60169 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
60170 Vdbe *p, /* Add the opcode to this VM */
60171 int op, /* The new opcode */
60172 int p1, /* The P1 operand */
60173 int p2, /* The P2 operand */
60174 int p3, /* The P3 operand */
60175 const char *zP4, /* The P4 operand */
60176 int p4type /* P4 operand type */
60178 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
60179 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
60180 return addr;
60184 ** Add an OP_ParseSchema opcode. This routine is broken out from
60185 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
60186 ** as having been used.
60188 ** The zWhere string must have been obtained from sqlite3_malloc().
60189 ** This routine will take ownership of the allocated memory.
60191 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
60192 int j;
60193 int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
60194 sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
60195 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
60199 ** Add an opcode that includes the p4 value as an integer.
60201 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
60202 Vdbe *p, /* Add the opcode to this VM */
60203 int op, /* The new opcode */
60204 int p1, /* The P1 operand */
60205 int p2, /* The P2 operand */
60206 int p3, /* The P3 operand */
60207 int p4 /* The P4 operand as an integer */
60209 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
60210 sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
60211 return addr;
60215 ** Create a new symbolic label for an instruction that has yet to be
60216 ** coded. The symbolic label is really just a negative number. The
60217 ** label can be used as the P2 value of an operation. Later, when
60218 ** the label is resolved to a specific address, the VDBE will scan
60219 ** through its operation list and change all values of P2 which match
60220 ** the label into the resolved address.
60222 ** The VDBE knows that a P2 value is a label because labels are
60223 ** always negative and P2 values are suppose to be non-negative.
60224 ** Hence, a negative P2 value is a label that has yet to be resolved.
60226 ** Zero is returned if a malloc() fails.
60228 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
60229 int i = p->nLabel++;
60230 assert( p->magic==VDBE_MAGIC_INIT );
60231 if( (i & (i-1))==0 ){
60232 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
60233 (i*2+1)*sizeof(p->aLabel[0]));
60235 if( p->aLabel ){
60236 p->aLabel[i] = -1;
60238 return -1-i;
60242 ** Resolve label "x" to be the address of the next instruction to
60243 ** be inserted. The parameter "x" must have been obtained from
60244 ** a prior call to sqlite3VdbeMakeLabel().
60246 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
60247 int j = -1-x;
60248 assert( p->magic==VDBE_MAGIC_INIT );
60249 assert( j<p->nLabel );
60250 if( j>=0 && p->aLabel ){
60251 p->aLabel[j] = p->nOp;
60256 ** Mark the VDBE as one that can only be run one time.
60258 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
60259 p->runOnlyOnce = 1;
60262 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
60265 ** The following type and function are used to iterate through all opcodes
60266 ** in a Vdbe main program and each of the sub-programs (triggers) it may
60267 ** invoke directly or indirectly. It should be used as follows:
60269 ** Op *pOp;
60270 ** VdbeOpIter sIter;
60272 ** memset(&sIter, 0, sizeof(sIter));
60273 ** sIter.v = v; // v is of type Vdbe*
60274 ** while( (pOp = opIterNext(&sIter)) ){
60275 ** // Do something with pOp
60276 ** }
60277 ** sqlite3DbFree(v->db, sIter.apSub);
60280 typedef struct VdbeOpIter VdbeOpIter;
60281 struct VdbeOpIter {
60282 Vdbe *v; /* Vdbe to iterate through the opcodes of */
60283 SubProgram **apSub; /* Array of subprograms */
60284 int nSub; /* Number of entries in apSub */
60285 int iAddr; /* Address of next instruction to return */
60286 int iSub; /* 0 = main program, 1 = first sub-program etc. */
60288 static Op *opIterNext(VdbeOpIter *p){
60289 Vdbe *v = p->v;
60290 Op *pRet = 0;
60291 Op *aOp;
60292 int nOp;
60294 if( p->iSub<=p->nSub ){
60296 if( p->iSub==0 ){
60297 aOp = v->aOp;
60298 nOp = v->nOp;
60299 }else{
60300 aOp = p->apSub[p->iSub-1]->aOp;
60301 nOp = p->apSub[p->iSub-1]->nOp;
60303 assert( p->iAddr<nOp );
60305 pRet = &aOp[p->iAddr];
60306 p->iAddr++;
60307 if( p->iAddr==nOp ){
60308 p->iSub++;
60309 p->iAddr = 0;
60312 if( pRet->p4type==P4_SUBPROGRAM ){
60313 int nByte = (p->nSub+1)*sizeof(SubProgram*);
60314 int j;
60315 for(j=0; j<p->nSub; j++){
60316 if( p->apSub[j]==pRet->p4.pProgram ) break;
60318 if( j==p->nSub ){
60319 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
60320 if( !p->apSub ){
60321 pRet = 0;
60322 }else{
60323 p->apSub[p->nSub++] = pRet->p4.pProgram;
60329 return pRet;
60333 ** Check if the program stored in the VM associated with pParse may
60334 ** throw an ABORT exception (causing the statement, but not entire transaction
60335 ** to be rolled back). This condition is true if the main program or any
60336 ** sub-programs contains any of the following:
60338 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
60339 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
60340 ** * OP_Destroy
60341 ** * OP_VUpdate
60342 ** * OP_VRename
60343 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
60345 ** Then check that the value of Parse.mayAbort is true if an
60346 ** ABORT may be thrown, or false otherwise. Return true if it does
60347 ** match, or false otherwise. This function is intended to be used as
60348 ** part of an assert statement in the compiler. Similar to:
60350 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
60352 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
60353 int hasAbort = 0;
60354 Op *pOp;
60355 VdbeOpIter sIter;
60356 memset(&sIter, 0, sizeof(sIter));
60357 sIter.v = v;
60359 while( (pOp = opIterNext(&sIter))!=0 ){
60360 int opcode = pOp->opcode;
60361 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
60362 #ifndef SQLITE_OMIT_FOREIGN_KEY
60363 || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
60364 #endif
60365 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
60366 && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
60368 hasAbort = 1;
60369 break;
60372 sqlite3DbFree(v->db, sIter.apSub);
60374 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
60375 ** If malloc failed, then the while() loop above may not have iterated
60376 ** through all opcodes and hasAbort may be set incorrectly. Return
60377 ** true for this case to prevent the assert() in the callers frame
60378 ** from failing. */
60379 return ( v->db->mallocFailed || hasAbort==mayAbort );
60381 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
60384 ** Loop through the program looking for P2 values that are negative
60385 ** on jump instructions. Each such value is a label. Resolve the
60386 ** label by setting the P2 value to its correct non-zero value.
60388 ** This routine is called once after all opcodes have been inserted.
60390 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
60391 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
60392 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
60394 ** The Op.opflags field is set on all opcodes.
60396 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
60397 int i;
60398 int nMaxArgs = *pMaxFuncArgs;
60399 Op *pOp;
60400 int *aLabel = p->aLabel;
60401 p->readOnly = 1;
60402 p->bIsReader = 0;
60403 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
60404 u8 opcode = pOp->opcode;
60406 /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
60407 ** cases from this switch! */
60408 switch( opcode ){
60409 case OP_Function:
60410 case OP_AggStep: {
60411 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
60412 break;
60414 case OP_Transaction: {
60415 if( pOp->p2!=0 ) p->readOnly = 0;
60416 /* fall thru */
60418 case OP_AutoCommit:
60419 case OP_Savepoint: {
60420 p->bIsReader = 1;
60421 break;
60423 #ifndef SQLITE_OMIT_WAL
60424 case OP_Checkpoint:
60425 #endif
60426 case OP_Vacuum:
60427 case OP_JournalMode: {
60428 p->readOnly = 0;
60429 p->bIsReader = 1;
60430 break;
60432 #ifndef SQLITE_OMIT_VIRTUALTABLE
60433 case OP_VUpdate: {
60434 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
60435 break;
60437 case OP_VFilter: {
60438 int n;
60439 assert( p->nOp - i >= 3 );
60440 assert( pOp[-1].opcode==OP_Integer );
60441 n = pOp[-1].p1;
60442 if( n>nMaxArgs ) nMaxArgs = n;
60443 break;
60445 #endif
60446 case OP_Next:
60447 case OP_SorterNext: {
60448 pOp->p4.xAdvance = sqlite3BtreeNext;
60449 pOp->p4type = P4_ADVANCE;
60450 break;
60452 case OP_Prev: {
60453 pOp->p4.xAdvance = sqlite3BtreePrevious;
60454 pOp->p4type = P4_ADVANCE;
60455 break;
60459 pOp->opflags = sqlite3OpcodeProperty[opcode];
60460 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
60461 assert( -1-pOp->p2<p->nLabel );
60462 pOp->p2 = aLabel[-1-pOp->p2];
60465 sqlite3DbFree(p->db, p->aLabel);
60466 p->aLabel = 0;
60467 *pMaxFuncArgs = nMaxArgs;
60468 assert( p->bIsReader!=0 || p->btreeMask==0 );
60472 ** Return the address of the next instruction to be inserted.
60474 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
60475 assert( p->magic==VDBE_MAGIC_INIT );
60476 return p->nOp;
60480 ** This function returns a pointer to the array of opcodes associated with
60481 ** the Vdbe passed as the first argument. It is the callers responsibility
60482 ** to arrange for the returned array to be eventually freed using the
60483 ** vdbeFreeOpArray() function.
60485 ** Before returning, *pnOp is set to the number of entries in the returned
60486 ** array. Also, *pnMaxArg is set to the larger of its current value and
60487 ** the number of entries in the Vdbe.apArg[] array required to execute the
60488 ** returned program.
60490 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
60491 VdbeOp *aOp = p->aOp;
60492 assert( aOp && !p->db->mallocFailed );
60494 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
60495 assert( p->btreeMask==0 );
60497 resolveP2Values(p, pnMaxArg);
60498 *pnOp = p->nOp;
60499 p->aOp = 0;
60500 return aOp;
60504 ** Add a whole list of operations to the operation stack. Return the
60505 ** address of the first operation added.
60507 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
60508 int addr;
60509 assert( p->magic==VDBE_MAGIC_INIT );
60510 if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
60511 return 0;
60513 addr = p->nOp;
60514 if( ALWAYS(nOp>0) ){
60515 int i;
60516 VdbeOpList const *pIn = aOp;
60517 for(i=0; i<nOp; i++, pIn++){
60518 int p2 = pIn->p2;
60519 VdbeOp *pOut = &p->aOp[i+addr];
60520 pOut->opcode = pIn->opcode;
60521 pOut->p1 = pIn->p1;
60522 if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
60523 pOut->p2 = addr + ADDR(p2);
60524 }else{
60525 pOut->p2 = p2;
60527 pOut->p3 = pIn->p3;
60528 pOut->p4type = P4_NOTUSED;
60529 pOut->p4.p = 0;
60530 pOut->p5 = 0;
60531 #ifdef SQLITE_DEBUG
60532 pOut->zComment = 0;
60533 if( p->db->flags & SQLITE_VdbeAddopTrace ){
60534 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
60536 #endif
60538 p->nOp += nOp;
60540 return addr;
60544 ** Change the value of the P1 operand for a specific instruction.
60545 ** This routine is useful when a large program is loaded from a
60546 ** static array using sqlite3VdbeAddOpList but we want to make a
60547 ** few minor changes to the program.
60549 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
60550 assert( p!=0 );
60551 if( ((u32)p->nOp)>addr ){
60552 p->aOp[addr].p1 = val;
60557 ** Change the value of the P2 operand for a specific instruction.
60558 ** This routine is useful for setting a jump destination.
60560 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
60561 assert( p!=0 );
60562 if( ((u32)p->nOp)>addr ){
60563 p->aOp[addr].p2 = val;
60568 ** Change the value of the P3 operand for a specific instruction.
60570 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
60571 assert( p!=0 );
60572 if( ((u32)p->nOp)>addr ){
60573 p->aOp[addr].p3 = val;
60578 ** Change the value of the P5 operand for the most recently
60579 ** added operation.
60581 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
60582 assert( p!=0 );
60583 if( p->aOp ){
60584 assert( p->nOp>0 );
60585 p->aOp[p->nOp-1].p5 = val;
60590 ** Change the P2 operand of instruction addr so that it points to
60591 ** the address of the next instruction to be coded.
60593 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
60594 if( ALWAYS(addr>=0) ) sqlite3VdbeChangeP2(p, addr, p->nOp);
60599 ** If the input FuncDef structure is ephemeral, then free it. If
60600 ** the FuncDef is not ephermal, then do nothing.
60602 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
60603 if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
60604 sqlite3DbFree(db, pDef);
60608 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
60611 ** Delete a P4 value if necessary.
60613 static void freeP4(sqlite3 *db, int p4type, void *p4){
60614 if( p4 ){
60615 assert( db );
60616 switch( p4type ){
60617 case P4_REAL:
60618 case P4_INT64:
60619 case P4_DYNAMIC:
60620 case P4_KEYINFO:
60621 case P4_INTARRAY:
60622 case P4_KEYINFO_HANDOFF: {
60623 sqlite3DbFree(db, p4);
60624 break;
60626 case P4_MPRINTF: {
60627 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
60628 break;
60630 case P4_FUNCDEF: {
60631 freeEphemeralFunction(db, (FuncDef*)p4);
60632 break;
60634 case P4_MEM: {
60635 if( db->pnBytesFreed==0 ){
60636 sqlite3ValueFree((sqlite3_value*)p4);
60637 }else{
60638 Mem *p = (Mem*)p4;
60639 sqlite3DbFree(db, p->zMalloc);
60640 sqlite3DbFree(db, p);
60642 break;
60644 case P4_VTAB : {
60645 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
60646 break;
60653 ** Free the space allocated for aOp and any p4 values allocated for the
60654 ** opcodes contained within. If aOp is not NULL it is assumed to contain
60655 ** nOp entries.
60657 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
60658 if( aOp ){
60659 Op *pOp;
60660 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
60661 freeP4(db, pOp->p4type, pOp->p4.p);
60662 #ifdef SQLITE_DEBUG
60663 sqlite3DbFree(db, pOp->zComment);
60664 #endif
60667 sqlite3DbFree(db, aOp);
60671 ** Link the SubProgram object passed as the second argument into the linked
60672 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
60673 ** objects when the VM is no longer required.
60675 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
60676 p->pNext = pVdbe->pProgram;
60677 pVdbe->pProgram = p;
60681 ** Change the opcode at addr into OP_Noop
60683 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
60684 if( p->aOp ){
60685 VdbeOp *pOp = &p->aOp[addr];
60686 sqlite3 *db = p->db;
60687 freeP4(db, pOp->p4type, pOp->p4.p);
60688 memset(pOp, 0, sizeof(pOp[0]));
60689 pOp->opcode = OP_Noop;
60694 ** Change the value of the P4 operand for a specific instruction.
60695 ** This routine is useful when a large program is loaded from a
60696 ** static array using sqlite3VdbeAddOpList but we want to make a
60697 ** few minor changes to the program.
60699 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
60700 ** the string is made into memory obtained from sqlite3_malloc().
60701 ** A value of n==0 means copy bytes of zP4 up to and including the
60702 ** first null byte. If n>0 then copy n+1 bytes of zP4.
60704 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
60705 ** A copy is made of the KeyInfo structure into memory obtained from
60706 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
60707 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
60708 ** stored in memory that the caller has obtained from sqlite3_malloc. The
60709 ** caller should not free the allocation, it will be freed when the Vdbe is
60710 ** finalized.
60712 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
60713 ** to a string or structure that is guaranteed to exist for the lifetime of
60714 ** the Vdbe. In these cases we can just copy the pointer.
60716 ** If addr<0 then change P4 on the most recently inserted instruction.
60718 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
60719 Op *pOp;
60720 sqlite3 *db;
60721 assert( p!=0 );
60722 db = p->db;
60723 assert( p->magic==VDBE_MAGIC_INIT );
60724 if( p->aOp==0 || db->mallocFailed ){
60725 if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
60726 freeP4(db, n, (void*)*(char**)&zP4);
60728 return;
60730 assert( p->nOp>0 );
60731 assert( addr<p->nOp );
60732 if( addr<0 ){
60733 addr = p->nOp - 1;
60735 pOp = &p->aOp[addr];
60736 assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
60737 freeP4(db, pOp->p4type, pOp->p4.p);
60738 pOp->p4.p = 0;
60739 if( n==P4_INT32 ){
60740 /* Note: this cast is safe, because the origin data point was an int
60741 ** that was cast to a (const char *). */
60742 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
60743 pOp->p4type = P4_INT32;
60744 }else if( zP4==0 ){
60745 pOp->p4.p = 0;
60746 pOp->p4type = P4_NOTUSED;
60747 }else if( n==P4_KEYINFO ){
60748 KeyInfo *pOrig, *pNew;
60750 pOrig = (KeyInfo*)zP4;
60751 pOp->p4.pKeyInfo = pNew = sqlite3KeyInfoAlloc(db, pOrig->nField);
60752 if( pNew ){
60753 memcpy(pNew->aColl, pOrig->aColl, pOrig->nField*sizeof(pNew->aColl[0]));
60754 memcpy(pNew->aSortOrder, pOrig->aSortOrder, pOrig->nField);
60755 pOp->p4type = P4_KEYINFO;
60756 }else{
60757 p->db->mallocFailed = 1;
60758 pOp->p4type = P4_NOTUSED;
60760 }else if( n==P4_KEYINFO_HANDOFF ){
60761 pOp->p4.p = (void*)zP4;
60762 pOp->p4type = P4_KEYINFO;
60763 }else if( n==P4_VTAB ){
60764 pOp->p4.p = (void*)zP4;
60765 pOp->p4type = P4_VTAB;
60766 sqlite3VtabLock((VTable *)zP4);
60767 assert( ((VTable *)zP4)->db==p->db );
60768 }else if( n<0 ){
60769 pOp->p4.p = (void*)zP4;
60770 pOp->p4type = (signed char)n;
60771 }else{
60772 if( n==0 ) n = sqlite3Strlen30(zP4);
60773 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
60774 pOp->p4type = P4_DYNAMIC;
60778 #ifndef NDEBUG
60780 ** Change the comment on the most recently coded instruction. Or
60781 ** insert a No-op and add the comment to that new instruction. This
60782 ** makes the code easier to read during debugging. None of this happens
60783 ** in a production build.
60785 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
60786 assert( p->nOp>0 || p->aOp==0 );
60787 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
60788 if( p->nOp ){
60789 assert( p->aOp );
60790 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
60791 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
60794 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
60795 va_list ap;
60796 if( p ){
60797 va_start(ap, zFormat);
60798 vdbeVComment(p, zFormat, ap);
60799 va_end(ap);
60802 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
60803 va_list ap;
60804 if( p ){
60805 sqlite3VdbeAddOp0(p, OP_Noop);
60806 va_start(ap, zFormat);
60807 vdbeVComment(p, zFormat, ap);
60808 va_end(ap);
60811 #endif /* NDEBUG */
60814 ** Return the opcode for a given address. If the address is -1, then
60815 ** return the most recently inserted opcode.
60817 ** If a memory allocation error has occurred prior to the calling of this
60818 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
60819 ** is readable but not writable, though it is cast to a writable value.
60820 ** The return of a dummy opcode allows the call to continue functioning
60821 ** after a OOM fault without having to check to see if the return from
60822 ** this routine is a valid pointer. But because the dummy.opcode is 0,
60823 ** dummy will never be written to. This is verified by code inspection and
60824 ** by running with Valgrind.
60826 ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
60827 ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
60828 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
60829 ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
60830 ** having to double-check to make sure that the result is non-negative. But
60831 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
60832 ** check the value of p->nOp-1 before continuing.
60834 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
60835 /* C89 specifies that the constant "dummy" will be initialized to all
60836 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
60837 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
60838 assert( p->magic==VDBE_MAGIC_INIT );
60839 if( addr<0 ){
60840 #ifdef SQLITE_OMIT_TRACE
60841 if( p->nOp==0 ) return (VdbeOp*)&dummy;
60842 #endif
60843 addr = p->nOp - 1;
60845 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
60846 if( p->db->mallocFailed ){
60847 return (VdbeOp*)&dummy;
60848 }else{
60849 return &p->aOp[addr];
60853 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
60854 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
60856 ** Compute a string that describes the P4 parameter for an opcode.
60857 ** Use zTemp for any required temporary buffer space.
60859 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
60860 char *zP4 = zTemp;
60861 assert( nTemp>=20 );
60862 switch( pOp->p4type ){
60863 case P4_KEYINFO_STATIC:
60864 case P4_KEYINFO: {
60865 int i, j;
60866 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
60867 assert( pKeyInfo->aSortOrder!=0 );
60868 sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
60869 i = sqlite3Strlen30(zTemp);
60870 for(j=0; j<pKeyInfo->nField; j++){
60871 CollSeq *pColl = pKeyInfo->aColl[j];
60872 const char *zColl = pColl ? pColl->zName : "nil";
60873 int n = sqlite3Strlen30(zColl);
60874 if( i+n>nTemp-6 ){
60875 memcpy(&zTemp[i],",...",4);
60876 break;
60878 zTemp[i++] = ',';
60879 if( pKeyInfo->aSortOrder[j] ){
60880 zTemp[i++] = '-';
60882 memcpy(&zTemp[i], zColl, n+1);
60883 i += n;
60885 zTemp[i++] = ')';
60886 zTemp[i] = 0;
60887 assert( i<nTemp );
60888 break;
60890 case P4_COLLSEQ: {
60891 CollSeq *pColl = pOp->p4.pColl;
60892 sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
60893 break;
60895 case P4_FUNCDEF: {
60896 FuncDef *pDef = pOp->p4.pFunc;
60897 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
60898 break;
60900 case P4_INT64: {
60901 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
60902 break;
60904 case P4_INT32: {
60905 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
60906 break;
60908 case P4_REAL: {
60909 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
60910 break;
60912 case P4_MEM: {
60913 Mem *pMem = pOp->p4.pMem;
60914 if( pMem->flags & MEM_Str ){
60915 zP4 = pMem->z;
60916 }else if( pMem->flags & MEM_Int ){
60917 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
60918 }else if( pMem->flags & MEM_Real ){
60919 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
60920 }else if( pMem->flags & MEM_Null ){
60921 sqlite3_snprintf(nTemp, zTemp, "NULL");
60922 }else{
60923 assert( pMem->flags & MEM_Blob );
60924 zP4 = "(blob)";
60926 break;
60928 #ifndef SQLITE_OMIT_VIRTUALTABLE
60929 case P4_VTAB: {
60930 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
60931 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
60932 break;
60934 #endif
60935 case P4_INTARRAY: {
60936 sqlite3_snprintf(nTemp, zTemp, "intarray");
60937 break;
60939 case P4_SUBPROGRAM: {
60940 sqlite3_snprintf(nTemp, zTemp, "program");
60941 break;
60943 case P4_ADVANCE: {
60944 zTemp[0] = 0;
60945 break;
60947 default: {
60948 zP4 = pOp->p4.z;
60949 if( zP4==0 ){
60950 zP4 = zTemp;
60951 zTemp[0] = 0;
60955 assert( zP4!=0 );
60956 return zP4;
60958 #endif
60961 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
60963 ** The prepared statements need to know in advance the complete set of
60964 ** attached databases that will be use. A mask of these databases
60965 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
60966 ** p->btreeMask of databases that will require a lock.
60968 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
60969 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
60970 assert( i<(int)sizeof(p->btreeMask)*8 );
60971 p->btreeMask |= ((yDbMask)1)<<i;
60972 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
60973 p->lockMask |= ((yDbMask)1)<<i;
60977 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
60979 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
60980 ** this routine obtains the mutex associated with each BtShared structure
60981 ** that may be accessed by the VM passed as an argument. In doing so it also
60982 ** sets the BtShared.db member of each of the BtShared structures, ensuring
60983 ** that the correct busy-handler callback is invoked if required.
60985 ** If SQLite is not threadsafe but does support shared-cache mode, then
60986 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
60987 ** of all of BtShared structures accessible via the database handle
60988 ** associated with the VM.
60990 ** If SQLite is not threadsafe and does not support shared-cache mode, this
60991 ** function is a no-op.
60993 ** The p->btreeMask field is a bitmask of all btrees that the prepared
60994 ** statement p will ever use. Let N be the number of bits in p->btreeMask
60995 ** corresponding to btrees that use shared cache. Then the runtime of
60996 ** this routine is N*N. But as N is rarely more than 1, this should not
60997 ** be a problem.
60999 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
61000 int i;
61001 yDbMask mask;
61002 sqlite3 *db;
61003 Db *aDb;
61004 int nDb;
61005 if( p->lockMask==0 ) return; /* The common case */
61006 db = p->db;
61007 aDb = db->aDb;
61008 nDb = db->nDb;
61009 for(i=0, mask=1; i<nDb; i++, mask += mask){
61010 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
61011 sqlite3BtreeEnter(aDb[i].pBt);
61015 #endif
61017 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
61019 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
61021 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
61022 int i;
61023 yDbMask mask;
61024 sqlite3 *db;
61025 Db *aDb;
61026 int nDb;
61027 if( p->lockMask==0 ) return; /* The common case */
61028 db = p->db;
61029 aDb = db->aDb;
61030 nDb = db->nDb;
61031 for(i=0, mask=1; i<nDb; i++, mask += mask){
61032 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
61033 sqlite3BtreeLeave(aDb[i].pBt);
61037 #endif
61039 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
61041 ** Print a single opcode. This routine is used for debugging only.
61043 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
61044 char *zP4;
61045 char zPtr[50];
61046 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
61047 if( pOut==0 ) pOut = stdout;
61048 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
61049 fprintf(pOut, zFormat1, pc,
61050 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
61051 #ifdef SQLITE_DEBUG
61052 pOp->zComment ? pOp->zComment : ""
61053 #else
61055 #endif
61057 fflush(pOut);
61059 #endif
61062 ** Release an array of N Mem elements
61064 static void releaseMemArray(Mem *p, int N){
61065 if( p && N ){
61066 Mem *pEnd;
61067 sqlite3 *db = p->db;
61068 u8 malloc_failed = db->mallocFailed;
61069 if( db->pnBytesFreed ){
61070 for(pEnd=&p[N]; p<pEnd; p++){
61071 sqlite3DbFree(db, p->zMalloc);
61073 return;
61075 for(pEnd=&p[N]; p<pEnd; p++){
61076 assert( (&p[1])==pEnd || p[0].db==p[1].db );
61078 /* This block is really an inlined version of sqlite3VdbeMemRelease()
61079 ** that takes advantage of the fact that the memory cell value is
61080 ** being set to NULL after releasing any dynamic resources.
61082 ** The justification for duplicating code is that according to
61083 ** callgrind, this causes a certain test case to hit the CPU 4.7
61084 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
61085 ** sqlite3MemRelease() were called from here. With -O2, this jumps
61086 ** to 6.6 percent. The test case is inserting 1000 rows into a table
61087 ** with no indexes using a single prepared INSERT statement, bind()
61088 ** and reset(). Inserts are grouped into a transaction.
61090 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
61091 sqlite3VdbeMemRelease(p);
61092 }else if( p->zMalloc ){
61093 sqlite3DbFree(db, p->zMalloc);
61094 p->zMalloc = 0;
61097 p->flags = MEM_Invalid;
61099 db->mallocFailed = malloc_failed;
61104 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
61105 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
61107 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
61108 int i;
61109 Mem *aMem = VdbeFrameMem(p);
61110 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
61111 for(i=0; i<p->nChildCsr; i++){
61112 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
61114 releaseMemArray(aMem, p->nChildMem);
61115 sqlite3DbFree(p->v->db, p);
61118 #ifndef SQLITE_OMIT_EXPLAIN
61120 ** Give a listing of the program in the virtual machine.
61122 ** The interface is the same as sqlite3VdbeExec(). But instead of
61123 ** running the code, it invokes the callback once for each instruction.
61124 ** This feature is used to implement "EXPLAIN".
61126 ** When p->explain==1, each instruction is listed. When
61127 ** p->explain==2, only OP_Explain instructions are listed and these
61128 ** are shown in a different format. p->explain==2 is used to implement
61129 ** EXPLAIN QUERY PLAN.
61131 ** When p->explain==1, first the main program is listed, then each of
61132 ** the trigger subprograms are listed one by one.
61134 SQLITE_PRIVATE int sqlite3VdbeList(
61135 Vdbe *p /* The VDBE */
61137 int nRow; /* Stop when row count reaches this */
61138 int nSub = 0; /* Number of sub-vdbes seen so far */
61139 SubProgram **apSub = 0; /* Array of sub-vdbes */
61140 Mem *pSub = 0; /* Memory cell hold array of subprogs */
61141 sqlite3 *db = p->db; /* The database connection */
61142 int i; /* Loop counter */
61143 int rc = SQLITE_OK; /* Return code */
61144 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
61146 assert( p->explain );
61147 assert( p->magic==VDBE_MAGIC_RUN );
61148 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
61150 /* Even though this opcode does not use dynamic strings for
61151 ** the result, result columns may become dynamic if the user calls
61152 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
61154 releaseMemArray(pMem, 8);
61155 p->pResultSet = 0;
61157 if( p->rc==SQLITE_NOMEM ){
61158 /* This happens if a malloc() inside a call to sqlite3_column_text() or
61159 ** sqlite3_column_text16() failed. */
61160 db->mallocFailed = 1;
61161 return SQLITE_ERROR;
61164 /* When the number of output rows reaches nRow, that means the
61165 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
61166 ** nRow is the sum of the number of rows in the main program, plus
61167 ** the sum of the number of rows in all trigger subprograms encountered
61168 ** so far. The nRow value will increase as new trigger subprograms are
61169 ** encountered, but p->pc will eventually catch up to nRow.
61171 nRow = p->nOp;
61172 if( p->explain==1 ){
61173 /* The first 8 memory cells are used for the result set. So we will
61174 ** commandeer the 9th cell to use as storage for an array of pointers
61175 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
61176 ** cells. */
61177 assert( p->nMem>9 );
61178 pSub = &p->aMem[9];
61179 if( pSub->flags&MEM_Blob ){
61180 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
61181 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
61182 nSub = pSub->n/sizeof(Vdbe*);
61183 apSub = (SubProgram **)pSub->z;
61185 for(i=0; i<nSub; i++){
61186 nRow += apSub[i]->nOp;
61191 i = p->pc++;
61192 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
61193 if( i>=nRow ){
61194 p->rc = SQLITE_OK;
61195 rc = SQLITE_DONE;
61196 }else if( db->u1.isInterrupted ){
61197 p->rc = SQLITE_INTERRUPT;
61198 rc = SQLITE_ERROR;
61199 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
61200 }else{
61201 char *z;
61202 Op *pOp;
61203 if( i<p->nOp ){
61204 /* The output line number is small enough that we are still in the
61205 ** main program. */
61206 pOp = &p->aOp[i];
61207 }else{
61208 /* We are currently listing subprograms. Figure out which one and
61209 ** pick up the appropriate opcode. */
61210 int j;
61211 i -= p->nOp;
61212 for(j=0; i>=apSub[j]->nOp; j++){
61213 i -= apSub[j]->nOp;
61215 pOp = &apSub[j]->aOp[i];
61217 if( p->explain==1 ){
61218 pMem->flags = MEM_Int;
61219 pMem->type = SQLITE_INTEGER;
61220 pMem->u.i = i; /* Program counter */
61221 pMem++;
61223 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
61224 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
61225 assert( pMem->z!=0 );
61226 pMem->n = sqlite3Strlen30(pMem->z);
61227 pMem->type = SQLITE_TEXT;
61228 pMem->enc = SQLITE_UTF8;
61229 pMem++;
61231 /* When an OP_Program opcode is encounter (the only opcode that has
61232 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
61233 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
61234 ** has not already been seen.
61236 if( pOp->p4type==P4_SUBPROGRAM ){
61237 int nByte = (nSub+1)*sizeof(SubProgram*);
61238 int j;
61239 for(j=0; j<nSub; j++){
61240 if( apSub[j]==pOp->p4.pProgram ) break;
61242 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
61243 apSub = (SubProgram **)pSub->z;
61244 apSub[nSub++] = pOp->p4.pProgram;
61245 pSub->flags |= MEM_Blob;
61246 pSub->n = nSub*sizeof(SubProgram*);
61251 pMem->flags = MEM_Int;
61252 pMem->u.i = pOp->p1; /* P1 */
61253 pMem->type = SQLITE_INTEGER;
61254 pMem++;
61256 pMem->flags = MEM_Int;
61257 pMem->u.i = pOp->p2; /* P2 */
61258 pMem->type = SQLITE_INTEGER;
61259 pMem++;
61261 pMem->flags = MEM_Int;
61262 pMem->u.i = pOp->p3; /* P3 */
61263 pMem->type = SQLITE_INTEGER;
61264 pMem++;
61266 if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
61267 assert( p->db->mallocFailed );
61268 return SQLITE_ERROR;
61270 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
61271 z = displayP4(pOp, pMem->z, 32);
61272 if( z!=pMem->z ){
61273 sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
61274 }else{
61275 assert( pMem->z!=0 );
61276 pMem->n = sqlite3Strlen30(pMem->z);
61277 pMem->enc = SQLITE_UTF8;
61279 pMem->type = SQLITE_TEXT;
61280 pMem++;
61282 if( p->explain==1 ){
61283 if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
61284 assert( p->db->mallocFailed );
61285 return SQLITE_ERROR;
61287 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
61288 pMem->n = 2;
61289 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
61290 pMem->type = SQLITE_TEXT;
61291 pMem->enc = SQLITE_UTF8;
61292 pMem++;
61294 #ifdef SQLITE_DEBUG
61295 if( pOp->zComment ){
61296 pMem->flags = MEM_Str|MEM_Term;
61297 pMem->z = pOp->zComment;
61298 pMem->n = sqlite3Strlen30(pMem->z);
61299 pMem->enc = SQLITE_UTF8;
61300 pMem->type = SQLITE_TEXT;
61301 }else
61302 #endif
61304 pMem->flags = MEM_Null; /* Comment */
61305 pMem->type = SQLITE_NULL;
61309 p->nResColumn = 8 - 4*(p->explain-1);
61310 p->pResultSet = &p->aMem[1];
61311 p->rc = SQLITE_OK;
61312 rc = SQLITE_ROW;
61314 return rc;
61316 #endif /* SQLITE_OMIT_EXPLAIN */
61318 #ifdef SQLITE_DEBUG
61320 ** Print the SQL that was used to generate a VDBE program.
61322 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
61323 int nOp = p->nOp;
61324 VdbeOp *pOp;
61325 if( nOp<1 ) return;
61326 pOp = &p->aOp[0];
61327 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
61328 const char *z = pOp->p4.z;
61329 while( sqlite3Isspace(*z) ) z++;
61330 printf("SQL: [%s]\n", z);
61333 #endif
61335 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
61337 ** Print an IOTRACE message showing SQL content.
61339 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
61340 int nOp = p->nOp;
61341 VdbeOp *pOp;
61342 if( sqlite3IoTrace==0 ) return;
61343 if( nOp<1 ) return;
61344 pOp = &p->aOp[0];
61345 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
61346 int i, j;
61347 char z[1000];
61348 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
61349 for(i=0; sqlite3Isspace(z[i]); i++){}
61350 for(j=0; z[i]; i++){
61351 if( sqlite3Isspace(z[i]) ){
61352 if( z[i-1]!=' ' ){
61353 z[j++] = ' ';
61355 }else{
61356 z[j++] = z[i];
61359 z[j] = 0;
61360 sqlite3IoTrace("SQL %s\n", z);
61363 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
61366 ** Allocate space from a fixed size buffer and return a pointer to
61367 ** that space. If insufficient space is available, return NULL.
61369 ** The pBuf parameter is the initial value of a pointer which will
61370 ** receive the new memory. pBuf is normally NULL. If pBuf is not
61371 ** NULL, it means that memory space has already been allocated and that
61372 ** this routine should not allocate any new memory. When pBuf is not
61373 ** NULL simply return pBuf. Only allocate new memory space when pBuf
61374 ** is NULL.
61376 ** nByte is the number of bytes of space needed.
61378 ** *ppFrom points to available space and pEnd points to the end of the
61379 ** available space. When space is allocated, *ppFrom is advanced past
61380 ** the end of the allocated space.
61382 ** *pnByte is a counter of the number of bytes of space that have failed
61383 ** to allocate. If there is insufficient space in *ppFrom to satisfy the
61384 ** request, then increment *pnByte by the amount of the request.
61386 static void *allocSpace(
61387 void *pBuf, /* Where return pointer will be stored */
61388 int nByte, /* Number of bytes to allocate */
61389 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
61390 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
61391 int *pnByte /* If allocation cannot be made, increment *pnByte */
61393 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
61394 if( pBuf ) return pBuf;
61395 nByte = ROUND8(nByte);
61396 if( &(*ppFrom)[nByte] <= pEnd ){
61397 pBuf = (void*)*ppFrom;
61398 *ppFrom += nByte;
61399 }else{
61400 *pnByte += nByte;
61402 return pBuf;
61406 ** Rewind the VDBE back to the beginning in preparation for
61407 ** running it.
61409 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
61410 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
61411 int i;
61412 #endif
61413 assert( p!=0 );
61414 assert( p->magic==VDBE_MAGIC_INIT );
61416 /* There should be at least one opcode.
61418 assert( p->nOp>0 );
61420 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
61421 p->magic = VDBE_MAGIC_RUN;
61423 #ifdef SQLITE_DEBUG
61424 for(i=1; i<p->nMem; i++){
61425 assert( p->aMem[i].db==p->db );
61427 #endif
61428 p->pc = -1;
61429 p->rc = SQLITE_OK;
61430 p->errorAction = OE_Abort;
61431 p->magic = VDBE_MAGIC_RUN;
61432 p->nChange = 0;
61433 p->cacheCtr = 1;
61434 p->minWriteFileFormat = 255;
61435 p->iStatement = 0;
61436 p->nFkConstraint = 0;
61437 #ifdef VDBE_PROFILE
61438 for(i=0; i<p->nOp; i++){
61439 p->aOp[i].cnt = 0;
61440 p->aOp[i].cycles = 0;
61442 #endif
61446 ** Prepare a virtual machine for execution for the first time after
61447 ** creating the virtual machine. This involves things such
61448 ** as allocating stack space and initializing the program counter.
61449 ** After the VDBE has be prepped, it can be executed by one or more
61450 ** calls to sqlite3VdbeExec().
61452 ** This function may be called exact once on a each virtual machine.
61453 ** After this routine is called the VM has been "packaged" and is ready
61454 ** to run. After this routine is called, futher calls to
61455 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
61456 ** the Vdbe from the Parse object that helped generate it so that the
61457 ** the Vdbe becomes an independent entity and the Parse object can be
61458 ** destroyed.
61460 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
61461 ** to its initial state after it has been run.
61463 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
61464 Vdbe *p, /* The VDBE */
61465 Parse *pParse /* Parsing context */
61467 sqlite3 *db; /* The database connection */
61468 int nVar; /* Number of parameters */
61469 int nMem; /* Number of VM memory registers */
61470 int nCursor; /* Number of cursors required */
61471 int nArg; /* Number of arguments in subprograms */
61472 int nOnce; /* Number of OP_Once instructions */
61473 int n; /* Loop counter */
61474 u8 *zCsr; /* Memory available for allocation */
61475 u8 *zEnd; /* First byte past allocated memory */
61476 int nByte; /* How much extra memory is needed */
61478 assert( p!=0 );
61479 assert( p->nOp>0 );
61480 assert( pParse!=0 );
61481 assert( p->magic==VDBE_MAGIC_INIT );
61482 db = p->db;
61483 assert( db->mallocFailed==0 );
61484 nVar = pParse->nVar;
61485 nMem = pParse->nMem;
61486 nCursor = pParse->nTab;
61487 nArg = pParse->nMaxArg;
61488 nOnce = pParse->nOnce;
61489 if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
61491 /* For each cursor required, also allocate a memory cell. Memory
61492 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
61493 ** the vdbe program. Instead they are used to allocate space for
61494 ** VdbeCursor/BtCursor structures. The blob of memory associated with
61495 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
61496 ** stores the blob of memory associated with cursor 1, etc.
61498 ** See also: allocateCursor().
61500 nMem += nCursor;
61502 /* Allocate space for memory registers, SQL variables, VDBE cursors and
61503 ** an array to marshal SQL function arguments in.
61505 zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
61506 zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */
61508 resolveP2Values(p, &nArg);
61509 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
61510 if( pParse->explain && nMem<10 ){
61511 nMem = 10;
61513 memset(zCsr, 0, zEnd-zCsr);
61514 zCsr += (zCsr - (u8*)0)&7;
61515 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
61516 p->expired = 0;
61518 /* Memory for registers, parameters, cursor, etc, is allocated in two
61519 ** passes. On the first pass, we try to reuse unused space at the
61520 ** end of the opcode array. If we are unable to satisfy all memory
61521 ** requirements by reusing the opcode array tail, then the second
61522 ** pass will fill in the rest using a fresh allocation.
61524 ** This two-pass approach that reuses as much memory as possible from
61525 ** the leftover space at the end of the opcode array can significantly
61526 ** reduce the amount of memory held by a prepared statement.
61528 do {
61529 nByte = 0;
61530 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
61531 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
61532 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
61533 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
61534 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
61535 &zCsr, zEnd, &nByte);
61536 p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
61537 if( nByte ){
61538 p->pFree = sqlite3DbMallocZero(db, nByte);
61540 zCsr = p->pFree;
61541 zEnd = &zCsr[nByte];
61542 }while( nByte && !db->mallocFailed );
61544 p->nCursor = nCursor;
61545 p->nOnceFlag = nOnce;
61546 if( p->aVar ){
61547 p->nVar = (ynVar)nVar;
61548 for(n=0; n<nVar; n++){
61549 p->aVar[n].flags = MEM_Null;
61550 p->aVar[n].db = db;
61553 if( p->azVar ){
61554 p->nzVar = pParse->nzVar;
61555 memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
61556 memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
61558 if( p->aMem ){
61559 p->aMem--; /* aMem[] goes from 1..nMem */
61560 p->nMem = nMem; /* not from 0..nMem-1 */
61561 for(n=1; n<=nMem; n++){
61562 p->aMem[n].flags = MEM_Invalid;
61563 p->aMem[n].db = db;
61566 p->explain = pParse->explain;
61567 sqlite3VdbeRewind(p);
61571 ** Close a VDBE cursor and release all the resources that cursor
61572 ** happens to hold.
61574 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
61575 if( pCx==0 ){
61576 return;
61578 sqlite3VdbeSorterClose(p->db, pCx);
61579 if( pCx->pBt ){
61580 sqlite3BtreeClose(pCx->pBt);
61581 /* The pCx->pCursor will be close automatically, if it exists, by
61582 ** the call above. */
61583 }else if( pCx->pCursor ){
61584 sqlite3BtreeCloseCursor(pCx->pCursor);
61586 #ifndef SQLITE_OMIT_VIRTUALTABLE
61587 if( pCx->pVtabCursor ){
61588 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
61589 const sqlite3_module *pModule = pCx->pModule;
61590 p->inVtabMethod = 1;
61591 pModule->xClose(pVtabCursor);
61592 p->inVtabMethod = 0;
61594 #endif
61598 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
61599 ** is used, for example, when a trigger sub-program is halted to restore
61600 ** control to the main program.
61602 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
61603 Vdbe *v = pFrame->v;
61604 v->aOnceFlag = pFrame->aOnceFlag;
61605 v->nOnceFlag = pFrame->nOnceFlag;
61606 v->aOp = pFrame->aOp;
61607 v->nOp = pFrame->nOp;
61608 v->aMem = pFrame->aMem;
61609 v->nMem = pFrame->nMem;
61610 v->apCsr = pFrame->apCsr;
61611 v->nCursor = pFrame->nCursor;
61612 v->db->lastRowid = pFrame->lastRowid;
61613 v->nChange = pFrame->nChange;
61614 return pFrame->pc;
61618 ** Close all cursors.
61620 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
61621 ** cell array. This is necessary as the memory cell array may contain
61622 ** pointers to VdbeFrame objects, which may in turn contain pointers to
61623 ** open cursors.
61625 static void closeAllCursors(Vdbe *p){
61626 if( p->pFrame ){
61627 VdbeFrame *pFrame;
61628 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
61629 sqlite3VdbeFrameRestore(pFrame);
61631 p->pFrame = 0;
61632 p->nFrame = 0;
61634 if( p->apCsr ){
61635 int i;
61636 for(i=0; i<p->nCursor; i++){
61637 VdbeCursor *pC = p->apCsr[i];
61638 if( pC ){
61639 sqlite3VdbeFreeCursor(p, pC);
61640 p->apCsr[i] = 0;
61644 if( p->aMem ){
61645 releaseMemArray(&p->aMem[1], p->nMem);
61647 while( p->pDelFrame ){
61648 VdbeFrame *pDel = p->pDelFrame;
61649 p->pDelFrame = pDel->pParent;
61650 sqlite3VdbeFrameDelete(pDel);
61653 /* Delete any auxdata allocations made by the VM */
61654 sqlite3VdbeDeleteAuxData(p, -1, 0);
61655 assert( p->pAuxData==0 );
61659 ** Clean up the VM after execution.
61661 ** This routine will automatically close any cursors, lists, and/or
61662 ** sorters that were left open. It also deletes the values of
61663 ** variables in the aVar[] array.
61665 static void Cleanup(Vdbe *p){
61666 sqlite3 *db = p->db;
61668 #ifdef SQLITE_DEBUG
61669 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
61670 ** Vdbe.aMem[] arrays have already been cleaned up. */
61671 int i;
61672 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
61673 if( p->aMem ){
61674 for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
61676 #endif
61678 sqlite3DbFree(db, p->zErrMsg);
61679 p->zErrMsg = 0;
61680 p->pResultSet = 0;
61684 ** Set the number of result columns that will be returned by this SQL
61685 ** statement. This is now set at compile time, rather than during
61686 ** execution of the vdbe program so that sqlite3_column_count() can
61687 ** be called on an SQL statement before sqlite3_step().
61689 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
61690 Mem *pColName;
61691 int n;
61692 sqlite3 *db = p->db;
61694 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61695 sqlite3DbFree(db, p->aColName);
61696 n = nResColumn*COLNAME_N;
61697 p->nResColumn = (u16)nResColumn;
61698 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
61699 if( p->aColName==0 ) return;
61700 while( n-- > 0 ){
61701 pColName->flags = MEM_Null;
61702 pColName->db = p->db;
61703 pColName++;
61708 ** Set the name of the idx'th column to be returned by the SQL statement.
61709 ** zName must be a pointer to a nul terminated string.
61711 ** This call must be made after a call to sqlite3VdbeSetNumCols().
61713 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
61714 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
61715 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
61717 SQLITE_PRIVATE int sqlite3VdbeSetColName(
61718 Vdbe *p, /* Vdbe being configured */
61719 int idx, /* Index of column zName applies to */
61720 int var, /* One of the COLNAME_* constants */
61721 const char *zName, /* Pointer to buffer containing name */
61722 void (*xDel)(void*) /* Memory management strategy for zName */
61724 int rc;
61725 Mem *pColName;
61726 assert( idx<p->nResColumn );
61727 assert( var<COLNAME_N );
61728 if( p->db->mallocFailed ){
61729 assert( !zName || xDel!=SQLITE_DYNAMIC );
61730 return SQLITE_NOMEM;
61732 assert( p->aColName!=0 );
61733 pColName = &(p->aColName[idx+var*p->nResColumn]);
61734 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
61735 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
61736 return rc;
61740 ** A read or write transaction may or may not be active on database handle
61741 ** db. If a transaction is active, commit it. If there is a
61742 ** write-transaction spanning more than one database file, this routine
61743 ** takes care of the master journal trickery.
61745 static int vdbeCommit(sqlite3 *db, Vdbe *p){
61746 int i;
61747 int nTrans = 0; /* Number of databases with an active write-transaction */
61748 int rc = SQLITE_OK;
61749 int needXcommit = 0;
61751 #ifdef SQLITE_OMIT_VIRTUALTABLE
61752 /* With this option, sqlite3VtabSync() is defined to be simply
61753 ** SQLITE_OK so p is not used.
61755 UNUSED_PARAMETER(p);
61756 #endif
61758 /* Before doing anything else, call the xSync() callback for any
61759 ** virtual module tables written in this transaction. This has to
61760 ** be done before determining whether a master journal file is
61761 ** required, as an xSync() callback may add an attached database
61762 ** to the transaction.
61764 rc = sqlite3VtabSync(db, p);
61766 /* This loop determines (a) if the commit hook should be invoked and
61767 ** (b) how many database files have open write transactions, not
61768 ** including the temp database. (b) is important because if more than
61769 ** one database file has an open write transaction, a master journal
61770 ** file is required for an atomic commit.
61772 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61773 Btree *pBt = db->aDb[i].pBt;
61774 if( sqlite3BtreeIsInTrans(pBt) ){
61775 needXcommit = 1;
61776 if( i!=1 ) nTrans++;
61777 sqlite3BtreeEnter(pBt);
61778 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
61779 sqlite3BtreeLeave(pBt);
61782 if( rc!=SQLITE_OK ){
61783 return rc;
61786 /* If there are any write-transactions at all, invoke the commit hook */
61787 if( needXcommit && db->xCommitCallback ){
61788 rc = db->xCommitCallback(db->pCommitArg);
61789 if( rc ){
61790 return SQLITE_CONSTRAINT_COMMITHOOK;
61794 /* The simple case - no more than one database file (not counting the
61795 ** TEMP database) has a transaction active. There is no need for the
61796 ** master-journal.
61798 ** If the return value of sqlite3BtreeGetFilename() is a zero length
61799 ** string, it means the main database is :memory: or a temp file. In
61800 ** that case we do not support atomic multi-file commits, so use the
61801 ** simple case then too.
61803 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
61804 || nTrans<=1
61806 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61807 Btree *pBt = db->aDb[i].pBt;
61808 if( pBt ){
61809 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
61813 /* Do the commit only if all databases successfully complete phase 1.
61814 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
61815 ** IO error while deleting or truncating a journal file. It is unlikely,
61816 ** but could happen. In this case abandon processing and return the error.
61818 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61819 Btree *pBt = db->aDb[i].pBt;
61820 if( pBt ){
61821 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
61824 if( rc==SQLITE_OK ){
61825 sqlite3VtabCommit(db);
61829 /* The complex case - There is a multi-file write-transaction active.
61830 ** This requires a master journal file to ensure the transaction is
61831 ** committed atomicly.
61833 #ifndef SQLITE_OMIT_DISKIO
61834 else{
61835 sqlite3_vfs *pVfs = db->pVfs;
61836 int needSync = 0;
61837 char *zMaster = 0; /* File-name for the master journal */
61838 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
61839 sqlite3_file *pMaster = 0;
61840 i64 offset = 0;
61841 int res;
61842 int retryCount = 0;
61843 int nMainFile;
61845 /* Select a master journal file name */
61846 nMainFile = sqlite3Strlen30(zMainFile);
61847 zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
61848 if( zMaster==0 ) return SQLITE_NOMEM;
61849 do {
61850 u32 iRandom;
61851 if( retryCount ){
61852 if( retryCount>100 ){
61853 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
61854 sqlite3OsDelete(pVfs, zMaster, 0);
61855 break;
61856 }else if( retryCount==1 ){
61857 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
61860 retryCount++;
61861 sqlite3_randomness(sizeof(iRandom), &iRandom);
61862 sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
61863 (iRandom>>8)&0xffffff, iRandom&0xff);
61864 /* The antipenultimate character of the master journal name must
61865 ** be "9" to avoid name collisions when using 8+3 filenames. */
61866 assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
61867 sqlite3FileSuffix3(zMainFile, zMaster);
61868 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
61869 }while( rc==SQLITE_OK && res );
61870 if( rc==SQLITE_OK ){
61871 /* Open the master journal. */
61872 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
61873 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
61874 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
61877 if( rc!=SQLITE_OK ){
61878 sqlite3DbFree(db, zMaster);
61879 return rc;
61882 /* Write the name of each database file in the transaction into the new
61883 ** master journal file. If an error occurs at this point close
61884 ** and delete the master journal file. All the individual journal files
61885 ** still have 'null' as the master journal pointer, so they will roll
61886 ** back independently if a failure occurs.
61888 for(i=0; i<db->nDb; i++){
61889 Btree *pBt = db->aDb[i].pBt;
61890 if( sqlite3BtreeIsInTrans(pBt) ){
61891 char const *zFile = sqlite3BtreeGetJournalname(pBt);
61892 if( zFile==0 ){
61893 continue; /* Ignore TEMP and :memory: databases */
61895 assert( zFile[0]!=0 );
61896 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
61897 needSync = 1;
61899 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
61900 offset += sqlite3Strlen30(zFile)+1;
61901 if( rc!=SQLITE_OK ){
61902 sqlite3OsCloseFree(pMaster);
61903 sqlite3OsDelete(pVfs, zMaster, 0);
61904 sqlite3DbFree(db, zMaster);
61905 return rc;
61910 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
61911 ** flag is set this is not required.
61913 if( needSync
61914 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
61915 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
61917 sqlite3OsCloseFree(pMaster);
61918 sqlite3OsDelete(pVfs, zMaster, 0);
61919 sqlite3DbFree(db, zMaster);
61920 return rc;
61923 /* Sync all the db files involved in the transaction. The same call
61924 ** sets the master journal pointer in each individual journal. If
61925 ** an error occurs here, do not delete the master journal file.
61927 ** If the error occurs during the first call to
61928 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
61929 ** master journal file will be orphaned. But we cannot delete it,
61930 ** in case the master journal file name was written into the journal
61931 ** file before the failure occurred.
61933 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61934 Btree *pBt = db->aDb[i].pBt;
61935 if( pBt ){
61936 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
61939 sqlite3OsCloseFree(pMaster);
61940 assert( rc!=SQLITE_BUSY );
61941 if( rc!=SQLITE_OK ){
61942 sqlite3DbFree(db, zMaster);
61943 return rc;
61946 /* Delete the master journal file. This commits the transaction. After
61947 ** doing this the directory is synced again before any individual
61948 ** transaction files are deleted.
61950 rc = sqlite3OsDelete(pVfs, zMaster, 1);
61951 sqlite3DbFree(db, zMaster);
61952 zMaster = 0;
61953 if( rc ){
61954 return rc;
61957 /* All files and directories have already been synced, so the following
61958 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
61959 ** deleting or truncating journals. If something goes wrong while
61960 ** this is happening we don't really care. The integrity of the
61961 ** transaction is already guaranteed, but some stray 'cold' journals
61962 ** may be lying around. Returning an error code won't help matters.
61964 disable_simulated_io_errors();
61965 sqlite3BeginBenignMalloc();
61966 for(i=0; i<db->nDb; i++){
61967 Btree *pBt = db->aDb[i].pBt;
61968 if( pBt ){
61969 sqlite3BtreeCommitPhaseTwo(pBt, 1);
61972 sqlite3EndBenignMalloc();
61973 enable_simulated_io_errors();
61975 sqlite3VtabCommit(db);
61977 #endif
61979 return rc;
61983 ** This routine checks that the sqlite3.nVdbeActive count variable
61984 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
61985 ** currently active. An assertion fails if the two counts do not match.
61986 ** This is an internal self-check only - it is not an essential processing
61987 ** step.
61989 ** This is a no-op if NDEBUG is defined.
61991 #ifndef NDEBUG
61992 static void checkActiveVdbeCnt(sqlite3 *db){
61993 Vdbe *p;
61994 int cnt = 0;
61995 int nWrite = 0;
61996 int nRead = 0;
61997 p = db->pVdbe;
61998 while( p ){
61999 if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
62000 cnt++;
62001 if( p->readOnly==0 ) nWrite++;
62002 if( p->bIsReader ) nRead++;
62004 p = p->pNext;
62006 assert( cnt==db->nVdbeActive );
62007 assert( nWrite==db->nVdbeWrite );
62008 assert( nRead==db->nVdbeRead );
62010 #else
62011 #define checkActiveVdbeCnt(x)
62012 #endif
62015 ** If the Vdbe passed as the first argument opened a statement-transaction,
62016 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
62017 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
62018 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
62019 ** statement transaction is committed.
62021 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
62022 ** Otherwise SQLITE_OK.
62024 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
62025 sqlite3 *const db = p->db;
62026 int rc = SQLITE_OK;
62028 /* If p->iStatement is greater than zero, then this Vdbe opened a
62029 ** statement transaction that should be closed here. The only exception
62030 ** is that an IO error may have occurred, causing an emergency rollback.
62031 ** In this case (db->nStatement==0), and there is nothing to do.
62033 if( db->nStatement && p->iStatement ){
62034 int i;
62035 const int iSavepoint = p->iStatement-1;
62037 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
62038 assert( db->nStatement>0 );
62039 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
62041 for(i=0; i<db->nDb; i++){
62042 int rc2 = SQLITE_OK;
62043 Btree *pBt = db->aDb[i].pBt;
62044 if( pBt ){
62045 if( eOp==SAVEPOINT_ROLLBACK ){
62046 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
62048 if( rc2==SQLITE_OK ){
62049 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
62051 if( rc==SQLITE_OK ){
62052 rc = rc2;
62056 db->nStatement--;
62057 p->iStatement = 0;
62059 if( rc==SQLITE_OK ){
62060 if( eOp==SAVEPOINT_ROLLBACK ){
62061 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
62063 if( rc==SQLITE_OK ){
62064 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
62068 /* If the statement transaction is being rolled back, also restore the
62069 ** database handles deferred constraint counter to the value it had when
62070 ** the statement transaction was opened. */
62071 if( eOp==SAVEPOINT_ROLLBACK ){
62072 db->nDeferredCons = p->nStmtDefCons;
62073 db->nDeferredImmCons = p->nStmtDefImmCons;
62076 return rc;
62080 ** This function is called when a transaction opened by the database
62081 ** handle associated with the VM passed as an argument is about to be
62082 ** committed. If there are outstanding deferred foreign key constraint
62083 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
62085 ** If there are outstanding FK violations and this function returns
62086 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
62087 ** and write an error message to it. Then return SQLITE_ERROR.
62089 #ifndef SQLITE_OMIT_FOREIGN_KEY
62090 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
62091 sqlite3 *db = p->db;
62092 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
62093 || (!deferred && p->nFkConstraint>0)
62095 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
62096 p->errorAction = OE_Abort;
62097 sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
62098 return SQLITE_ERROR;
62100 return SQLITE_OK;
62102 #endif
62105 ** This routine is called the when a VDBE tries to halt. If the VDBE
62106 ** has made changes and is in autocommit mode, then commit those
62107 ** changes. If a rollback is needed, then do the rollback.
62109 ** This routine is the only way to move the state of a VM from
62110 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
62111 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
62113 ** Return an error code. If the commit could not complete because of
62114 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
62115 ** means the close did not happen and needs to be repeated.
62117 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
62118 int rc; /* Used to store transient return codes */
62119 sqlite3 *db = p->db;
62121 /* This function contains the logic that determines if a statement or
62122 ** transaction will be committed or rolled back as a result of the
62123 ** execution of this virtual machine.
62125 ** If any of the following errors occur:
62127 ** SQLITE_NOMEM
62128 ** SQLITE_IOERR
62129 ** SQLITE_FULL
62130 ** SQLITE_INTERRUPT
62132 ** Then the internal cache might have been left in an inconsistent
62133 ** state. We need to rollback the statement transaction, if there is
62134 ** one, or the complete transaction if there is no statement transaction.
62137 if( p->db->mallocFailed ){
62138 p->rc = SQLITE_NOMEM;
62140 if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
62141 closeAllCursors(p);
62142 if( p->magic!=VDBE_MAGIC_RUN ){
62143 return SQLITE_OK;
62145 checkActiveVdbeCnt(db);
62147 /* No commit or rollback needed if the program never started or if the
62148 ** SQL statement does not read or write a database file. */
62149 if( p->pc>=0 && p->bIsReader ){
62150 int mrc; /* Primary error code from p->rc */
62151 int eStatementOp = 0;
62152 int isSpecialError; /* Set to true if a 'special' error */
62154 /* Lock all btrees used by the statement */
62155 sqlite3VdbeEnter(p);
62157 /* Check for one of the special errors */
62158 mrc = p->rc & 0xff;
62159 assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
62160 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
62161 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
62162 if( isSpecialError ){
62163 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
62164 ** no rollback is necessary. Otherwise, at least a savepoint
62165 ** transaction must be rolled back to restore the database to a
62166 ** consistent state.
62168 ** Even if the statement is read-only, it is important to perform
62169 ** a statement or transaction rollback operation. If the error
62170 ** occurred while writing to the journal, sub-journal or database
62171 ** file as part of an effort to free up cache space (see function
62172 ** pagerStress() in pager.c), the rollback is required to restore
62173 ** the pager to a consistent state.
62175 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
62176 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
62177 eStatementOp = SAVEPOINT_ROLLBACK;
62178 }else{
62179 /* We are forced to roll back the active transaction. Before doing
62180 ** so, abort any other statements this handle currently has active.
62182 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62183 sqlite3CloseSavepoints(db);
62184 db->autoCommit = 1;
62189 /* Check for immediate foreign key violations. */
62190 if( p->rc==SQLITE_OK ){
62191 sqlite3VdbeCheckFk(p, 0);
62194 /* If the auto-commit flag is set and this is the only active writer
62195 ** VM, then we do either a commit or rollback of the current transaction.
62197 ** Note: This block also runs if one of the special errors handled
62198 ** above has occurred.
62200 if( !sqlite3VtabInSync(db)
62201 && db->autoCommit
62202 && db->nVdbeWrite==(p->readOnly==0)
62204 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
62205 rc = sqlite3VdbeCheckFk(p, 1);
62206 if( rc!=SQLITE_OK ){
62207 if( NEVER(p->readOnly) ){
62208 sqlite3VdbeLeave(p);
62209 return SQLITE_ERROR;
62211 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
62212 }else{
62213 /* The auto-commit flag is true, the vdbe program was successful
62214 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
62215 ** key constraints to hold up the transaction. This means a commit
62216 ** is required. */
62217 rc = vdbeCommit(db, p);
62219 if( rc==SQLITE_BUSY && p->readOnly ){
62220 sqlite3VdbeLeave(p);
62221 return SQLITE_BUSY;
62222 }else if( rc!=SQLITE_OK ){
62223 p->rc = rc;
62224 sqlite3RollbackAll(db, SQLITE_OK);
62225 }else{
62226 db->nDeferredCons = 0;
62227 db->nDeferredImmCons = 0;
62228 db->flags &= ~SQLITE_DeferFKs;
62229 sqlite3CommitInternalChanges(db);
62231 }else{
62232 sqlite3RollbackAll(db, SQLITE_OK);
62234 db->nStatement = 0;
62235 }else if( eStatementOp==0 ){
62236 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
62237 eStatementOp = SAVEPOINT_RELEASE;
62238 }else if( p->errorAction==OE_Abort ){
62239 eStatementOp = SAVEPOINT_ROLLBACK;
62240 }else{
62241 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62242 sqlite3CloseSavepoints(db);
62243 db->autoCommit = 1;
62247 /* If eStatementOp is non-zero, then a statement transaction needs to
62248 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
62249 ** do so. If this operation returns an error, and the current statement
62250 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
62251 ** current statement error code.
62253 if( eStatementOp ){
62254 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
62255 if( rc ){
62256 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
62257 p->rc = rc;
62258 sqlite3DbFree(db, p->zErrMsg);
62259 p->zErrMsg = 0;
62261 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62262 sqlite3CloseSavepoints(db);
62263 db->autoCommit = 1;
62267 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
62268 ** has been rolled back, update the database connection change-counter.
62270 if( p->changeCntOn ){
62271 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
62272 sqlite3VdbeSetChanges(db, p->nChange);
62273 }else{
62274 sqlite3VdbeSetChanges(db, 0);
62276 p->nChange = 0;
62279 /* Release the locks */
62280 sqlite3VdbeLeave(p);
62283 /* We have successfully halted and closed the VM. Record this fact. */
62284 if( p->pc>=0 ){
62285 db->nVdbeActive--;
62286 if( !p->readOnly ) db->nVdbeWrite--;
62287 if( p->bIsReader ) db->nVdbeRead--;
62288 assert( db->nVdbeActive>=db->nVdbeRead );
62289 assert( db->nVdbeRead>=db->nVdbeWrite );
62290 assert( db->nVdbeWrite>=0 );
62292 p->magic = VDBE_MAGIC_HALT;
62293 checkActiveVdbeCnt(db);
62294 if( p->db->mallocFailed ){
62295 p->rc = SQLITE_NOMEM;
62298 /* If the auto-commit flag is set to true, then any locks that were held
62299 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
62300 ** to invoke any required unlock-notify callbacks.
62302 if( db->autoCommit ){
62303 sqlite3ConnectionUnlocked(db);
62306 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
62307 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
62312 ** Each VDBE holds the result of the most recent sqlite3_step() call
62313 ** in p->rc. This routine sets that result back to SQLITE_OK.
62315 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
62316 p->rc = SQLITE_OK;
62320 ** Copy the error code and error message belonging to the VDBE passed
62321 ** as the first argument to its database handle (so that they will be
62322 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
62324 ** This function does not clear the VDBE error code or message, just
62325 ** copies them to the database handle.
62327 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
62328 sqlite3 *db = p->db;
62329 int rc = p->rc;
62330 if( p->zErrMsg ){
62331 u8 mallocFailed = db->mallocFailed;
62332 sqlite3BeginBenignMalloc();
62333 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
62334 sqlite3EndBenignMalloc();
62335 db->mallocFailed = mallocFailed;
62336 db->errCode = rc;
62337 }else{
62338 sqlite3Error(db, rc, 0);
62340 return rc;
62343 #ifdef SQLITE_ENABLE_SQLLOG
62345 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
62346 ** invoke it.
62348 static void vdbeInvokeSqllog(Vdbe *v){
62349 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
62350 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
62351 assert( v->db->init.busy==0 );
62352 if( zExpanded ){
62353 sqlite3GlobalConfig.xSqllog(
62354 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
62356 sqlite3DbFree(v->db, zExpanded);
62360 #else
62361 # define vdbeInvokeSqllog(x)
62362 #endif
62365 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
62366 ** Write any error messages into *pzErrMsg. Return the result code.
62368 ** After this routine is run, the VDBE should be ready to be executed
62369 ** again.
62371 ** To look at it another way, this routine resets the state of the
62372 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
62373 ** VDBE_MAGIC_INIT.
62375 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
62376 sqlite3 *db;
62377 db = p->db;
62379 /* If the VM did not run to completion or if it encountered an
62380 ** error, then it might not have been halted properly. So halt
62381 ** it now.
62383 sqlite3VdbeHalt(p);
62385 /* If the VDBE has be run even partially, then transfer the error code
62386 ** and error message from the VDBE into the main database structure. But
62387 ** if the VDBE has just been set to run but has not actually executed any
62388 ** instructions yet, leave the main database error information unchanged.
62390 if( p->pc>=0 ){
62391 vdbeInvokeSqllog(p);
62392 sqlite3VdbeTransferError(p);
62393 sqlite3DbFree(db, p->zErrMsg);
62394 p->zErrMsg = 0;
62395 if( p->runOnlyOnce ) p->expired = 1;
62396 }else if( p->rc && p->expired ){
62397 /* The expired flag was set on the VDBE before the first call
62398 ** to sqlite3_step(). For consistency (since sqlite3_step() was
62399 ** called), set the database error in this case as well.
62401 sqlite3Error(db, p->rc, 0);
62402 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
62403 sqlite3DbFree(db, p->zErrMsg);
62404 p->zErrMsg = 0;
62407 /* Reclaim all memory used by the VDBE
62409 Cleanup(p);
62411 /* Save profiling information from this VDBE run.
62413 #ifdef VDBE_PROFILE
62415 FILE *out = fopen("vdbe_profile.out", "a");
62416 if( out ){
62417 int i;
62418 fprintf(out, "---- ");
62419 for(i=0; i<p->nOp; i++){
62420 fprintf(out, "%02x", p->aOp[i].opcode);
62422 fprintf(out, "\n");
62423 for(i=0; i<p->nOp; i++){
62424 fprintf(out, "%6d %10lld %8lld ",
62425 p->aOp[i].cnt,
62426 p->aOp[i].cycles,
62427 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
62429 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
62431 fclose(out);
62434 #endif
62435 p->magic = VDBE_MAGIC_INIT;
62436 return p->rc & db->errMask;
62440 ** Clean up and delete a VDBE after execution. Return an integer which is
62441 ** the result code. Write any error message text into *pzErrMsg.
62443 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
62444 int rc = SQLITE_OK;
62445 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
62446 rc = sqlite3VdbeReset(p);
62447 assert( (rc & p->db->errMask)==rc );
62449 sqlite3VdbeDelete(p);
62450 return rc;
62454 ** If parameter iOp is less than zero, then invoke the destructor for
62455 ** all auxiliary data pointers currently cached by the VM passed as
62456 ** the first argument.
62458 ** Or, if iOp is greater than or equal to zero, then the destructor is
62459 ** only invoked for those auxiliary data pointers created by the user
62460 ** function invoked by the OP_Function opcode at instruction iOp of
62461 ** VM pVdbe, and only then if:
62463 ** * the associated function parameter is the 32nd or later (counting
62464 ** from left to right), or
62466 ** * the corresponding bit in argument mask is clear (where the first
62467 ** function parameter corrsponds to bit 0 etc.).
62469 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
62470 AuxData **pp = &pVdbe->pAuxData;
62471 while( *pp ){
62472 AuxData *pAux = *pp;
62473 if( (iOp<0)
62474 || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & ((u32)1<<pAux->iArg))))
62476 if( pAux->xDelete ){
62477 pAux->xDelete(pAux->pAux);
62479 *pp = pAux->pNext;
62480 sqlite3DbFree(pVdbe->db, pAux);
62481 }else{
62482 pp= &pAux->pNext;
62488 ** Free all memory associated with the Vdbe passed as the second argument,
62489 ** except for object itself, which is preserved.
62491 ** The difference between this function and sqlite3VdbeDelete() is that
62492 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
62493 ** the database connection and frees the object itself.
62495 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
62496 SubProgram *pSub, *pNext;
62497 int i;
62498 assert( p->db==0 || p->db==db );
62499 releaseMemArray(p->aVar, p->nVar);
62500 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
62501 for(pSub=p->pProgram; pSub; pSub=pNext){
62502 pNext = pSub->pNext;
62503 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
62504 sqlite3DbFree(db, pSub);
62506 for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
62507 vdbeFreeOpArray(db, p->aOp, p->nOp);
62508 sqlite3DbFree(db, p->aLabel);
62509 sqlite3DbFree(db, p->aColName);
62510 sqlite3DbFree(db, p->zSql);
62511 sqlite3DbFree(db, p->pFree);
62512 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
62513 sqlite3DbFree(db, p->zExplain);
62514 sqlite3DbFree(db, p->pExplain);
62515 #endif
62519 ** Delete an entire VDBE.
62521 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
62522 sqlite3 *db;
62524 if( NEVER(p==0) ) return;
62525 db = p->db;
62526 assert( sqlite3_mutex_held(db->mutex) );
62527 sqlite3VdbeClearObject(db, p);
62528 if( p->pPrev ){
62529 p->pPrev->pNext = p->pNext;
62530 }else{
62531 assert( db->pVdbe==p );
62532 db->pVdbe = p->pNext;
62534 if( p->pNext ){
62535 p->pNext->pPrev = p->pPrev;
62537 p->magic = VDBE_MAGIC_DEAD;
62538 p->db = 0;
62539 sqlite3DbFree(db, p);
62543 ** Make sure the cursor p is ready to read or write the row to which it
62544 ** was last positioned. Return an error code if an OOM fault or I/O error
62545 ** prevents us from positioning the cursor to its correct position.
62547 ** If a MoveTo operation is pending on the given cursor, then do that
62548 ** MoveTo now. If no move is pending, check to see if the row has been
62549 ** deleted out from under the cursor and if it has, mark the row as
62550 ** a NULL row.
62552 ** If the cursor is already pointing to the correct row and that row has
62553 ** not been deleted out from under the cursor, then this routine is a no-op.
62555 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
62556 if( p->deferredMoveto ){
62557 int res, rc;
62558 #ifdef SQLITE_TEST
62559 extern int sqlite3_search_count;
62560 #endif
62561 assert( p->isTable );
62562 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
62563 if( rc ) return rc;
62564 p->lastRowid = p->movetoTarget;
62565 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
62566 p->rowidIsValid = 1;
62567 #ifdef SQLITE_TEST
62568 sqlite3_search_count++;
62569 #endif
62570 p->deferredMoveto = 0;
62571 p->cacheStatus = CACHE_STALE;
62572 }else if( ALWAYS(p->pCursor) ){
62573 int hasMoved;
62574 int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
62575 if( rc ) return rc;
62576 if( hasMoved ){
62577 p->cacheStatus = CACHE_STALE;
62578 p->nullRow = 1;
62581 return SQLITE_OK;
62585 ** The following functions:
62587 ** sqlite3VdbeSerialType()
62588 ** sqlite3VdbeSerialTypeLen()
62589 ** sqlite3VdbeSerialLen()
62590 ** sqlite3VdbeSerialPut()
62591 ** sqlite3VdbeSerialGet()
62593 ** encapsulate the code that serializes values for storage in SQLite
62594 ** data and index records. Each serialized value consists of a
62595 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
62596 ** integer, stored as a varint.
62598 ** In an SQLite index record, the serial type is stored directly before
62599 ** the blob of data that it corresponds to. In a table record, all serial
62600 ** types are stored at the start of the record, and the blobs of data at
62601 ** the end. Hence these functions allow the caller to handle the
62602 ** serial-type and data blob separately.
62604 ** The following table describes the various storage classes for data:
62606 ** serial type bytes of data type
62607 ** -------------- --------------- ---------------
62608 ** 0 0 NULL
62609 ** 1 1 signed integer
62610 ** 2 2 signed integer
62611 ** 3 3 signed integer
62612 ** 4 4 signed integer
62613 ** 5 6 signed integer
62614 ** 6 8 signed integer
62615 ** 7 8 IEEE float
62616 ** 8 0 Integer constant 0
62617 ** 9 0 Integer constant 1
62618 ** 10,11 reserved for expansion
62619 ** N>=12 and even (N-12)/2 BLOB
62620 ** N>=13 and odd (N-13)/2 text
62622 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
62623 ** of SQLite will not understand those serial types.
62627 ** Return the serial-type for the value stored in pMem.
62629 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
62630 int flags = pMem->flags;
62631 int n;
62633 if( flags&MEM_Null ){
62634 return 0;
62636 if( flags&MEM_Int ){
62637 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
62638 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
62639 i64 i = pMem->u.i;
62640 u64 u;
62641 if( i<0 ){
62642 if( i<(-MAX_6BYTE) ) return 6;
62643 /* Previous test prevents: u = -(-9223372036854775808) */
62644 u = -i;
62645 }else{
62646 u = i;
62648 if( u<=127 ){
62649 return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
62651 if( u<=32767 ) return 2;
62652 if( u<=8388607 ) return 3;
62653 if( u<=2147483647 ) return 4;
62654 if( u<=MAX_6BYTE ) return 5;
62655 return 6;
62657 if( flags&MEM_Real ){
62658 return 7;
62660 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
62661 n = pMem->n;
62662 if( flags & MEM_Zero ){
62663 n += pMem->u.nZero;
62665 assert( n>=0 );
62666 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
62670 ** Return the length of the data corresponding to the supplied serial-type.
62672 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
62673 if( serial_type>=12 ){
62674 return (serial_type-12)/2;
62675 }else{
62676 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
62677 return aSize[serial_type];
62682 ** If we are on an architecture with mixed-endian floating
62683 ** points (ex: ARM7) then swap the lower 4 bytes with the
62684 ** upper 4 bytes. Return the result.
62686 ** For most architectures, this is a no-op.
62688 ** (later): It is reported to me that the mixed-endian problem
62689 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
62690 ** that early versions of GCC stored the two words of a 64-bit
62691 ** float in the wrong order. And that error has been propagated
62692 ** ever since. The blame is not necessarily with GCC, though.
62693 ** GCC might have just copying the problem from a prior compiler.
62694 ** I am also told that newer versions of GCC that follow a different
62695 ** ABI get the byte order right.
62697 ** Developers using SQLite on an ARM7 should compile and run their
62698 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
62699 ** enabled, some asserts below will ensure that the byte order of
62700 ** floating point values is correct.
62702 ** (2007-08-30) Frank van Vugt has studied this problem closely
62703 ** and has send his findings to the SQLite developers. Frank
62704 ** writes that some Linux kernels offer floating point hardware
62705 ** emulation that uses only 32-bit mantissas instead of a full
62706 ** 48-bits as required by the IEEE standard. (This is the
62707 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
62708 ** byte swapping becomes very complicated. To avoid problems,
62709 ** the necessary byte swapping is carried out using a 64-bit integer
62710 ** rather than a 64-bit float. Frank assures us that the code here
62711 ** works for him. We, the developers, have no way to independently
62712 ** verify this, but Frank seems to know what he is talking about
62713 ** so we trust him.
62715 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
62716 static u64 floatSwap(u64 in){
62717 union {
62718 u64 r;
62719 u32 i[2];
62720 } u;
62721 u32 t;
62723 u.r = in;
62724 t = u.i[0];
62725 u.i[0] = u.i[1];
62726 u.i[1] = t;
62727 return u.r;
62729 # define swapMixedEndianFloat(X) X = floatSwap(X)
62730 #else
62731 # define swapMixedEndianFloat(X)
62732 #endif
62735 ** Write the serialized data blob for the value stored in pMem into
62736 ** buf. It is assumed that the caller has allocated sufficient space.
62737 ** Return the number of bytes written.
62739 ** nBuf is the amount of space left in buf[]. nBuf must always be
62740 ** large enough to hold the entire field. Except, if the field is
62741 ** a blob with a zero-filled tail, then buf[] might be just the right
62742 ** size to hold everything except for the zero-filled tail. If buf[]
62743 ** is only big enough to hold the non-zero prefix, then only write that
62744 ** prefix into buf[]. But if buf[] is large enough to hold both the
62745 ** prefix and the tail then write the prefix and set the tail to all
62746 ** zeros.
62748 ** Return the number of bytes actually written into buf[]. The number
62749 ** of bytes in the zero-filled tail is included in the return value only
62750 ** if those bytes were zeroed in buf[].
62752 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
62753 u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
62754 u32 len;
62756 /* Integer and Real */
62757 if( serial_type<=7 && serial_type>0 ){
62758 u64 v;
62759 u32 i;
62760 if( serial_type==7 ){
62761 assert( sizeof(v)==sizeof(pMem->r) );
62762 memcpy(&v, &pMem->r, sizeof(v));
62763 swapMixedEndianFloat(v);
62764 }else{
62765 v = pMem->u.i;
62767 len = i = sqlite3VdbeSerialTypeLen(serial_type);
62768 assert( len<=(u32)nBuf );
62769 while( i-- ){
62770 buf[i] = (u8)(v&0xFF);
62771 v >>= 8;
62773 return len;
62776 /* String or blob */
62777 if( serial_type>=12 ){
62778 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
62779 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
62780 assert( pMem->n<=nBuf );
62781 len = pMem->n;
62782 memcpy(buf, pMem->z, len);
62783 if( pMem->flags & MEM_Zero ){
62784 len += pMem->u.nZero;
62785 assert( nBuf>=0 );
62786 if( len > (u32)nBuf ){
62787 len = (u32)nBuf;
62789 memset(&buf[pMem->n], 0, len-pMem->n);
62791 return len;
62794 /* NULL or constants 0 or 1 */
62795 return 0;
62799 ** Deserialize the data blob pointed to by buf as serial type serial_type
62800 ** and store the result in pMem. Return the number of bytes read.
62802 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
62803 const unsigned char *buf, /* Buffer to deserialize from */
62804 u32 serial_type, /* Serial type to deserialize */
62805 Mem *pMem /* Memory cell to write value into */
62807 switch( serial_type ){
62808 case 10: /* Reserved for future use */
62809 case 11: /* Reserved for future use */
62810 case 0: { /* NULL */
62811 pMem->flags = MEM_Null;
62812 break;
62814 case 1: { /* 1-byte signed integer */
62815 pMem->u.i = (signed char)buf[0];
62816 pMem->flags = MEM_Int;
62817 return 1;
62819 case 2: { /* 2-byte signed integer */
62820 pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
62821 pMem->flags = MEM_Int;
62822 return 2;
62824 case 3: { /* 3-byte signed integer */
62825 pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
62826 pMem->flags = MEM_Int;
62827 return 3;
62829 case 4: { /* 4-byte signed integer */
62830 pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62831 pMem->flags = MEM_Int;
62832 return 4;
62834 case 5: { /* 6-byte signed integer */
62835 u64 x = (((signed char)buf[0])<<8) | buf[1];
62836 u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
62837 x = (x<<32) | y;
62838 pMem->u.i = *(i64*)&x;
62839 pMem->flags = MEM_Int;
62840 return 6;
62842 case 6: /* 8-byte signed integer */
62843 case 7: { /* IEEE floating point */
62844 u64 x;
62845 u32 y;
62846 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
62847 /* Verify that integers and floating point values use the same
62848 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
62849 ** defined that 64-bit floating point values really are mixed
62850 ** endian.
62852 static const u64 t1 = ((u64)0x3ff00000)<<32;
62853 static const double r1 = 1.0;
62854 u64 t2 = t1;
62855 swapMixedEndianFloat(t2);
62856 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
62857 #endif
62859 x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62860 y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
62861 x = (x<<32) | y;
62862 if( serial_type==6 ){
62863 pMem->u.i = *(i64*)&x;
62864 pMem->flags = MEM_Int;
62865 }else{
62866 assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
62867 swapMixedEndianFloat(x);
62868 memcpy(&pMem->r, &x, sizeof(x));
62869 pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
62871 return 8;
62873 case 8: /* Integer 0 */
62874 case 9: { /* Integer 1 */
62875 pMem->u.i = serial_type-8;
62876 pMem->flags = MEM_Int;
62877 return 0;
62879 default: {
62880 u32 len = (serial_type-12)/2;
62881 pMem->z = (char *)buf;
62882 pMem->n = len;
62883 pMem->xDel = 0;
62884 if( serial_type&0x01 ){
62885 pMem->flags = MEM_Str | MEM_Ephem;
62886 }else{
62887 pMem->flags = MEM_Blob | MEM_Ephem;
62889 return len;
62892 return 0;
62896 ** This routine is used to allocate sufficient space for an UnpackedRecord
62897 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
62898 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
62900 ** The space is either allocated using sqlite3DbMallocRaw() or from within
62901 ** the unaligned buffer passed via the second and third arguments (presumably
62902 ** stack space). If the former, then *ppFree is set to a pointer that should
62903 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
62904 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
62905 ** before returning.
62907 ** If an OOM error occurs, NULL is returned.
62909 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
62910 KeyInfo *pKeyInfo, /* Description of the record */
62911 char *pSpace, /* Unaligned space available */
62912 int szSpace, /* Size of pSpace[] in bytes */
62913 char **ppFree /* OUT: Caller should free this pointer */
62915 UnpackedRecord *p; /* Unpacked record to return */
62916 int nOff; /* Increment pSpace by nOff to align it */
62917 int nByte; /* Number of bytes required for *p */
62919 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
62920 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
62921 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
62923 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
62924 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
62925 if( nByte>szSpace+nOff ){
62926 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
62927 *ppFree = (char *)p;
62928 if( !p ) return 0;
62929 }else{
62930 p = (UnpackedRecord*)&pSpace[nOff];
62931 *ppFree = 0;
62934 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
62935 assert( pKeyInfo->aSortOrder!=0 );
62936 p->pKeyInfo = pKeyInfo;
62937 p->nField = pKeyInfo->nField + 1;
62938 return p;
62942 ** Given the nKey-byte encoding of a record in pKey[], populate the
62943 ** UnpackedRecord structure indicated by the fourth argument with the
62944 ** contents of the decoded record.
62946 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
62947 KeyInfo *pKeyInfo, /* Information about the record format */
62948 int nKey, /* Size of the binary record */
62949 const void *pKey, /* The binary record */
62950 UnpackedRecord *p /* Populate this structure before returning. */
62952 const unsigned char *aKey = (const unsigned char *)pKey;
62953 int d;
62954 u32 idx; /* Offset in aKey[] to read from */
62955 u16 u; /* Unsigned loop counter */
62956 u32 szHdr;
62957 Mem *pMem = p->aMem;
62959 p->flags = 0;
62960 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62961 idx = getVarint32(aKey, szHdr);
62962 d = szHdr;
62963 u = 0;
62964 while( idx<szHdr && u<p->nField && d<=nKey ){
62965 u32 serial_type;
62967 idx += getVarint32(&aKey[idx], serial_type);
62968 pMem->enc = pKeyInfo->enc;
62969 pMem->db = pKeyInfo->db;
62970 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
62971 pMem->zMalloc = 0;
62972 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
62973 pMem++;
62974 u++;
62976 assert( u<=pKeyInfo->nField + 1 );
62977 p->nField = u;
62981 ** This function compares the two table rows or index records
62982 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
62983 ** or positive integer if key1 is less than, equal to or
62984 ** greater than key2. The {nKey1, pKey1} key must be a blob
62985 ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
62986 ** key must be a parsed key such as obtained from
62987 ** sqlite3VdbeParseRecord.
62989 ** Key1 and Key2 do not have to contain the same number of fields.
62990 ** The key with fewer fields is usually compares less than the
62991 ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
62992 ** and the common prefixes are equal, then key1 is less than key2.
62993 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
62994 ** equal, then the keys are considered to be equal and
62995 ** the parts beyond the common prefix are ignored.
62997 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
62998 int nKey1, const void *pKey1, /* Left key */
62999 UnpackedRecord *pPKey2 /* Right key */
63001 u32 d1; /* Offset into aKey[] of next data element */
63002 u32 idx1; /* Offset into aKey[] of next header element */
63003 u32 szHdr1; /* Number of bytes in header */
63004 int i = 0;
63005 int rc = 0;
63006 const unsigned char *aKey1 = (const unsigned char *)pKey1;
63007 KeyInfo *pKeyInfo;
63008 Mem mem1;
63010 pKeyInfo = pPKey2->pKeyInfo;
63011 mem1.enc = pKeyInfo->enc;
63012 mem1.db = pKeyInfo->db;
63013 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
63014 VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
63016 /* Compilers may complain that mem1.u.i is potentially uninitialized.
63017 ** We could initialize it, as shown here, to silence those complaints.
63018 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
63019 ** the unnecessary initialization has a measurable negative performance
63020 ** impact, since this routine is a very high runner. And so, we choose
63021 ** to ignore the compiler warnings and leave this variable uninitialized.
63023 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
63025 idx1 = getVarint32(aKey1, szHdr1);
63026 d1 = szHdr1;
63027 assert( pKeyInfo->nField+1>=pPKey2->nField );
63028 assert( pKeyInfo->aSortOrder!=0 );
63029 while( idx1<szHdr1 && i<pPKey2->nField ){
63030 u32 serial_type1;
63032 /* Read the serial types for the next element in each key. */
63033 idx1 += getVarint32( aKey1+idx1, serial_type1 );
63035 /* Verify that there is enough key space remaining to avoid
63036 ** a buffer overread. The "d1+serial_type1+2" subexpression will
63037 ** always be greater than or equal to the amount of required key space.
63038 ** Use that approximation to avoid the more expensive call to
63039 ** sqlite3VdbeSerialTypeLen() in the common case.
63041 if( d1+serial_type1+2>(u32)nKey1
63042 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
63044 break;
63047 /* Extract the values to be compared.
63049 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
63051 /* Do the comparison
63053 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
63054 if( rc!=0 ){
63055 assert( mem1.zMalloc==0 ); /* See comment below */
63057 /* Invert the result if we are using DESC sort order. */
63058 if( pKeyInfo->aSortOrder[i] ){
63059 rc = -rc;
63062 /* If the PREFIX_SEARCH flag is set and all fields except the final
63063 ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
63064 ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
63065 ** This is used by the OP_IsUnique opcode.
63067 if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
63068 assert( idx1==szHdr1 && rc );
63069 assert( mem1.flags & MEM_Int );
63070 pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
63071 pPKey2->rowid = mem1.u.i;
63074 return rc;
63076 i++;
63079 /* No memory allocation is ever used on mem1. Prove this using
63080 ** the following assert(). If the assert() fails, it indicates a
63081 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
63083 assert( mem1.zMalloc==0 );
63085 /* rc==0 here means that one of the keys ran out of fields and
63086 ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
63087 ** flag is set, then break the tie by treating key2 as larger.
63088 ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
63089 ** are considered to be equal. Otherwise, the longer key is the
63090 ** larger. As it happens, the pPKey2 will always be the longer
63091 ** if there is a difference.
63093 assert( rc==0 );
63094 if( pPKey2->flags & UNPACKED_INCRKEY ){
63095 rc = -1;
63096 }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
63097 /* Leave rc==0 */
63098 }else if( idx1<szHdr1 ){
63099 rc = 1;
63101 return rc;
63106 ** pCur points at an index entry created using the OP_MakeRecord opcode.
63107 ** Read the rowid (the last field in the record) and store it in *rowid.
63108 ** Return SQLITE_OK if everything works, or an error code otherwise.
63110 ** pCur might be pointing to text obtained from a corrupt database file.
63111 ** So the content cannot be trusted. Do appropriate checks on the content.
63113 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
63114 i64 nCellKey = 0;
63115 int rc;
63116 u32 szHdr; /* Size of the header */
63117 u32 typeRowid; /* Serial type of the rowid */
63118 u32 lenRowid; /* Size of the rowid */
63119 Mem m, v;
63121 UNUSED_PARAMETER(db);
63123 /* Get the size of the index entry. Only indices entries of less
63124 ** than 2GiB are support - anything large must be database corruption.
63125 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
63126 ** this code can safely assume that nCellKey is 32-bits
63128 assert( sqlite3BtreeCursorIsValid(pCur) );
63129 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
63130 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
63131 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
63133 /* Read in the complete content of the index entry */
63134 memset(&m, 0, sizeof(m));
63135 rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
63136 if( rc ){
63137 return rc;
63140 /* The index entry must begin with a header size */
63141 (void)getVarint32((u8*)m.z, szHdr);
63142 testcase( szHdr==3 );
63143 testcase( szHdr==m.n );
63144 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
63145 goto idx_rowid_corruption;
63148 /* The last field of the index should be an integer - the ROWID.
63149 ** Verify that the last entry really is an integer. */
63150 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
63151 testcase( typeRowid==1 );
63152 testcase( typeRowid==2 );
63153 testcase( typeRowid==3 );
63154 testcase( typeRowid==4 );
63155 testcase( typeRowid==5 );
63156 testcase( typeRowid==6 );
63157 testcase( typeRowid==8 );
63158 testcase( typeRowid==9 );
63159 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
63160 goto idx_rowid_corruption;
63162 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
63163 testcase( (u32)m.n==szHdr+lenRowid );
63164 if( unlikely((u32)m.n<szHdr+lenRowid) ){
63165 goto idx_rowid_corruption;
63168 /* Fetch the integer off the end of the index record */
63169 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
63170 *rowid = v.u.i;
63171 sqlite3VdbeMemRelease(&m);
63172 return SQLITE_OK;
63174 /* Jump here if database corruption is detected after m has been
63175 ** allocated. Free the m object and return SQLITE_CORRUPT. */
63176 idx_rowid_corruption:
63177 testcase( m.zMalloc!=0 );
63178 sqlite3VdbeMemRelease(&m);
63179 return SQLITE_CORRUPT_BKPT;
63183 ** Compare the key of the index entry that cursor pC is pointing to against
63184 ** the key string in pUnpacked. Write into *pRes a number
63185 ** that is negative, zero, or positive if pC is less than, equal to,
63186 ** or greater than pUnpacked. Return SQLITE_OK on success.
63188 ** pUnpacked is either created without a rowid or is truncated so that it
63189 ** omits the rowid at the end. The rowid at the end of the index entry
63190 ** is ignored as well. Hence, this routine only compares the prefixes
63191 ** of the keys prior to the final rowid, not the entire key.
63193 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
63194 VdbeCursor *pC, /* The cursor to compare against */
63195 UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
63196 int *res /* Write the comparison result here */
63198 i64 nCellKey = 0;
63199 int rc;
63200 BtCursor *pCur = pC->pCursor;
63201 Mem m;
63203 assert( sqlite3BtreeCursorIsValid(pCur) );
63204 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
63205 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
63206 /* nCellKey will always be between 0 and 0xffffffff because of the say
63207 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
63208 if( nCellKey<=0 || nCellKey>0x7fffffff ){
63209 *res = 0;
63210 return SQLITE_CORRUPT_BKPT;
63212 memset(&m, 0, sizeof(m));
63213 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
63214 if( rc ){
63215 return rc;
63217 assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
63218 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
63219 sqlite3VdbeMemRelease(&m);
63220 return SQLITE_OK;
63224 ** This routine sets the value to be returned by subsequent calls to
63225 ** sqlite3_changes() on the database handle 'db'.
63227 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
63228 assert( sqlite3_mutex_held(db->mutex) );
63229 db->nChange = nChange;
63230 db->nTotalChange += nChange;
63234 ** Set a flag in the vdbe to update the change counter when it is finalised
63235 ** or reset.
63237 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
63238 v->changeCntOn = 1;
63242 ** Mark every prepared statement associated with a database connection
63243 ** as expired.
63245 ** An expired statement means that recompilation of the statement is
63246 ** recommend. Statements expire when things happen that make their
63247 ** programs obsolete. Removing user-defined functions or collating
63248 ** sequences, or changing an authorization function are the types of
63249 ** things that make prepared statements obsolete.
63251 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
63252 Vdbe *p;
63253 for(p = db->pVdbe; p; p=p->pNext){
63254 p->expired = 1;
63259 ** Return the database associated with the Vdbe.
63261 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
63262 return v->db;
63266 ** Return a pointer to an sqlite3_value structure containing the value bound
63267 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
63268 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
63269 ** constants) to the value before returning it.
63271 ** The returned value must be freed by the caller using sqlite3ValueFree().
63273 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
63274 assert( iVar>0 );
63275 if( v ){
63276 Mem *pMem = &v->aVar[iVar-1];
63277 if( 0==(pMem->flags & MEM_Null) ){
63278 sqlite3_value *pRet = sqlite3ValueNew(v->db);
63279 if( pRet ){
63280 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
63281 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
63282 sqlite3VdbeMemStoreType((Mem *)pRet);
63284 return pRet;
63287 return 0;
63291 ** Configure SQL variable iVar so that binding a new value to it signals
63292 ** to sqlite3_reoptimize() that re-preparing the statement may result
63293 ** in a better query plan.
63295 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
63296 assert( iVar>0 );
63297 if( iVar>32 ){
63298 v->expmask = 0xffffffff;
63299 }else{
63300 v->expmask |= ((u32)1 << (iVar-1));
63304 #ifndef SQLITE_OMIT_VIRTUALTABLE
63306 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
63307 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
63308 ** in memory obtained from sqlite3DbMalloc).
63310 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
63311 sqlite3 *db = p->db;
63312 sqlite3DbFree(db, p->zErrMsg);
63313 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
63314 sqlite3_free(pVtab->zErrMsg);
63315 pVtab->zErrMsg = 0;
63317 #endif /* SQLITE_OMIT_VIRTUALTABLE */
63319 /************** End of vdbeaux.c *********************************************/
63320 /************** Begin file vdbeapi.c *****************************************/
63322 ** 2004 May 26
63324 ** The author disclaims copyright to this source code. In place of
63325 ** a legal notice, here is a blessing:
63327 ** May you do good and not evil.
63328 ** May you find forgiveness for yourself and forgive others.
63329 ** May you share freely, never taking more than you give.
63331 *************************************************************************
63333 ** This file contains code use to implement APIs that are part of the
63334 ** VDBE.
63337 #ifndef SQLITE_OMIT_DEPRECATED
63339 ** Return TRUE (non-zero) of the statement supplied as an argument needs
63340 ** to be recompiled. A statement needs to be recompiled whenever the
63341 ** execution environment changes in a way that would alter the program
63342 ** that sqlite3_prepare() generates. For example, if new functions or
63343 ** collating sequences are registered or if an authorizer function is
63344 ** added or changed.
63346 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
63347 Vdbe *p = (Vdbe*)pStmt;
63348 return p==0 || p->expired;
63350 #endif
63353 ** Check on a Vdbe to make sure it has not been finalized. Log
63354 ** an error and return true if it has been finalized (or is otherwise
63355 ** invalid). Return false if it is ok.
63357 static int vdbeSafety(Vdbe *p){
63358 if( p->db==0 ){
63359 sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
63360 return 1;
63361 }else{
63362 return 0;
63365 static int vdbeSafetyNotNull(Vdbe *p){
63366 if( p==0 ){
63367 sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
63368 return 1;
63369 }else{
63370 return vdbeSafety(p);
63375 ** The following routine destroys a virtual machine that is created by
63376 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
63377 ** success/failure code that describes the result of executing the virtual
63378 ** machine.
63380 ** This routine sets the error code and string returned by
63381 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
63383 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
63384 int rc;
63385 if( pStmt==0 ){
63386 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
63387 ** pointer is a harmless no-op. */
63388 rc = SQLITE_OK;
63389 }else{
63390 Vdbe *v = (Vdbe*)pStmt;
63391 sqlite3 *db = v->db;
63392 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
63393 sqlite3_mutex_enter(db->mutex);
63394 rc = sqlite3VdbeFinalize(v);
63395 rc = sqlite3ApiExit(db, rc);
63396 sqlite3LeaveMutexAndCloseZombie(db);
63398 return rc;
63402 ** Terminate the current execution of an SQL statement and reset it
63403 ** back to its starting state so that it can be reused. A success code from
63404 ** the prior execution is returned.
63406 ** This routine sets the error code and string returned by
63407 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
63409 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
63410 int rc;
63411 if( pStmt==0 ){
63412 rc = SQLITE_OK;
63413 }else{
63414 Vdbe *v = (Vdbe*)pStmt;
63415 sqlite3_mutex_enter(v->db->mutex);
63416 rc = sqlite3VdbeReset(v);
63417 sqlite3VdbeRewind(v);
63418 assert( (rc & (v->db->errMask))==rc );
63419 rc = sqlite3ApiExit(v->db, rc);
63420 sqlite3_mutex_leave(v->db->mutex);
63422 return rc;
63426 ** Set all the parameters in the compiled SQL statement to NULL.
63428 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
63429 int i;
63430 int rc = SQLITE_OK;
63431 Vdbe *p = (Vdbe*)pStmt;
63432 #if SQLITE_THREADSAFE
63433 sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
63434 #endif
63435 sqlite3_mutex_enter(mutex);
63436 for(i=0; i<p->nVar; i++){
63437 sqlite3VdbeMemRelease(&p->aVar[i]);
63438 p->aVar[i].flags = MEM_Null;
63440 if( p->isPrepareV2 && p->expmask ){
63441 p->expired = 1;
63443 sqlite3_mutex_leave(mutex);
63444 return rc;
63448 /**************************** sqlite3_value_ *******************************
63449 ** The following routines extract information from a Mem or sqlite3_value
63450 ** structure.
63452 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
63453 Mem *p = (Mem*)pVal;
63454 if( p->flags & (MEM_Blob|MEM_Str) ){
63455 sqlite3VdbeMemExpandBlob(p);
63456 p->flags &= ~MEM_Str;
63457 p->flags |= MEM_Blob;
63458 return p->n ? p->z : 0;
63459 }else{
63460 return sqlite3_value_text(pVal);
63463 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
63464 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
63466 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
63467 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
63469 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
63470 return sqlite3VdbeRealValue((Mem*)pVal);
63472 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
63473 return (int)sqlite3VdbeIntValue((Mem*)pVal);
63475 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
63476 return sqlite3VdbeIntValue((Mem*)pVal);
63478 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
63479 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
63481 #ifndef SQLITE_OMIT_UTF16
63482 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
63483 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
63485 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
63486 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
63488 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
63489 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
63491 #endif /* SQLITE_OMIT_UTF16 */
63492 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
63493 return pVal->type;
63496 /**************************** sqlite3_result_ *******************************
63497 ** The following routines are used by user-defined functions to specify
63498 ** the function result.
63500 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
63501 ** result as a string or blob but if the string or blob is too large, it
63502 ** then sets the error code to SQLITE_TOOBIG
63504 static void setResultStrOrError(
63505 sqlite3_context *pCtx, /* Function context */
63506 const char *z, /* String pointer */
63507 int n, /* Bytes in string, or negative */
63508 u8 enc, /* Encoding of z. 0 for BLOBs */
63509 void (*xDel)(void*) /* Destructor function */
63511 if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
63512 sqlite3_result_error_toobig(pCtx);
63515 SQLITE_API void sqlite3_result_blob(
63516 sqlite3_context *pCtx,
63517 const void *z,
63518 int n,
63519 void (*xDel)(void *)
63521 assert( n>=0 );
63522 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63523 setResultStrOrError(pCtx, z, n, 0, xDel);
63525 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
63526 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63527 sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
63529 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
63530 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63531 pCtx->isError = SQLITE_ERROR;
63532 pCtx->fErrorOrAux = 1;
63533 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
63535 #ifndef SQLITE_OMIT_UTF16
63536 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
63537 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63538 pCtx->isError = SQLITE_ERROR;
63539 pCtx->fErrorOrAux = 1;
63540 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
63542 #endif
63543 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
63544 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63545 sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
63547 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
63548 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63549 sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
63551 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
63552 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63553 sqlite3VdbeMemSetNull(&pCtx->s);
63555 SQLITE_API void sqlite3_result_text(
63556 sqlite3_context *pCtx,
63557 const char *z,
63558 int n,
63559 void (*xDel)(void *)
63561 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63562 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
63564 #ifndef SQLITE_OMIT_UTF16
63565 SQLITE_API void sqlite3_result_text16(
63566 sqlite3_context *pCtx,
63567 const void *z,
63568 int n,
63569 void (*xDel)(void *)
63571 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63572 setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
63574 SQLITE_API void sqlite3_result_text16be(
63575 sqlite3_context *pCtx,
63576 const void *z,
63577 int n,
63578 void (*xDel)(void *)
63580 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63581 setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
63583 SQLITE_API void sqlite3_result_text16le(
63584 sqlite3_context *pCtx,
63585 const void *z,
63586 int n,
63587 void (*xDel)(void *)
63589 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63590 setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
63592 #endif /* SQLITE_OMIT_UTF16 */
63593 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
63594 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63595 sqlite3VdbeMemCopy(&pCtx->s, pValue);
63597 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
63598 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63599 sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
63601 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
63602 pCtx->isError = errCode;
63603 pCtx->fErrorOrAux = 1;
63604 if( pCtx->s.flags & MEM_Null ){
63605 sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
63606 SQLITE_UTF8, SQLITE_STATIC);
63610 /* Force an SQLITE_TOOBIG error. */
63611 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
63612 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63613 pCtx->isError = SQLITE_TOOBIG;
63614 pCtx->fErrorOrAux = 1;
63615 sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
63616 SQLITE_UTF8, SQLITE_STATIC);
63619 /* An SQLITE_NOMEM error. */
63620 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
63621 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63622 sqlite3VdbeMemSetNull(&pCtx->s);
63623 pCtx->isError = SQLITE_NOMEM;
63624 pCtx->fErrorOrAux = 1;
63625 pCtx->s.db->mallocFailed = 1;
63629 ** This function is called after a transaction has been committed. It
63630 ** invokes callbacks registered with sqlite3_wal_hook() as required.
63632 static int doWalCallbacks(sqlite3 *db){
63633 int rc = SQLITE_OK;
63634 #ifndef SQLITE_OMIT_WAL
63635 int i;
63636 for(i=0; i<db->nDb; i++){
63637 Btree *pBt = db->aDb[i].pBt;
63638 if( pBt ){
63639 int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
63640 if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
63641 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
63645 #endif
63646 return rc;
63650 ** Execute the statement pStmt, either until a row of data is ready, the
63651 ** statement is completely executed or an error occurs.
63653 ** This routine implements the bulk of the logic behind the sqlite_step()
63654 ** API. The only thing omitted is the automatic recompile if a
63655 ** schema change has occurred. That detail is handled by the
63656 ** outer sqlite3_step() wrapper procedure.
63658 static int sqlite3Step(Vdbe *p){
63659 sqlite3 *db;
63660 int rc;
63662 assert(p);
63663 if( p->magic!=VDBE_MAGIC_RUN ){
63664 /* We used to require that sqlite3_reset() be called before retrying
63665 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
63666 ** with version 3.7.0, we changed this so that sqlite3_reset() would
63667 ** be called automatically instead of throwing the SQLITE_MISUSE error.
63668 ** This "automatic-reset" change is not technically an incompatibility,
63669 ** since any application that receives an SQLITE_MISUSE is broken by
63670 ** definition.
63672 ** Nevertheless, some published applications that were originally written
63673 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
63674 ** returns, and those were broken by the automatic-reset change. As a
63675 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
63676 ** legacy behavior of returning SQLITE_MISUSE for cases where the
63677 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
63678 ** or SQLITE_BUSY error.
63680 #ifdef SQLITE_OMIT_AUTORESET
63681 if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
63682 sqlite3_reset((sqlite3_stmt*)p);
63683 }else{
63684 return SQLITE_MISUSE_BKPT;
63686 #else
63687 sqlite3_reset((sqlite3_stmt*)p);
63688 #endif
63691 /* Check that malloc() has not failed. If it has, return early. */
63692 db = p->db;
63693 if( db->mallocFailed ){
63694 p->rc = SQLITE_NOMEM;
63695 return SQLITE_NOMEM;
63698 if( p->pc<=0 && p->expired ){
63699 p->rc = SQLITE_SCHEMA;
63700 rc = SQLITE_ERROR;
63701 goto end_of_step;
63703 if( p->pc<0 ){
63704 /* If there are no other statements currently running, then
63705 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
63706 ** from interrupting a statement that has not yet started.
63708 if( db->nVdbeActive==0 ){
63709 db->u1.isInterrupted = 0;
63712 assert( db->nVdbeWrite>0 || db->autoCommit==0
63713 || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
63716 #ifndef SQLITE_OMIT_TRACE
63717 if( db->xProfile && !db->init.busy ){
63718 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
63720 #endif
63722 db->nVdbeActive++;
63723 if( p->readOnly==0 ) db->nVdbeWrite++;
63724 if( p->bIsReader ) db->nVdbeRead++;
63725 p->pc = 0;
63727 #ifndef SQLITE_OMIT_EXPLAIN
63728 if( p->explain ){
63729 rc = sqlite3VdbeList(p);
63730 }else
63731 #endif /* SQLITE_OMIT_EXPLAIN */
63733 db->nVdbeExec++;
63734 rc = sqlite3VdbeExec(p);
63735 db->nVdbeExec--;
63738 #ifndef SQLITE_OMIT_TRACE
63739 /* Invoke the profile callback if there is one
63741 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
63742 sqlite3_int64 iNow;
63743 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
63744 db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
63746 #endif
63748 if( rc==SQLITE_DONE ){
63749 assert( p->rc==SQLITE_OK );
63750 p->rc = doWalCallbacks(db);
63751 if( p->rc!=SQLITE_OK ){
63752 rc = SQLITE_ERROR;
63756 db->errCode = rc;
63757 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
63758 p->rc = SQLITE_NOMEM;
63760 end_of_step:
63761 /* At this point local variable rc holds the value that should be
63762 ** returned if this statement was compiled using the legacy
63763 ** sqlite3_prepare() interface. According to the docs, this can only
63764 ** be one of the values in the first assert() below. Variable p->rc
63765 ** contains the value that would be returned if sqlite3_finalize()
63766 ** were called on statement p.
63768 assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
63769 || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
63771 assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
63772 if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
63773 /* If this statement was prepared using sqlite3_prepare_v2(), and an
63774 ** error has occurred, then return the error code in p->rc to the
63775 ** caller. Set the error code in the database handle to the same value.
63777 rc = sqlite3VdbeTransferError(p);
63779 return (rc&db->errMask);
63783 ** This is the top-level implementation of sqlite3_step(). Call
63784 ** sqlite3Step() to do most of the work. If a schema error occurs,
63785 ** call sqlite3Reprepare() and try again.
63787 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
63788 int rc = SQLITE_OK; /* Result from sqlite3Step() */
63789 int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
63790 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
63791 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
63792 sqlite3 *db; /* The database connection */
63794 if( vdbeSafetyNotNull(v) ){
63795 return SQLITE_MISUSE_BKPT;
63797 db = v->db;
63798 sqlite3_mutex_enter(db->mutex);
63799 v->doingRerun = 0;
63800 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
63801 && cnt++ < SQLITE_MAX_SCHEMA_RETRY
63802 && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
63803 sqlite3_reset(pStmt);
63804 v->doingRerun = 1;
63805 assert( v->expired==0 );
63807 if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
63808 /* This case occurs after failing to recompile an sql statement.
63809 ** The error message from the SQL compiler has already been loaded
63810 ** into the database handle. This block copies the error message
63811 ** from the database handle into the statement and sets the statement
63812 ** program counter to 0 to ensure that when the statement is
63813 ** finalized or reset the parser error message is available via
63814 ** sqlite3_errmsg() and sqlite3_errcode().
63816 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
63817 sqlite3DbFree(db, v->zErrMsg);
63818 if( !db->mallocFailed ){
63819 v->zErrMsg = sqlite3DbStrDup(db, zErr);
63820 v->rc = rc2;
63821 } else {
63822 v->zErrMsg = 0;
63823 v->rc = rc = SQLITE_NOMEM;
63826 rc = sqlite3ApiExit(db, rc);
63827 sqlite3_mutex_leave(db->mutex);
63828 return rc;
63832 ** Extract the user data from a sqlite3_context structure and return a
63833 ** pointer to it.
63835 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
63836 assert( p && p->pFunc );
63837 return p->pFunc->pUserData;
63841 ** Extract the user data from a sqlite3_context structure and return a
63842 ** pointer to it.
63844 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
63845 ** returns a copy of the pointer to the database connection (the 1st
63846 ** parameter) of the sqlite3_create_function() and
63847 ** sqlite3_create_function16() routines that originally registered the
63848 ** application defined function.
63850 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
63851 assert( p && p->pFunc );
63852 return p->s.db;
63856 ** The following is the implementation of an SQL function that always
63857 ** fails with an error message stating that the function is used in the
63858 ** wrong context. The sqlite3_overload_function() API might construct
63859 ** SQL function that use this routine so that the functions will exist
63860 ** for name resolution but are actually overloaded by the xFindFunction
63861 ** method of virtual tables.
63863 SQLITE_PRIVATE void sqlite3InvalidFunction(
63864 sqlite3_context *context, /* The function calling context */
63865 int NotUsed, /* Number of arguments to the function */
63866 sqlite3_value **NotUsed2 /* Value of each argument */
63868 const char *zName = context->pFunc->zName;
63869 char *zErr;
63870 UNUSED_PARAMETER2(NotUsed, NotUsed2);
63871 zErr = sqlite3_mprintf(
63872 "unable to use function %s in the requested context", zName);
63873 sqlite3_result_error(context, zErr, -1);
63874 sqlite3_free(zErr);
63878 ** Allocate or return the aggregate context for a user function. A new
63879 ** context is allocated on the first call. Subsequent calls return the
63880 ** same context that was returned on prior calls.
63882 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
63883 Mem *pMem;
63884 assert( p && p->pFunc && p->pFunc->xStep );
63885 assert( sqlite3_mutex_held(p->s.db->mutex) );
63886 pMem = p->pMem;
63887 testcase( nByte<0 );
63888 if( (pMem->flags & MEM_Agg)==0 ){
63889 if( nByte<=0 ){
63890 sqlite3VdbeMemReleaseExternal(pMem);
63891 pMem->flags = MEM_Null;
63892 pMem->z = 0;
63893 }else{
63894 sqlite3VdbeMemGrow(pMem, nByte, 0);
63895 pMem->flags = MEM_Agg;
63896 pMem->u.pDef = p->pFunc;
63897 if( pMem->z ){
63898 memset(pMem->z, 0, nByte);
63902 return (void*)pMem->z;
63906 ** Return the auxilary data pointer, if any, for the iArg'th argument to
63907 ** the user-function defined by pCtx.
63909 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
63910 AuxData *pAuxData;
63912 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63913 for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
63914 if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
63917 return (pAuxData ? pAuxData->pAux : 0);
63921 ** Set the auxilary data pointer and delete function, for the iArg'th
63922 ** argument to the user-function defined by pCtx. Any previous value is
63923 ** deleted by calling the delete function specified when it was set.
63925 SQLITE_API void sqlite3_set_auxdata(
63926 sqlite3_context *pCtx,
63927 int iArg,
63928 void *pAux,
63929 void (*xDelete)(void*)
63931 AuxData *pAuxData;
63932 Vdbe *pVdbe = pCtx->pVdbe;
63934 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63935 if( iArg<0 ) goto failed;
63937 for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
63938 if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
63940 if( pAuxData==0 ){
63941 pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
63942 if( !pAuxData ) goto failed;
63943 pAuxData->iOp = pCtx->iOp;
63944 pAuxData->iArg = iArg;
63945 pAuxData->pNext = pVdbe->pAuxData;
63946 pVdbe->pAuxData = pAuxData;
63947 if( pCtx->fErrorOrAux==0 ){
63948 pCtx->isError = 0;
63949 pCtx->fErrorOrAux = 1;
63951 }else if( pAuxData->xDelete ){
63952 pAuxData->xDelete(pAuxData->pAux);
63955 pAuxData->pAux = pAux;
63956 pAuxData->xDelete = xDelete;
63957 return;
63959 failed:
63960 if( xDelete ){
63961 xDelete(pAux);
63965 #ifndef SQLITE_OMIT_DEPRECATED
63967 ** Return the number of times the Step function of a aggregate has been
63968 ** called.
63970 ** This function is deprecated. Do not use it for new code. It is
63971 ** provide only to avoid breaking legacy code. New aggregate function
63972 ** implementations should keep their own counts within their aggregate
63973 ** context.
63975 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
63976 assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
63977 return p->pMem->n;
63979 #endif
63982 ** Return the number of columns in the result set for the statement pStmt.
63984 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
63985 Vdbe *pVm = (Vdbe *)pStmt;
63986 return pVm ? pVm->nResColumn : 0;
63990 ** Return the number of values available from the current row of the
63991 ** currently executing statement pStmt.
63993 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
63994 Vdbe *pVm = (Vdbe *)pStmt;
63995 if( pVm==0 || pVm->pResultSet==0 ) return 0;
63996 return pVm->nResColumn;
64001 ** Check to see if column iCol of the given statement is valid. If
64002 ** it is, return a pointer to the Mem for the value of that column.
64003 ** If iCol is not valid, return a pointer to a Mem which has a value
64004 ** of NULL.
64006 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
64007 Vdbe *pVm;
64008 Mem *pOut;
64010 pVm = (Vdbe *)pStmt;
64011 if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
64012 sqlite3_mutex_enter(pVm->db->mutex);
64013 pOut = &pVm->pResultSet[i];
64014 }else{
64015 /* If the value passed as the second argument is out of range, return
64016 ** a pointer to the following static Mem object which contains the
64017 ** value SQL NULL. Even though the Mem structure contains an element
64018 ** of type i64, on certain architectures (x86) with certain compiler
64019 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
64020 ** instead of an 8-byte one. This all works fine, except that when
64021 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
64022 ** that a Mem structure is located on an 8-byte boundary. To prevent
64023 ** these assert()s from failing, when building with SQLITE_DEBUG defined
64024 ** using gcc, we force nullMem to be 8-byte aligned using the magical
64025 ** __attribute__((aligned(8))) macro. */
64026 static const Mem nullMem
64027 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
64028 __attribute__((aligned(8)))
64029 #endif
64030 = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
64031 #ifdef SQLITE_DEBUG
64032 0, 0, /* pScopyFrom, pFiller */
64033 #endif
64034 0, 0 };
64036 if( pVm && ALWAYS(pVm->db) ){
64037 sqlite3_mutex_enter(pVm->db->mutex);
64038 sqlite3Error(pVm->db, SQLITE_RANGE, 0);
64040 pOut = (Mem*)&nullMem;
64042 return pOut;
64046 ** This function is called after invoking an sqlite3_value_XXX function on a
64047 ** column value (i.e. a value returned by evaluating an SQL expression in the
64048 ** select list of a SELECT statement) that may cause a malloc() failure. If
64049 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
64050 ** code of statement pStmt set to SQLITE_NOMEM.
64052 ** Specifically, this is called from within:
64054 ** sqlite3_column_int()
64055 ** sqlite3_column_int64()
64056 ** sqlite3_column_text()
64057 ** sqlite3_column_text16()
64058 ** sqlite3_column_real()
64059 ** sqlite3_column_bytes()
64060 ** sqlite3_column_bytes16()
64061 ** sqiite3_column_blob()
64063 static void columnMallocFailure(sqlite3_stmt *pStmt)
64065 /* If malloc() failed during an encoding conversion within an
64066 ** sqlite3_column_XXX API, then set the return code of the statement to
64067 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
64068 ** and _finalize() will return NOMEM.
64070 Vdbe *p = (Vdbe *)pStmt;
64071 if( p ){
64072 p->rc = sqlite3ApiExit(p->db, p->rc);
64073 sqlite3_mutex_leave(p->db->mutex);
64077 /**************************** sqlite3_column_ *******************************
64078 ** The following routines are used to access elements of the current row
64079 ** in the result set.
64081 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
64082 const void *val;
64083 val = sqlite3_value_blob( columnMem(pStmt,i) );
64084 /* Even though there is no encoding conversion, value_blob() might
64085 ** need to call malloc() to expand the result of a zeroblob()
64086 ** expression.
64088 columnMallocFailure(pStmt);
64089 return val;
64091 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
64092 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
64093 columnMallocFailure(pStmt);
64094 return val;
64096 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
64097 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
64098 columnMallocFailure(pStmt);
64099 return val;
64101 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
64102 double val = sqlite3_value_double( columnMem(pStmt,i) );
64103 columnMallocFailure(pStmt);
64104 return val;
64106 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
64107 int val = sqlite3_value_int( columnMem(pStmt,i) );
64108 columnMallocFailure(pStmt);
64109 return val;
64111 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
64112 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
64113 columnMallocFailure(pStmt);
64114 return val;
64116 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
64117 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
64118 columnMallocFailure(pStmt);
64119 return val;
64121 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
64122 Mem *pOut = columnMem(pStmt, i);
64123 if( pOut->flags&MEM_Static ){
64124 pOut->flags &= ~MEM_Static;
64125 pOut->flags |= MEM_Ephem;
64127 columnMallocFailure(pStmt);
64128 return (sqlite3_value *)pOut;
64130 #ifndef SQLITE_OMIT_UTF16
64131 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
64132 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
64133 columnMallocFailure(pStmt);
64134 return val;
64136 #endif /* SQLITE_OMIT_UTF16 */
64137 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
64138 int iType = sqlite3_value_type( columnMem(pStmt,i) );
64139 columnMallocFailure(pStmt);
64140 return iType;
64144 ** Convert the N-th element of pStmt->pColName[] into a string using
64145 ** xFunc() then return that string. If N is out of range, return 0.
64147 ** There are up to 5 names for each column. useType determines which
64148 ** name is returned. Here are the names:
64150 ** 0 The column name as it should be displayed for output
64151 ** 1 The datatype name for the column
64152 ** 2 The name of the database that the column derives from
64153 ** 3 The name of the table that the column derives from
64154 ** 4 The name of the table column that the result column derives from
64156 ** If the result is not a simple column reference (if it is an expression
64157 ** or a constant) then useTypes 2, 3, and 4 return NULL.
64159 static const void *columnName(
64160 sqlite3_stmt *pStmt,
64161 int N,
64162 const void *(*xFunc)(Mem*),
64163 int useType
64165 const void *ret = 0;
64166 Vdbe *p = (Vdbe *)pStmt;
64167 int n;
64168 sqlite3 *db = p->db;
64170 assert( db!=0 );
64171 n = sqlite3_column_count(pStmt);
64172 if( N<n && N>=0 ){
64173 N += useType*n;
64174 sqlite3_mutex_enter(db->mutex);
64175 assert( db->mallocFailed==0 );
64176 ret = xFunc(&p->aColName[N]);
64177 /* A malloc may have failed inside of the xFunc() call. If this
64178 ** is the case, clear the mallocFailed flag and return NULL.
64180 if( db->mallocFailed ){
64181 db->mallocFailed = 0;
64182 ret = 0;
64184 sqlite3_mutex_leave(db->mutex);
64186 return ret;
64190 ** Return the name of the Nth column of the result set returned by SQL
64191 ** statement pStmt.
64193 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
64194 return columnName(
64195 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
64197 #ifndef SQLITE_OMIT_UTF16
64198 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
64199 return columnName(
64200 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
64202 #endif
64205 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
64206 ** not define OMIT_DECLTYPE.
64208 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
64209 # error "Must not define both SQLITE_OMIT_DECLTYPE \
64210 and SQLITE_ENABLE_COLUMN_METADATA"
64211 #endif
64213 #ifndef SQLITE_OMIT_DECLTYPE
64215 ** Return the column declaration type (if applicable) of the 'i'th column
64216 ** of the result set of SQL statement pStmt.
64218 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
64219 return columnName(
64220 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
64222 #ifndef SQLITE_OMIT_UTF16
64223 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
64224 return columnName(
64225 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
64227 #endif /* SQLITE_OMIT_UTF16 */
64228 #endif /* SQLITE_OMIT_DECLTYPE */
64230 #ifdef SQLITE_ENABLE_COLUMN_METADATA
64232 ** Return the name of the database from which a result column derives.
64233 ** NULL is returned if the result column is an expression or constant or
64234 ** anything else which is not an unabiguous reference to a database column.
64236 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
64237 return columnName(
64238 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
64240 #ifndef SQLITE_OMIT_UTF16
64241 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
64242 return columnName(
64243 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
64245 #endif /* SQLITE_OMIT_UTF16 */
64248 ** Return the name of the table from which a result column derives.
64249 ** NULL is returned if the result column is an expression or constant or
64250 ** anything else which is not an unabiguous reference to a database column.
64252 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
64253 return columnName(
64254 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
64256 #ifndef SQLITE_OMIT_UTF16
64257 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
64258 return columnName(
64259 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
64261 #endif /* SQLITE_OMIT_UTF16 */
64264 ** Return the name of the table column from which a result column derives.
64265 ** NULL is returned if the result column is an expression or constant or
64266 ** anything else which is not an unabiguous reference to a database column.
64268 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
64269 return columnName(
64270 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
64272 #ifndef SQLITE_OMIT_UTF16
64273 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
64274 return columnName(
64275 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
64277 #endif /* SQLITE_OMIT_UTF16 */
64278 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
64281 /******************************* sqlite3_bind_ ***************************
64283 ** Routines used to attach values to wildcards in a compiled SQL statement.
64286 ** Unbind the value bound to variable i in virtual machine p. This is the
64287 ** the same as binding a NULL value to the column. If the "i" parameter is
64288 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
64290 ** A successful evaluation of this routine acquires the mutex on p.
64291 ** the mutex is released if any kind of error occurs.
64293 ** The error code stored in database p->db is overwritten with the return
64294 ** value in any case.
64296 static int vdbeUnbind(Vdbe *p, int i){
64297 Mem *pVar;
64298 if( vdbeSafetyNotNull(p) ){
64299 return SQLITE_MISUSE_BKPT;
64301 sqlite3_mutex_enter(p->db->mutex);
64302 if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
64303 sqlite3Error(p->db, SQLITE_MISUSE, 0);
64304 sqlite3_mutex_leave(p->db->mutex);
64305 sqlite3_log(SQLITE_MISUSE,
64306 "bind on a busy prepared statement: [%s]", p->zSql);
64307 return SQLITE_MISUSE_BKPT;
64309 if( i<1 || i>p->nVar ){
64310 sqlite3Error(p->db, SQLITE_RANGE, 0);
64311 sqlite3_mutex_leave(p->db->mutex);
64312 return SQLITE_RANGE;
64314 i--;
64315 pVar = &p->aVar[i];
64316 sqlite3VdbeMemRelease(pVar);
64317 pVar->flags = MEM_Null;
64318 sqlite3Error(p->db, SQLITE_OK, 0);
64320 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
64321 ** binding a new value to this variable invalidates the current query plan.
64323 ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
64324 ** parameter in the WHERE clause might influence the choice of query plan
64325 ** for a statement, then the statement will be automatically recompiled,
64326 ** as if there had been a schema change, on the first sqlite3_step() call
64327 ** following any change to the bindings of that parameter.
64329 if( p->isPrepareV2 &&
64330 ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
64332 p->expired = 1;
64334 return SQLITE_OK;
64338 ** Bind a text or BLOB value.
64340 static int bindText(
64341 sqlite3_stmt *pStmt, /* The statement to bind against */
64342 int i, /* Index of the parameter to bind */
64343 const void *zData, /* Pointer to the data to be bound */
64344 int nData, /* Number of bytes of data to be bound */
64345 void (*xDel)(void*), /* Destructor for the data */
64346 u8 encoding /* Encoding for the data */
64348 Vdbe *p = (Vdbe *)pStmt;
64349 Mem *pVar;
64350 int rc;
64352 rc = vdbeUnbind(p, i);
64353 if( rc==SQLITE_OK ){
64354 if( zData!=0 ){
64355 pVar = &p->aVar[i-1];
64356 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
64357 if( rc==SQLITE_OK && encoding!=0 ){
64358 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
64360 sqlite3Error(p->db, rc, 0);
64361 rc = sqlite3ApiExit(p->db, rc);
64363 sqlite3_mutex_leave(p->db->mutex);
64364 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
64365 xDel((void*)zData);
64367 return rc;
64372 ** Bind a blob value to an SQL statement variable.
64374 SQLITE_API int sqlite3_bind_blob(
64375 sqlite3_stmt *pStmt,
64376 int i,
64377 const void *zData,
64378 int nData,
64379 void (*xDel)(void*)
64381 return bindText(pStmt, i, zData, nData, xDel, 0);
64383 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
64384 int rc;
64385 Vdbe *p = (Vdbe *)pStmt;
64386 rc = vdbeUnbind(p, i);
64387 if( rc==SQLITE_OK ){
64388 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
64389 sqlite3_mutex_leave(p->db->mutex);
64391 return rc;
64393 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
64394 return sqlite3_bind_int64(p, i, (i64)iValue);
64396 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
64397 int rc;
64398 Vdbe *p = (Vdbe *)pStmt;
64399 rc = vdbeUnbind(p, i);
64400 if( rc==SQLITE_OK ){
64401 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
64402 sqlite3_mutex_leave(p->db->mutex);
64404 return rc;
64406 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
64407 int rc;
64408 Vdbe *p = (Vdbe*)pStmt;
64409 rc = vdbeUnbind(p, i);
64410 if( rc==SQLITE_OK ){
64411 sqlite3_mutex_leave(p->db->mutex);
64413 return rc;
64415 SQLITE_API int sqlite3_bind_text(
64416 sqlite3_stmt *pStmt,
64417 int i,
64418 const char *zData,
64419 int nData,
64420 void (*xDel)(void*)
64422 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
64424 #ifndef SQLITE_OMIT_UTF16
64425 SQLITE_API int sqlite3_bind_text16(
64426 sqlite3_stmt *pStmt,
64427 int i,
64428 const void *zData,
64429 int nData,
64430 void (*xDel)(void*)
64432 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
64434 #endif /* SQLITE_OMIT_UTF16 */
64435 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
64436 int rc;
64437 switch( pValue->type ){
64438 case SQLITE_INTEGER: {
64439 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
64440 break;
64442 case SQLITE_FLOAT: {
64443 rc = sqlite3_bind_double(pStmt, i, pValue->r);
64444 break;
64446 case SQLITE_BLOB: {
64447 if( pValue->flags & MEM_Zero ){
64448 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
64449 }else{
64450 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
64452 break;
64454 case SQLITE_TEXT: {
64455 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
64456 pValue->enc);
64457 break;
64459 default: {
64460 rc = sqlite3_bind_null(pStmt, i);
64461 break;
64464 return rc;
64466 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
64467 int rc;
64468 Vdbe *p = (Vdbe *)pStmt;
64469 rc = vdbeUnbind(p, i);
64470 if( rc==SQLITE_OK ){
64471 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
64472 sqlite3_mutex_leave(p->db->mutex);
64474 return rc;
64478 ** Return the number of wildcards that can be potentially bound to.
64479 ** This routine is added to support DBD::SQLite.
64481 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
64482 Vdbe *p = (Vdbe*)pStmt;
64483 return p ? p->nVar : 0;
64487 ** Return the name of a wildcard parameter. Return NULL if the index
64488 ** is out of range or if the wildcard is unnamed.
64490 ** The result is always UTF-8.
64492 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
64493 Vdbe *p = (Vdbe*)pStmt;
64494 if( p==0 || i<1 || i>p->nzVar ){
64495 return 0;
64497 return p->azVar[i-1];
64501 ** Given a wildcard parameter name, return the index of the variable
64502 ** with that name. If there is no variable with the given name,
64503 ** return 0.
64505 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
64506 int i;
64507 if( p==0 ){
64508 return 0;
64510 if( zName ){
64511 for(i=0; i<p->nzVar; i++){
64512 const char *z = p->azVar[i];
64513 if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
64514 return i+1;
64518 return 0;
64520 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
64521 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
64525 ** Transfer all bindings from the first statement over to the second.
64527 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64528 Vdbe *pFrom = (Vdbe*)pFromStmt;
64529 Vdbe *pTo = (Vdbe*)pToStmt;
64530 int i;
64531 assert( pTo->db==pFrom->db );
64532 assert( pTo->nVar==pFrom->nVar );
64533 sqlite3_mutex_enter(pTo->db->mutex);
64534 for(i=0; i<pFrom->nVar; i++){
64535 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
64537 sqlite3_mutex_leave(pTo->db->mutex);
64538 return SQLITE_OK;
64541 #ifndef SQLITE_OMIT_DEPRECATED
64543 ** Deprecated external interface. Internal/core SQLite code
64544 ** should call sqlite3TransferBindings.
64546 ** Is is misuse to call this routine with statements from different
64547 ** database connections. But as this is a deprecated interface, we
64548 ** will not bother to check for that condition.
64550 ** If the two statements contain a different number of bindings, then
64551 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
64552 ** SQLITE_OK is returned.
64554 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64555 Vdbe *pFrom = (Vdbe*)pFromStmt;
64556 Vdbe *pTo = (Vdbe*)pToStmt;
64557 if( pFrom->nVar!=pTo->nVar ){
64558 return SQLITE_ERROR;
64560 if( pTo->isPrepareV2 && pTo->expmask ){
64561 pTo->expired = 1;
64563 if( pFrom->isPrepareV2 && pFrom->expmask ){
64564 pFrom->expired = 1;
64566 return sqlite3TransferBindings(pFromStmt, pToStmt);
64568 #endif
64571 ** Return the sqlite3* database handle to which the prepared statement given
64572 ** in the argument belongs. This is the same database handle that was
64573 ** the first argument to the sqlite3_prepare() that was used to create
64574 ** the statement in the first place.
64576 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
64577 return pStmt ? ((Vdbe*)pStmt)->db : 0;
64581 ** Return true if the prepared statement is guaranteed to not modify the
64582 ** database.
64584 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
64585 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
64589 ** Return true if the prepared statement is in need of being reset.
64591 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
64592 Vdbe *v = (Vdbe*)pStmt;
64593 return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
64597 ** Return a pointer to the next prepared statement after pStmt associated
64598 ** with database connection pDb. If pStmt is NULL, return the first
64599 ** prepared statement for the database connection. Return NULL if there
64600 ** are no more.
64602 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
64603 sqlite3_stmt *pNext;
64604 sqlite3_mutex_enter(pDb->mutex);
64605 if( pStmt==0 ){
64606 pNext = (sqlite3_stmt*)pDb->pVdbe;
64607 }else{
64608 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
64610 sqlite3_mutex_leave(pDb->mutex);
64611 return pNext;
64615 ** Return the value of a status counter for a prepared statement
64617 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
64618 Vdbe *pVdbe = (Vdbe*)pStmt;
64619 u32 v = pVdbe->aCounter[op];
64620 if( resetFlag ) pVdbe->aCounter[op] = 0;
64621 return (int)v;
64624 /************** End of vdbeapi.c *********************************************/
64625 /************** Begin file vdbetrace.c ***************************************/
64627 ** 2009 November 25
64629 ** The author disclaims copyright to this source code. In place of
64630 ** a legal notice, here is a blessing:
64632 ** May you do good and not evil.
64633 ** May you find forgiveness for yourself and forgive others.
64634 ** May you share freely, never taking more than you give.
64636 *************************************************************************
64638 ** This file contains code used to insert the values of host parameters
64639 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
64641 ** The Vdbe parse-tree explainer is also found here.
64644 #ifndef SQLITE_OMIT_TRACE
64647 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
64648 ** bytes in this text up to but excluding the first character in
64649 ** a host parameter. If the text contains no host parameters, return
64650 ** the total number of bytes in the text.
64652 static int findNextHostParameter(const char *zSql, int *pnToken){
64653 int tokenType;
64654 int nTotal = 0;
64655 int n;
64657 *pnToken = 0;
64658 while( zSql[0] ){
64659 n = sqlite3GetToken((u8*)zSql, &tokenType);
64660 assert( n>0 && tokenType!=TK_ILLEGAL );
64661 if( tokenType==TK_VARIABLE ){
64662 *pnToken = n;
64663 break;
64665 nTotal += n;
64666 zSql += n;
64668 return nTotal;
64672 ** This function returns a pointer to a nul-terminated string in memory
64673 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
64674 ** string contains a copy of zRawSql but with host parameters expanded to
64675 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
64676 ** then the returned string holds a copy of zRawSql with "-- " prepended
64677 ** to each line of text.
64679 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
64680 ** then long strings and blobs are truncated to that many bytes. This
64681 ** can be used to prevent unreasonably large trace strings when dealing
64682 ** with large (multi-megabyte) strings and blobs.
64684 ** The calling function is responsible for making sure the memory returned
64685 ** is eventually freed.
64687 ** ALGORITHM: Scan the input string looking for host parameters in any of
64688 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
64689 ** string literals, quoted identifier names, and comments. For text forms,
64690 ** the host parameter index is found by scanning the perpared
64691 ** statement for the corresponding OP_Variable opcode. Once the host
64692 ** parameter index is known, locate the value in p->aVar[]. Then render
64693 ** the value as a literal in place of the host parameter name.
64695 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
64696 Vdbe *p, /* The prepared statement being evaluated */
64697 const char *zRawSql /* Raw text of the SQL statement */
64699 sqlite3 *db; /* The database connection */
64700 int idx = 0; /* Index of a host parameter */
64701 int nextIndex = 1; /* Index of next ? host parameter */
64702 int n; /* Length of a token prefix */
64703 int nToken; /* Length of the parameter token */
64704 int i; /* Loop counter */
64705 Mem *pVar; /* Value of a host parameter */
64706 StrAccum out; /* Accumulate the output here */
64707 char zBase[100]; /* Initial working space */
64709 db = p->db;
64710 sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
64711 db->aLimit[SQLITE_LIMIT_LENGTH]);
64712 out.db = db;
64713 if( db->nVdbeExec>1 ){
64714 while( *zRawSql ){
64715 const char *zStart = zRawSql;
64716 while( *(zRawSql++)!='\n' && *zRawSql );
64717 sqlite3StrAccumAppend(&out, "-- ", 3);
64718 sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
64720 }else{
64721 while( zRawSql[0] ){
64722 n = findNextHostParameter(zRawSql, &nToken);
64723 assert( n>0 );
64724 sqlite3StrAccumAppend(&out, zRawSql, n);
64725 zRawSql += n;
64726 assert( zRawSql[0] || nToken==0 );
64727 if( nToken==0 ) break;
64728 if( zRawSql[0]=='?' ){
64729 if( nToken>1 ){
64730 assert( sqlite3Isdigit(zRawSql[1]) );
64731 sqlite3GetInt32(&zRawSql[1], &idx);
64732 }else{
64733 idx = nextIndex;
64735 }else{
64736 assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
64737 testcase( zRawSql[0]==':' );
64738 testcase( zRawSql[0]=='$' );
64739 testcase( zRawSql[0]=='@' );
64740 idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
64741 assert( idx>0 );
64743 zRawSql += nToken;
64744 nextIndex = idx + 1;
64745 assert( idx>0 && idx<=p->nVar );
64746 pVar = &p->aVar[idx-1];
64747 if( pVar->flags & MEM_Null ){
64748 sqlite3StrAccumAppend(&out, "NULL", 4);
64749 }else if( pVar->flags & MEM_Int ){
64750 sqlite3XPrintf(&out, "%lld", pVar->u.i);
64751 }else if( pVar->flags & MEM_Real ){
64752 sqlite3XPrintf(&out, "%!.15g", pVar->r);
64753 }else if( pVar->flags & MEM_Str ){
64754 int nOut; /* Number of bytes of the string text to include in output */
64755 #ifndef SQLITE_OMIT_UTF16
64756 u8 enc = ENC(db);
64757 Mem utf8;
64758 if( enc!=SQLITE_UTF8 ){
64759 memset(&utf8, 0, sizeof(utf8));
64760 utf8.db = db;
64761 sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
64762 sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
64763 pVar = &utf8;
64765 #endif
64766 nOut = pVar->n;
64767 #ifdef SQLITE_TRACE_SIZE_LIMIT
64768 if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
64769 nOut = SQLITE_TRACE_SIZE_LIMIT;
64770 while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
64772 #endif
64773 sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
64774 #ifdef SQLITE_TRACE_SIZE_LIMIT
64775 if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
64776 #endif
64777 #ifndef SQLITE_OMIT_UTF16
64778 if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
64779 #endif
64780 }else if( pVar->flags & MEM_Zero ){
64781 sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
64782 }else{
64783 int nOut; /* Number of bytes of the blob to include in output */
64784 assert( pVar->flags & MEM_Blob );
64785 sqlite3StrAccumAppend(&out, "x'", 2);
64786 nOut = pVar->n;
64787 #ifdef SQLITE_TRACE_SIZE_LIMIT
64788 if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
64789 #endif
64790 for(i=0; i<nOut; i++){
64791 sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64793 sqlite3StrAccumAppend(&out, "'", 1);
64794 #ifdef SQLITE_TRACE_SIZE_LIMIT
64795 if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
64796 #endif
64800 return sqlite3StrAccumFinish(&out);
64803 #endif /* #ifndef SQLITE_OMIT_TRACE */
64805 /*****************************************************************************
64806 ** The following code implements the data-structure explaining logic
64807 ** for the Vdbe.
64810 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
64813 ** Allocate a new Explain object
64815 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
64816 if( pVdbe ){
64817 Explain *p;
64818 sqlite3BeginBenignMalloc();
64819 p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
64820 if( p ){
64821 p->pVdbe = pVdbe;
64822 sqlite3_free(pVdbe->pExplain);
64823 pVdbe->pExplain = p;
64824 sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
64825 SQLITE_MAX_LENGTH);
64826 p->str.useMalloc = 2;
64827 }else{
64828 sqlite3EndBenignMalloc();
64834 ** Return true if the Explain ends with a new-line.
64836 static int endsWithNL(Explain *p){
64837 return p && p->str.zText && p->str.nChar
64838 && p->str.zText[p->str.nChar-1]=='\n';
64842 ** Append text to the indentation
64844 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
64845 Explain *p;
64846 if( pVdbe && (p = pVdbe->pExplain)!=0 ){
64847 va_list ap;
64848 if( p->nIndent && endsWithNL(p) ){
64849 int n = p->nIndent;
64850 if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
64851 sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
64853 va_start(ap, zFormat);
64854 sqlite3VXPrintf(&p->str, 1, zFormat, ap);
64855 va_end(ap);
64860 ** Append a '\n' if there is not already one.
64862 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
64863 Explain *p;
64864 if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
64865 sqlite3StrAccumAppend(&p->str, "\n", 1);
64870 ** Push a new indentation level. Subsequent lines will be indented
64871 ** so that they begin at the current cursor position.
64873 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
64874 Explain *p;
64875 if( pVdbe && (p = pVdbe->pExplain)!=0 ){
64876 if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
64877 const char *z = p->str.zText;
64878 int i = p->str.nChar-1;
64879 int x;
64880 while( i>=0 && z[i]!='\n' ){ i--; }
64881 x = (p->str.nChar - 1) - i;
64882 if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
64883 x = p->aIndent[p->nIndent-1];
64885 p->aIndent[p->nIndent] = x;
64887 p->nIndent++;
64892 ** Pop the indentation stack by one level.
64894 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
64895 if( p && p->pExplain ) p->pExplain->nIndent--;
64899 ** Free the indentation structure
64901 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
64902 if( pVdbe && pVdbe->pExplain ){
64903 sqlite3_free(pVdbe->zExplain);
64904 sqlite3ExplainNL(pVdbe);
64905 pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
64906 sqlite3_free(pVdbe->pExplain);
64907 pVdbe->pExplain = 0;
64908 sqlite3EndBenignMalloc();
64913 ** Return the explanation of a virtual machine.
64915 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
64916 return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
64918 #endif /* defined(SQLITE_DEBUG) */
64920 /************** End of vdbetrace.c *******************************************/
64921 /************** Begin file vdbe.c ********************************************/
64923 ** 2001 September 15
64925 ** The author disclaims copyright to this source code. In place of
64926 ** a legal notice, here is a blessing:
64928 ** May you do good and not evil.
64929 ** May you find forgiveness for yourself and forgive others.
64930 ** May you share freely, never taking more than you give.
64932 *************************************************************************
64933 ** The code in this file implements execution method of the
64934 ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
64935 ** handles housekeeping details such as creating and deleting
64936 ** VDBE instances. This file is solely interested in executing
64937 ** the VDBE program.
64939 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
64940 ** to a VDBE.
64942 ** The SQL parser generates a program which is then executed by
64943 ** the VDBE to do the work of the SQL statement. VDBE programs are
64944 ** similar in form to assembly language. The program consists of
64945 ** a linear sequence of operations. Each operation has an opcode
64946 ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
64947 ** is a null-terminated string. Operand P5 is an unsigned character.
64948 ** Few opcodes use all 5 operands.
64950 ** Computation results are stored on a set of registers numbered beginning
64951 ** with 1 and going up to Vdbe.nMem. Each register can store
64952 ** either an integer, a null-terminated string, a floating point
64953 ** number, or the SQL "NULL" value. An implicit conversion from one
64954 ** type to the other occurs as necessary.
64956 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
64957 ** function which does the work of interpreting a VDBE program.
64958 ** But other routines are also provided to help in building up
64959 ** a program instruction by instruction.
64961 ** Various scripts scan this source file in order to generate HTML
64962 ** documentation, headers files, or other derived files. The formatting
64963 ** of the code in this file is, therefore, important. See other comments
64964 ** in this file for details. If in doubt, do not deviate from existing
64965 ** commenting and indentation practices when changing or adding code.
64969 ** Invoke this macro on memory cells just prior to changing the
64970 ** value of the cell. This macro verifies that shallow copies are
64971 ** not misused.
64973 #ifdef SQLITE_DEBUG
64974 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
64975 #else
64976 # define memAboutToChange(P,M)
64977 #endif
64980 ** The following global variable is incremented every time a cursor
64981 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
64982 ** procedures use this information to make sure that indices are
64983 ** working correctly. This variable has no function other than to
64984 ** help verify the correct operation of the library.
64986 #ifdef SQLITE_TEST
64987 SQLITE_API int sqlite3_search_count = 0;
64988 #endif
64991 ** When this global variable is positive, it gets decremented once before
64992 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
64993 ** field of the sqlite3 structure is set in order to simulate an interrupt.
64995 ** This facility is used for testing purposes only. It does not function
64996 ** in an ordinary build.
64998 #ifdef SQLITE_TEST
64999 SQLITE_API int sqlite3_interrupt_count = 0;
65000 #endif
65003 ** The next global variable is incremented each type the OP_Sort opcode
65004 ** is executed. The test procedures use this information to make sure that
65005 ** sorting is occurring or not occurring at appropriate times. This variable
65006 ** has no function other than to help verify the correct operation of the
65007 ** library.
65009 #ifdef SQLITE_TEST
65010 SQLITE_API int sqlite3_sort_count = 0;
65011 #endif
65014 ** The next global variable records the size of the largest MEM_Blob
65015 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
65016 ** use this information to make sure that the zero-blob functionality
65017 ** is working correctly. This variable has no function other than to
65018 ** help verify the correct operation of the library.
65020 #ifdef SQLITE_TEST
65021 SQLITE_API int sqlite3_max_blobsize = 0;
65022 static void updateMaxBlobsize(Mem *p){
65023 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
65024 sqlite3_max_blobsize = p->n;
65027 #endif
65030 ** The next global variable is incremented each type the OP_Found opcode
65031 ** is executed. This is used to test whether or not the foreign key
65032 ** operation implemented using OP_FkIsZero is working. This variable
65033 ** has no function other than to help verify the correct operation of the
65034 ** library.
65036 #ifdef SQLITE_TEST
65037 SQLITE_API int sqlite3_found_count = 0;
65038 #endif
65041 ** Test a register to see if it exceeds the current maximum blob size.
65042 ** If it does, record the new maximum blob size.
65044 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
65045 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
65046 #else
65047 # define UPDATE_MAX_BLOBSIZE(P)
65048 #endif
65051 ** Convert the given register into a string if it isn't one
65052 ** already. Return non-zero if a malloc() fails.
65054 #define Stringify(P, enc) \
65055 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
65056 { goto no_mem; }
65059 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
65060 ** a pointer to a dynamically allocated string where some other entity
65061 ** is responsible for deallocating that string. Because the register
65062 ** does not control the string, it might be deleted without the register
65063 ** knowing it.
65065 ** This routine converts an ephemeral string into a dynamically allocated
65066 ** string that the register itself controls. In other words, it
65067 ** converts an MEM_Ephem string into an MEM_Dyn string.
65069 #define Deephemeralize(P) \
65070 if( ((P)->flags&MEM_Ephem)!=0 \
65071 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
65073 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
65074 # define isSorter(x) ((x)->pSorter!=0)
65077 ** Argument pMem points at a register that will be passed to a
65078 ** user-defined function or returned to the user as the result of a query.
65079 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
65080 ** routines.
65082 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
65083 int flags = pMem->flags;
65084 if( flags & MEM_Null ){
65085 pMem->type = SQLITE_NULL;
65087 else if( flags & MEM_Int ){
65088 pMem->type = SQLITE_INTEGER;
65090 else if( flags & MEM_Real ){
65091 pMem->type = SQLITE_FLOAT;
65093 else if( flags & MEM_Str ){
65094 pMem->type = SQLITE_TEXT;
65095 }else{
65096 pMem->type = SQLITE_BLOB;
65101 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
65102 ** if we run out of memory.
65104 static VdbeCursor *allocateCursor(
65105 Vdbe *p, /* The virtual machine */
65106 int iCur, /* Index of the new VdbeCursor */
65107 int nField, /* Number of fields in the table or index */
65108 int iDb, /* Database the cursor belongs to, or -1 */
65109 int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
65111 /* Find the memory cell that will be used to store the blob of memory
65112 ** required for this VdbeCursor structure. It is convenient to use a
65113 ** vdbe memory cell to manage the memory allocation required for a
65114 ** VdbeCursor structure for the following reasons:
65116 ** * Sometimes cursor numbers are used for a couple of different
65117 ** purposes in a vdbe program. The different uses might require
65118 ** different sized allocations. Memory cells provide growable
65119 ** allocations.
65121 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
65122 ** be freed lazily via the sqlite3_release_memory() API. This
65123 ** minimizes the number of malloc calls made by the system.
65125 ** Memory cells for cursors are allocated at the top of the address
65126 ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
65127 ** cursor 1 is managed by memory cell (p->nMem-1), etc.
65129 Mem *pMem = &p->aMem[p->nMem-iCur];
65131 int nByte;
65132 VdbeCursor *pCx = 0;
65133 nByte =
65134 ROUND8(sizeof(VdbeCursor)) +
65135 (isBtreeCursor?sqlite3BtreeCursorSize():0) +
65136 2*nField*sizeof(u32);
65138 assert( iCur<p->nCursor );
65139 if( p->apCsr[iCur] ){
65140 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
65141 p->apCsr[iCur] = 0;
65143 if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
65144 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
65145 memset(pCx, 0, sizeof(VdbeCursor));
65146 pCx->iDb = iDb;
65147 pCx->nField = nField;
65148 if( nField ){
65149 pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
65151 if( isBtreeCursor ){
65152 pCx->pCursor = (BtCursor*)
65153 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
65154 sqlite3BtreeCursorZero(pCx->pCursor);
65157 return pCx;
65161 ** Try to convert a value into a numeric representation if we can
65162 ** do so without loss of information. In other words, if the string
65163 ** looks like a number, convert it into a number. If it does not
65164 ** look like a number, leave it alone.
65166 static void applyNumericAffinity(Mem *pRec){
65167 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
65168 double rValue;
65169 i64 iValue;
65170 u8 enc = pRec->enc;
65171 if( (pRec->flags&MEM_Str)==0 ) return;
65172 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
65173 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
65174 pRec->u.i = iValue;
65175 pRec->flags |= MEM_Int;
65176 }else{
65177 pRec->r = rValue;
65178 pRec->flags |= MEM_Real;
65184 ** Processing is determine by the affinity parameter:
65186 ** SQLITE_AFF_INTEGER:
65187 ** SQLITE_AFF_REAL:
65188 ** SQLITE_AFF_NUMERIC:
65189 ** Try to convert pRec to an integer representation or a
65190 ** floating-point representation if an integer representation
65191 ** is not possible. Note that the integer representation is
65192 ** always preferred, even if the affinity is REAL, because
65193 ** an integer representation is more space efficient on disk.
65195 ** SQLITE_AFF_TEXT:
65196 ** Convert pRec to a text representation.
65198 ** SQLITE_AFF_NONE:
65199 ** No-op. pRec is unchanged.
65201 static void applyAffinity(
65202 Mem *pRec, /* The value to apply affinity to */
65203 char affinity, /* The affinity to be applied */
65204 u8 enc /* Use this text encoding */
65206 if( affinity==SQLITE_AFF_TEXT ){
65207 /* Only attempt the conversion to TEXT if there is an integer or real
65208 ** representation (blob and NULL do not get converted) but no string
65209 ** representation.
65211 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
65212 sqlite3VdbeMemStringify(pRec, enc);
65214 pRec->flags &= ~(MEM_Real|MEM_Int);
65215 }else if( affinity!=SQLITE_AFF_NONE ){
65216 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
65217 || affinity==SQLITE_AFF_NUMERIC );
65218 applyNumericAffinity(pRec);
65219 if( pRec->flags & MEM_Real ){
65220 sqlite3VdbeIntegerAffinity(pRec);
65226 ** Try to convert the type of a function argument or a result column
65227 ** into a numeric representation. Use either INTEGER or REAL whichever
65228 ** is appropriate. But only do the conversion if it is possible without
65229 ** loss of information and return the revised type of the argument.
65231 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
65232 Mem *pMem = (Mem*)pVal;
65233 if( pMem->type==SQLITE_TEXT ){
65234 applyNumericAffinity(pMem);
65235 sqlite3VdbeMemStoreType(pMem);
65237 return pMem->type;
65241 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
65242 ** not the internal Mem* type.
65244 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
65245 sqlite3_value *pVal,
65246 u8 affinity,
65247 u8 enc
65249 applyAffinity((Mem *)pVal, affinity, enc);
65252 #ifdef SQLITE_DEBUG
65254 ** Write a nice string representation of the contents of cell pMem
65255 ** into buffer zBuf, length nBuf.
65257 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
65258 char *zCsr = zBuf;
65259 int f = pMem->flags;
65261 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
65263 if( f&MEM_Blob ){
65264 int i;
65265 char c;
65266 if( f & MEM_Dyn ){
65267 c = 'z';
65268 assert( (f & (MEM_Static|MEM_Ephem))==0 );
65269 }else if( f & MEM_Static ){
65270 c = 't';
65271 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
65272 }else if( f & MEM_Ephem ){
65273 c = 'e';
65274 assert( (f & (MEM_Static|MEM_Dyn))==0 );
65275 }else{
65276 c = 's';
65279 sqlite3_snprintf(100, zCsr, "%c", c);
65280 zCsr += sqlite3Strlen30(zCsr);
65281 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
65282 zCsr += sqlite3Strlen30(zCsr);
65283 for(i=0; i<16 && i<pMem->n; i++){
65284 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
65285 zCsr += sqlite3Strlen30(zCsr);
65287 for(i=0; i<16 && i<pMem->n; i++){
65288 char z = pMem->z[i];
65289 if( z<32 || z>126 ) *zCsr++ = '.';
65290 else *zCsr++ = z;
65293 sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
65294 zCsr += sqlite3Strlen30(zCsr);
65295 if( f & MEM_Zero ){
65296 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
65297 zCsr += sqlite3Strlen30(zCsr);
65299 *zCsr = '\0';
65300 }else if( f & MEM_Str ){
65301 int j, k;
65302 zBuf[0] = ' ';
65303 if( f & MEM_Dyn ){
65304 zBuf[1] = 'z';
65305 assert( (f & (MEM_Static|MEM_Ephem))==0 );
65306 }else if( f & MEM_Static ){
65307 zBuf[1] = 't';
65308 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
65309 }else if( f & MEM_Ephem ){
65310 zBuf[1] = 'e';
65311 assert( (f & (MEM_Static|MEM_Dyn))==0 );
65312 }else{
65313 zBuf[1] = 's';
65315 k = 2;
65316 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
65317 k += sqlite3Strlen30(&zBuf[k]);
65318 zBuf[k++] = '[';
65319 for(j=0; j<15 && j<pMem->n; j++){
65320 u8 c = pMem->z[j];
65321 if( c>=0x20 && c<0x7f ){
65322 zBuf[k++] = c;
65323 }else{
65324 zBuf[k++] = '.';
65327 zBuf[k++] = ']';
65328 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
65329 k += sqlite3Strlen30(&zBuf[k]);
65330 zBuf[k++] = 0;
65333 #endif
65335 #ifdef SQLITE_DEBUG
65337 ** Print the value of a register for tracing purposes:
65339 static void memTracePrint(FILE *out, Mem *p){
65340 if( p->flags & MEM_Invalid ){
65341 fprintf(out, " undefined");
65342 }else if( p->flags & MEM_Null ){
65343 fprintf(out, " NULL");
65344 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
65345 fprintf(out, " si:%lld", p->u.i);
65346 }else if( p->flags & MEM_Int ){
65347 fprintf(out, " i:%lld", p->u.i);
65348 #ifndef SQLITE_OMIT_FLOATING_POINT
65349 }else if( p->flags & MEM_Real ){
65350 fprintf(out, " r:%g", p->r);
65351 #endif
65352 }else if( p->flags & MEM_RowSet ){
65353 fprintf(out, " (rowset)");
65354 }else{
65355 char zBuf[200];
65356 sqlite3VdbeMemPrettyPrint(p, zBuf);
65357 fprintf(out, " ");
65358 fprintf(out, "%s", zBuf);
65361 static void registerTrace(FILE *out, int iReg, Mem *p){
65362 fprintf(out, "REG[%d] = ", iReg);
65363 memTracePrint(out, p);
65364 fprintf(out, "\n");
65366 #endif
65368 #ifdef SQLITE_DEBUG
65369 # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
65370 #else
65371 # define REGISTER_TRACE(R,M)
65372 #endif
65375 #ifdef VDBE_PROFILE
65378 ** hwtime.h contains inline assembler code for implementing
65379 ** high-performance timing routines.
65381 /************** Include hwtime.h in the middle of vdbe.c *********************/
65382 /************** Begin file hwtime.h ******************************************/
65384 ** 2008 May 27
65386 ** The author disclaims copyright to this source code. In place of
65387 ** a legal notice, here is a blessing:
65389 ** May you do good and not evil.
65390 ** May you find forgiveness for yourself and forgive others.
65391 ** May you share freely, never taking more than you give.
65393 ******************************************************************************
65395 ** This file contains inline asm code for retrieving "high-performance"
65396 ** counters for x86 class CPUs.
65398 #ifndef _HWTIME_H_
65399 #define _HWTIME_H_
65402 ** The following routine only works on pentium-class (or newer) processors.
65403 ** It uses the RDTSC opcode to read the cycle count value out of the
65404 ** processor and returns that value. This can be used for high-res
65405 ** profiling.
65407 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
65408 (defined(i386) || defined(__i386__) || defined(_M_IX86))
65410 #if defined(__GNUC__)
65412 __inline__ sqlite_uint64 sqlite3Hwtime(void){
65413 unsigned int lo, hi;
65414 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
65415 return (sqlite_uint64)hi << 32 | lo;
65418 #elif defined(_MSC_VER)
65420 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
65421 __asm {
65422 rdtsc
65423 ret ; return value at EDX:EAX
65427 #endif
65429 #elif (defined(__GNUC__) && defined(__x86_64__))
65431 __inline__ sqlite_uint64 sqlite3Hwtime(void){
65432 unsigned long val;
65433 __asm__ __volatile__ ("rdtsc" : "=A" (val));
65434 return val;
65437 #elif (defined(__GNUC__) && defined(__ppc__))
65439 __inline__ sqlite_uint64 sqlite3Hwtime(void){
65440 unsigned long long retval;
65441 unsigned long junk;
65442 __asm__ __volatile__ ("\n\
65443 1: mftbu %1\n\
65444 mftb %L0\n\
65445 mftbu %0\n\
65446 cmpw %0,%1\n\
65447 bne 1b"
65448 : "=r" (retval), "=r" (junk));
65449 return retval;
65452 #else
65454 #error Need implementation of sqlite3Hwtime() for your platform.
65457 ** To compile without implementing sqlite3Hwtime() for your platform,
65458 ** you can remove the above #error and use the following
65459 ** stub function. You will lose timing support for many
65460 ** of the debugging and testing utilities, but it should at
65461 ** least compile and run.
65463 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
65465 #endif
65467 #endif /* !defined(_HWTIME_H_) */
65469 /************** End of hwtime.h **********************************************/
65470 /************** Continuing where we left off in vdbe.c ***********************/
65472 #endif
65475 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
65476 ** sqlite3_interrupt() routine has been called. If it has been, then
65477 ** processing of the VDBE program is interrupted.
65479 ** This macro added to every instruction that does a jump in order to
65480 ** implement a loop. This test used to be on every single instruction,
65481 ** but that meant we more testing than we needed. By only testing the
65482 ** flag on jump instructions, we get a (small) speed improvement.
65484 #define CHECK_FOR_INTERRUPT \
65485 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
65488 #ifndef NDEBUG
65490 ** This function is only called from within an assert() expression. It
65491 ** checks that the sqlite3.nTransaction variable is correctly set to
65492 ** the number of non-transaction savepoints currently in the
65493 ** linked list starting at sqlite3.pSavepoint.
65495 ** Usage:
65497 ** assert( checkSavepointCount(db) );
65499 static int checkSavepointCount(sqlite3 *db){
65500 int n = 0;
65501 Savepoint *p;
65502 for(p=db->pSavepoint; p; p=p->pNext) n++;
65503 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
65504 return 1;
65506 #endif
65510 ** Execute as much of a VDBE program as we can then return.
65512 ** sqlite3VdbeMakeReady() must be called before this routine in order to
65513 ** close the program with a final OP_Halt and to set up the callbacks
65514 ** and the error message pointer.
65516 ** Whenever a row or result data is available, this routine will either
65517 ** invoke the result callback (if there is one) or return with
65518 ** SQLITE_ROW.
65520 ** If an attempt is made to open a locked database, then this routine
65521 ** will either invoke the busy callback (if there is one) or it will
65522 ** return SQLITE_BUSY.
65524 ** If an error occurs, an error message is written to memory obtained
65525 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
65526 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
65528 ** If the callback ever returns non-zero, then the program exits
65529 ** immediately. There will be no error message but the p->rc field is
65530 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
65532 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
65533 ** routine to return SQLITE_ERROR.
65535 ** Other fatal errors return SQLITE_ERROR.
65537 ** After this routine has finished, sqlite3VdbeFinalize() should be
65538 ** used to clean up the mess that was left behind.
65540 SQLITE_PRIVATE int sqlite3VdbeExec(
65541 Vdbe *p /* The VDBE */
65543 int pc=0; /* The program counter */
65544 Op *aOp = p->aOp; /* Copy of p->aOp */
65545 Op *pOp; /* Current operation */
65546 int rc = SQLITE_OK; /* Value to return */
65547 sqlite3 *db = p->db; /* The database */
65548 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
65549 u8 encoding = ENC(db); /* The database encoding */
65550 int iCompare = 0; /* Result of last OP_Compare operation */
65551 unsigned nVmStep = 0; /* Number of virtual machine steps */
65552 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65553 unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
65554 #endif
65555 Mem *aMem = p->aMem; /* Copy of p->aMem */
65556 Mem *pIn1 = 0; /* 1st input operand */
65557 Mem *pIn2 = 0; /* 2nd input operand */
65558 Mem *pIn3 = 0; /* 3rd input operand */
65559 Mem *pOut = 0; /* Output operand */
65560 int *aPermute = 0; /* Permutation of columns for OP_Compare */
65561 i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
65562 #ifdef VDBE_PROFILE
65563 u64 start; /* CPU clock count at start of opcode */
65564 int origPc; /* Program counter at start of opcode */
65565 #endif
65566 /********************************************************************
65567 ** Automatically generated code
65569 ** The following union is automatically generated by the
65570 ** vdbe-compress.tcl script. The purpose of this union is to
65571 ** reduce the amount of stack space required by this function.
65572 ** See comments in the vdbe-compress.tcl script for details.
65574 union vdbeExecUnion {
65575 struct OP_Yield_stack_vars {
65576 int pcDest;
65577 } aa;
65578 struct OP_Null_stack_vars {
65579 int cnt;
65580 u16 nullFlag;
65581 } ab;
65582 struct OP_Variable_stack_vars {
65583 Mem *pVar; /* Value being transferred */
65584 } ac;
65585 struct OP_Move_stack_vars {
65586 char *zMalloc; /* Holding variable for allocated memory */
65587 int n; /* Number of registers left to copy */
65588 int p1; /* Register to copy from */
65589 int p2; /* Register to copy to */
65590 } ad;
65591 struct OP_Copy_stack_vars {
65592 int n;
65593 } ae;
65594 struct OP_ResultRow_stack_vars {
65595 Mem *pMem;
65596 int i;
65597 } af;
65598 struct OP_Concat_stack_vars {
65599 i64 nByte;
65600 } ag;
65601 struct OP_Remainder_stack_vars {
65602 char bIntint; /* Started out as two integer operands */
65603 int flags; /* Combined MEM_* flags from both inputs */
65604 i64 iA; /* Integer value of left operand */
65605 i64 iB; /* Integer value of right operand */
65606 double rA; /* Real value of left operand */
65607 double rB; /* Real value of right operand */
65608 } ah;
65609 struct OP_Function_stack_vars {
65610 int i;
65611 Mem *pArg;
65612 sqlite3_context ctx;
65613 sqlite3_value **apVal;
65614 int n;
65615 } ai;
65616 struct OP_ShiftRight_stack_vars {
65617 i64 iA;
65618 u64 uA;
65619 i64 iB;
65620 u8 op;
65621 } aj;
65622 struct OP_Ge_stack_vars {
65623 int res; /* Result of the comparison of pIn1 against pIn3 */
65624 char affinity; /* Affinity to use for comparison */
65625 u16 flags1; /* Copy of initial value of pIn1->flags */
65626 u16 flags3; /* Copy of initial value of pIn3->flags */
65627 } ak;
65628 struct OP_Compare_stack_vars {
65629 int n;
65630 int i;
65631 int p1;
65632 int p2;
65633 const KeyInfo *pKeyInfo;
65634 int idx;
65635 CollSeq *pColl; /* Collating sequence to use on this term */
65636 int bRev; /* True for DESCENDING sort order */
65637 } al;
65638 struct OP_Or_stack_vars {
65639 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65640 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65641 } am;
65642 struct OP_IfNot_stack_vars {
65643 int c;
65644 } an;
65645 struct OP_Column_stack_vars {
65646 u32 payloadSize; /* Number of bytes in the record */
65647 i64 payloadSize64; /* Number of bytes in the record */
65648 int p1; /* P1 value of the opcode */
65649 int p2; /* column number to retrieve */
65650 VdbeCursor *pC; /* The VDBE cursor */
65651 char *zRec; /* Pointer to complete record-data */
65652 BtCursor *pCrsr; /* The BTree cursor */
65653 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
65654 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
65655 int nField; /* number of fields in the record */
65656 int len; /* The length of the serialized data for the column */
65657 int i; /* Loop counter */
65658 char *zData; /* Part of the record being decoded */
65659 Mem *pDest; /* Where to write the extracted value */
65660 Mem sMem; /* For storing the record being decoded */
65661 u8 *zIdx; /* Index into header */
65662 u8 *zEndHdr; /* Pointer to first byte after the header */
65663 u32 offset; /* Offset into the data */
65664 u32 szField; /* Number of bytes in the content of a field */
65665 int szHdr; /* Size of the header size field at start of record */
65666 int avail; /* Number of bytes of available data */
65667 u32 t; /* A type code from the record header */
65668 Mem *pReg; /* PseudoTable input register */
65669 } ao;
65670 struct OP_Affinity_stack_vars {
65671 const char *zAffinity; /* The affinity to be applied */
65672 char cAff; /* A single character of affinity */
65673 } ap;
65674 struct OP_MakeRecord_stack_vars {
65675 u8 *zNewRecord; /* A buffer to hold the data for the new record */
65676 Mem *pRec; /* The new record */
65677 u64 nData; /* Number of bytes of data space */
65678 int nHdr; /* Number of bytes of header space */
65679 i64 nByte; /* Data space required for this record */
65680 int nZero; /* Number of zero bytes at the end of the record */
65681 int nVarint; /* Number of bytes in a varint */
65682 u32 serial_type; /* Type field */
65683 Mem *pData0; /* First field to be combined into the record */
65684 Mem *pLast; /* Last field of the record */
65685 int nField; /* Number of fields in the record */
65686 char *zAffinity; /* The affinity string for the record */
65687 int file_format; /* File format to use for encoding */
65688 int i; /* Space used in zNewRecord[] */
65689 int len; /* Length of a field */
65690 } aq;
65691 struct OP_Count_stack_vars {
65692 i64 nEntry;
65693 BtCursor *pCrsr;
65694 } ar;
65695 struct OP_Savepoint_stack_vars {
65696 int p1; /* Value of P1 operand */
65697 char *zName; /* Name of savepoint */
65698 int nName;
65699 Savepoint *pNew;
65700 Savepoint *pSavepoint;
65701 Savepoint *pTmp;
65702 int iSavepoint;
65703 int ii;
65704 } as;
65705 struct OP_AutoCommit_stack_vars {
65706 int desiredAutoCommit;
65707 int iRollback;
65708 int turnOnAC;
65709 } at;
65710 struct OP_Transaction_stack_vars {
65711 Btree *pBt;
65712 } au;
65713 struct OP_ReadCookie_stack_vars {
65714 int iMeta;
65715 int iDb;
65716 int iCookie;
65717 } av;
65718 struct OP_SetCookie_stack_vars {
65719 Db *pDb;
65720 } aw;
65721 struct OP_VerifyCookie_stack_vars {
65722 int iMeta;
65723 int iGen;
65724 Btree *pBt;
65725 } ax;
65726 struct OP_OpenWrite_stack_vars {
65727 int nField;
65728 KeyInfo *pKeyInfo;
65729 int p2;
65730 int iDb;
65731 int wrFlag;
65732 Btree *pX;
65733 VdbeCursor *pCur;
65734 Db *pDb;
65735 } ay;
65736 struct OP_OpenEphemeral_stack_vars {
65737 VdbeCursor *pCx;
65738 } az;
65739 struct OP_SorterOpen_stack_vars {
65740 VdbeCursor *pCx;
65741 } ba;
65742 struct OP_OpenPseudo_stack_vars {
65743 VdbeCursor *pCx;
65744 } bb;
65745 struct OP_SeekGt_stack_vars {
65746 int res;
65747 int oc;
65748 VdbeCursor *pC;
65749 UnpackedRecord r;
65750 int nField;
65751 i64 iKey; /* The rowid we are to seek to */
65752 } bc;
65753 struct OP_Seek_stack_vars {
65754 VdbeCursor *pC;
65755 } bd;
65756 struct OP_Found_stack_vars {
65757 int alreadyExists;
65758 VdbeCursor *pC;
65759 int res;
65760 char *pFree;
65761 UnpackedRecord *pIdxKey;
65762 UnpackedRecord r;
65763 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65764 } be;
65765 struct OP_IsUnique_stack_vars {
65766 u16 ii;
65767 VdbeCursor *pCx;
65768 BtCursor *pCrsr;
65769 u16 nField;
65770 Mem *aMx;
65771 UnpackedRecord r; /* B-Tree index search key */
65772 i64 R; /* Rowid stored in register P3 */
65773 } bf;
65774 struct OP_NotExists_stack_vars {
65775 VdbeCursor *pC;
65776 BtCursor *pCrsr;
65777 int res;
65778 u64 iKey;
65779 } bg;
65780 struct OP_NewRowid_stack_vars {
65781 i64 v; /* The new rowid */
65782 VdbeCursor *pC; /* Cursor of table to get the new rowid */
65783 int res; /* Result of an sqlite3BtreeLast() */
65784 int cnt; /* Counter to limit the number of searches */
65785 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
65786 VdbeFrame *pFrame; /* Root frame of VDBE */
65787 } bh;
65788 struct OP_InsertInt_stack_vars {
65789 Mem *pData; /* MEM cell holding data for the record to be inserted */
65790 Mem *pKey; /* MEM cell holding key for the record */
65791 i64 iKey; /* The integer ROWID or key for the record to be inserted */
65792 VdbeCursor *pC; /* Cursor to table into which insert is written */
65793 int nZero; /* Number of zero-bytes to append */
65794 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
65795 const char *zDb; /* database name - used by the update hook */
65796 const char *zTbl; /* Table name - used by the opdate hook */
65797 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
65798 } bi;
65799 struct OP_Delete_stack_vars {
65800 i64 iKey;
65801 VdbeCursor *pC;
65802 } bj;
65803 struct OP_SorterCompare_stack_vars {
65804 VdbeCursor *pC;
65805 int res;
65806 } bk;
65807 struct OP_SorterData_stack_vars {
65808 VdbeCursor *pC;
65809 } bl;
65810 struct OP_RowData_stack_vars {
65811 VdbeCursor *pC;
65812 BtCursor *pCrsr;
65813 u32 n;
65814 i64 n64;
65815 } bm;
65816 struct OP_Rowid_stack_vars {
65817 VdbeCursor *pC;
65818 i64 v;
65819 sqlite3_vtab *pVtab;
65820 const sqlite3_module *pModule;
65821 } bn;
65822 struct OP_NullRow_stack_vars {
65823 VdbeCursor *pC;
65824 } bo;
65825 struct OP_Last_stack_vars {
65826 VdbeCursor *pC;
65827 BtCursor *pCrsr;
65828 int res;
65829 } bp;
65830 struct OP_Rewind_stack_vars {
65831 VdbeCursor *pC;
65832 BtCursor *pCrsr;
65833 int res;
65834 } bq;
65835 struct OP_Next_stack_vars {
65836 VdbeCursor *pC;
65837 int res;
65838 } br;
65839 struct OP_IdxInsert_stack_vars {
65840 VdbeCursor *pC;
65841 BtCursor *pCrsr;
65842 int nKey;
65843 const char *zKey;
65844 } bs;
65845 struct OP_IdxDelete_stack_vars {
65846 VdbeCursor *pC;
65847 BtCursor *pCrsr;
65848 int res;
65849 UnpackedRecord r;
65850 } bt;
65851 struct OP_IdxRowid_stack_vars {
65852 BtCursor *pCrsr;
65853 VdbeCursor *pC;
65854 i64 rowid;
65855 } bu;
65856 struct OP_IdxGE_stack_vars {
65857 VdbeCursor *pC;
65858 int res;
65859 UnpackedRecord r;
65860 } bv;
65861 struct OP_Destroy_stack_vars {
65862 int iMoved;
65863 int iCnt;
65864 Vdbe *pVdbe;
65865 int iDb;
65866 } bw;
65867 struct OP_Clear_stack_vars {
65868 int nChange;
65869 } bx;
65870 struct OP_CreateTable_stack_vars {
65871 int pgno;
65872 int flags;
65873 Db *pDb;
65874 } by;
65875 struct OP_ParseSchema_stack_vars {
65876 int iDb;
65877 const char *zMaster;
65878 char *zSql;
65879 InitData initData;
65880 } bz;
65881 struct OP_IntegrityCk_stack_vars {
65882 int nRoot; /* Number of tables to check. (Number of root pages.) */
65883 int *aRoot; /* Array of rootpage numbers for tables to be checked */
65884 int j; /* Loop counter */
65885 int nErr; /* Number of errors reported */
65886 char *z; /* Text of the error report */
65887 Mem *pnErr; /* Register keeping track of errors remaining */
65888 } ca;
65889 struct OP_RowSetRead_stack_vars {
65890 i64 val;
65891 } cb;
65892 struct OP_RowSetTest_stack_vars {
65893 int iSet;
65894 int exists;
65895 } cc;
65896 struct OP_Program_stack_vars {
65897 int nMem; /* Number of memory registers for sub-program */
65898 int nByte; /* Bytes of runtime space required for sub-program */
65899 Mem *pRt; /* Register to allocate runtime space */
65900 Mem *pMem; /* Used to iterate through memory cells */
65901 Mem *pEnd; /* Last memory cell in new array */
65902 VdbeFrame *pFrame; /* New vdbe frame to execute in */
65903 SubProgram *pProgram; /* Sub-program to execute */
65904 void *t; /* Token identifying trigger */
65905 } cd;
65906 struct OP_Param_stack_vars {
65907 VdbeFrame *pFrame;
65908 Mem *pIn;
65909 } ce;
65910 struct OP_MemMax_stack_vars {
65911 Mem *pIn1;
65912 VdbeFrame *pFrame;
65913 } cf;
65914 struct OP_AggStep_stack_vars {
65915 int n;
65916 int i;
65917 Mem *pMem;
65918 Mem *pRec;
65919 sqlite3_context ctx;
65920 sqlite3_value **apVal;
65921 } cg;
65922 struct OP_AggFinal_stack_vars {
65923 Mem *pMem;
65924 } ch;
65925 struct OP_Checkpoint_stack_vars {
65926 int i; /* Loop counter */
65927 int aRes[3]; /* Results */
65928 Mem *pMem; /* Write results here */
65929 } ci;
65930 struct OP_JournalMode_stack_vars {
65931 Btree *pBt; /* Btree to change journal mode of */
65932 Pager *pPager; /* Pager associated with pBt */
65933 int eNew; /* New journal mode */
65934 int eOld; /* The old journal mode */
65935 #ifndef SQLITE_OMIT_WAL
65936 const char *zFilename; /* Name of database file for pPager */
65937 #endif
65938 } cj;
65939 struct OP_IncrVacuum_stack_vars {
65940 Btree *pBt;
65941 } ck;
65942 struct OP_VBegin_stack_vars {
65943 VTable *pVTab;
65944 } cl;
65945 struct OP_VOpen_stack_vars {
65946 VdbeCursor *pCur;
65947 sqlite3_vtab_cursor *pVtabCursor;
65948 sqlite3_vtab *pVtab;
65949 sqlite3_module *pModule;
65950 } cm;
65951 struct OP_VFilter_stack_vars {
65952 int nArg;
65953 int iQuery;
65954 const sqlite3_module *pModule;
65955 Mem *pQuery;
65956 Mem *pArgc;
65957 sqlite3_vtab_cursor *pVtabCursor;
65958 sqlite3_vtab *pVtab;
65959 VdbeCursor *pCur;
65960 int res;
65961 int i;
65962 Mem **apArg;
65963 } cn;
65964 struct OP_VColumn_stack_vars {
65965 sqlite3_vtab *pVtab;
65966 const sqlite3_module *pModule;
65967 Mem *pDest;
65968 sqlite3_context sContext;
65969 } co;
65970 struct OP_VNext_stack_vars {
65971 sqlite3_vtab *pVtab;
65972 const sqlite3_module *pModule;
65973 int res;
65974 VdbeCursor *pCur;
65975 } cp;
65976 struct OP_VRename_stack_vars {
65977 sqlite3_vtab *pVtab;
65978 Mem *pName;
65979 } cq;
65980 struct OP_VUpdate_stack_vars {
65981 sqlite3_vtab *pVtab;
65982 sqlite3_module *pModule;
65983 int nArg;
65984 int i;
65985 sqlite_int64 rowid;
65986 Mem **apArg;
65987 Mem *pX;
65988 } cr;
65989 struct OP_Trace_stack_vars {
65990 char *zTrace;
65991 char *z;
65992 } cs;
65993 } u;
65994 /* End automatically generated code
65995 ********************************************************************/
65997 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
65998 sqlite3VdbeEnter(p);
65999 if( p->rc==SQLITE_NOMEM ){
66000 /* This happens if a malloc() inside a call to sqlite3_column_text() or
66001 ** sqlite3_column_text16() failed. */
66002 goto no_mem;
66004 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
66005 assert( p->bIsReader || p->readOnly!=0 );
66006 p->rc = SQLITE_OK;
66007 assert( p->explain==0 );
66008 p->pResultSet = 0;
66009 db->busyHandler.nBusy = 0;
66010 CHECK_FOR_INTERRUPT;
66011 sqlite3VdbeIOTraceSql(p);
66012 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
66013 if( db->xProgress ){
66014 assert( 0 < db->nProgressOps );
66015 nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
66016 if( nProgressLimit==0 ){
66017 nProgressLimit = db->nProgressOps;
66018 }else{
66019 nProgressLimit %= (unsigned)db->nProgressOps;
66022 #endif
66023 #ifdef SQLITE_DEBUG
66024 sqlite3BeginBenignMalloc();
66025 if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
66026 int i;
66027 printf("VDBE Program Listing:\n");
66028 sqlite3VdbePrintSql(p);
66029 for(i=0; i<p->nOp; i++){
66030 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
66033 sqlite3EndBenignMalloc();
66034 #endif
66035 for(pc=p->pc; rc==SQLITE_OK; pc++){
66036 assert( pc>=0 && pc<p->nOp );
66037 if( db->mallocFailed ) goto no_mem;
66038 #ifdef VDBE_PROFILE
66039 origPc = pc;
66040 start = sqlite3Hwtime();
66041 #endif
66042 nVmStep++;
66043 pOp = &aOp[pc];
66045 /* Only allow tracing if SQLITE_DEBUG is defined.
66047 #ifdef SQLITE_DEBUG
66048 if( p->trace ){
66049 if( pc==0 ){
66050 printf("VDBE Execution Trace:\n");
66051 sqlite3VdbePrintSql(p);
66053 sqlite3VdbePrintOp(p->trace, pc, pOp);
66055 #endif
66058 /* Check to see if we need to simulate an interrupt. This only happens
66059 ** if we have a special test build.
66061 #ifdef SQLITE_TEST
66062 if( sqlite3_interrupt_count>0 ){
66063 sqlite3_interrupt_count--;
66064 if( sqlite3_interrupt_count==0 ){
66065 sqlite3_interrupt(db);
66068 #endif
66070 /* On any opcode with the "out2-prerelease" tag, free any
66071 ** external allocations out of mem[p2] and set mem[p2] to be
66072 ** an undefined integer. Opcodes will either fill in the integer
66073 ** value or convert mem[p2] to a different type.
66075 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
66076 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
66077 assert( pOp->p2>0 );
66078 assert( pOp->p2<=p->nMem );
66079 pOut = &aMem[pOp->p2];
66080 memAboutToChange(p, pOut);
66081 VdbeMemRelease(pOut);
66082 pOut->flags = MEM_Int;
66085 /* Sanity checking on other operands */
66086 #ifdef SQLITE_DEBUG
66087 if( (pOp->opflags & OPFLG_IN1)!=0 ){
66088 assert( pOp->p1>0 );
66089 assert( pOp->p1<=p->nMem );
66090 assert( memIsValid(&aMem[pOp->p1]) );
66091 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
66093 if( (pOp->opflags & OPFLG_IN2)!=0 ){
66094 assert( pOp->p2>0 );
66095 assert( pOp->p2<=p->nMem );
66096 assert( memIsValid(&aMem[pOp->p2]) );
66097 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
66099 if( (pOp->opflags & OPFLG_IN3)!=0 ){
66100 assert( pOp->p3>0 );
66101 assert( pOp->p3<=p->nMem );
66102 assert( memIsValid(&aMem[pOp->p3]) );
66103 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
66105 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
66106 assert( pOp->p2>0 );
66107 assert( pOp->p2<=p->nMem );
66108 memAboutToChange(p, &aMem[pOp->p2]);
66110 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
66111 assert( pOp->p3>0 );
66112 assert( pOp->p3<=p->nMem );
66113 memAboutToChange(p, &aMem[pOp->p3]);
66115 #endif
66117 switch( pOp->opcode ){
66119 /*****************************************************************************
66120 ** What follows is a massive switch statement where each case implements a
66121 ** separate instruction in the virtual machine. If we follow the usual
66122 ** indentation conventions, each case should be indented by 6 spaces. But
66123 ** that is a lot of wasted space on the left margin. So the code within
66124 ** the switch statement will break with convention and be flush-left. Another
66125 ** big comment (similar to this one) will mark the point in the code where
66126 ** we transition back to normal indentation.
66128 ** The formatting of each case is important. The makefile for SQLite
66129 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
66130 ** file looking for lines that begin with "case OP_". The opcodes.h files
66131 ** will be filled with #defines that give unique integer values to each
66132 ** opcode and the opcodes.c file is filled with an array of strings where
66133 ** each string is the symbolic name for the corresponding opcode. If the
66134 ** case statement is followed by a comment of the form "/# same as ... #/"
66135 ** that comment is used to determine the particular value of the opcode.
66137 ** Other keywords in the comment that follows each case are used to
66138 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
66139 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
66140 ** the mkopcodeh.awk script for additional information.
66142 ** Documentation about VDBE opcodes is generated by scanning this file
66143 ** for lines of that contain "Opcode:". That line and all subsequent
66144 ** comment lines are used in the generation of the opcode.html documentation
66145 ** file.
66147 ** SUMMARY:
66149 ** Formatting is important to scripts that scan this file.
66150 ** Do not deviate from the formatting style currently in use.
66152 *****************************************************************************/
66154 /* Opcode: Goto * P2 * * *
66156 ** An unconditional jump to address P2.
66157 ** The next instruction executed will be
66158 ** the one at index P2 from the beginning of
66159 ** the program.
66161 case OP_Goto: { /* jump */
66162 pc = pOp->p2 - 1;
66164 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
66165 ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
66166 ** completion. Check to see if sqlite3_interrupt() has been called
66167 ** or if the progress callback needs to be invoked.
66169 ** This code uses unstructured "goto" statements and does not look clean.
66170 ** But that is not due to sloppy coding habits. The code is written this
66171 ** way for performance, to avoid having to run the interrupt and progress
66172 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
66173 ** faster according to "valgrind --tool=cachegrind" */
66174 check_for_interrupt:
66175 CHECK_FOR_INTERRUPT;
66176 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
66177 /* Call the progress callback if it is configured and the required number
66178 ** of VDBE ops have been executed (either since this invocation of
66179 ** sqlite3VdbeExec() or since last time the progress callback was called).
66180 ** If the progress callback returns non-zero, exit the virtual machine with
66181 ** a return code SQLITE_ABORT.
66183 if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
66184 int prc;
66185 prc = db->xProgress(db->pProgressArg);
66186 if( prc!=0 ){
66187 rc = SQLITE_INTERRUPT;
66188 goto vdbe_error_halt;
66190 if( db->xProgress!=0 ){
66191 nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
66194 #endif
66196 break;
66199 /* Opcode: Gosub P1 P2 * * *
66201 ** Write the current address onto register P1
66202 ** and then jump to address P2.
66204 case OP_Gosub: { /* jump */
66205 assert( pOp->p1>0 && pOp->p1<=p->nMem );
66206 pIn1 = &aMem[pOp->p1];
66207 assert( (pIn1->flags & MEM_Dyn)==0 );
66208 memAboutToChange(p, pIn1);
66209 pIn1->flags = MEM_Int;
66210 pIn1->u.i = pc;
66211 REGISTER_TRACE(pOp->p1, pIn1);
66212 pc = pOp->p2 - 1;
66213 break;
66216 /* Opcode: Return P1 * * * *
66218 ** Jump to the next instruction after the address in register P1.
66220 case OP_Return: { /* in1 */
66221 pIn1 = &aMem[pOp->p1];
66222 assert( pIn1->flags & MEM_Int );
66223 pc = (int)pIn1->u.i;
66224 break;
66227 /* Opcode: Yield P1 * * * *
66229 ** Swap the program counter with the value in register P1.
66231 case OP_Yield: { /* in1 */
66232 #if 0 /* local variables moved into u.aa */
66233 int pcDest;
66234 #endif /* local variables moved into u.aa */
66235 pIn1 = &aMem[pOp->p1];
66236 assert( (pIn1->flags & MEM_Dyn)==0 );
66237 pIn1->flags = MEM_Int;
66238 u.aa.pcDest = (int)pIn1->u.i;
66239 pIn1->u.i = pc;
66240 REGISTER_TRACE(pOp->p1, pIn1);
66241 pc = u.aa.pcDest;
66242 break;
66245 /* Opcode: HaltIfNull P1 P2 P3 P4 *
66247 ** Check the value in register P3. If it is NULL then Halt using
66248 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
66249 ** value in register P3 is not NULL, then this routine is a no-op.
66251 case OP_HaltIfNull: { /* in3 */
66252 pIn3 = &aMem[pOp->p3];
66253 if( (pIn3->flags & MEM_Null)==0 ) break;
66254 /* Fall through into OP_Halt */
66257 /* Opcode: Halt P1 P2 * P4 *
66259 ** Exit immediately. All open cursors, etc are closed
66260 ** automatically.
66262 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
66263 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
66264 ** For errors, it can be some other value. If P1!=0 then P2 will determine
66265 ** whether or not to rollback the current transaction. Do not rollback
66266 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
66267 ** then back out all changes that have occurred during this execution of the
66268 ** VDBE, but do not rollback the transaction.
66270 ** If P4 is not null then it is an error message string.
66272 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
66273 ** every program. So a jump past the last instruction of the program
66274 ** is the same as executing Halt.
66276 case OP_Halt: {
66277 if( pOp->p1==SQLITE_OK && p->pFrame ){
66278 /* Halt the sub-program. Return control to the parent frame. */
66279 VdbeFrame *pFrame = p->pFrame;
66280 p->pFrame = pFrame->pParent;
66281 p->nFrame--;
66282 sqlite3VdbeSetChanges(db, p->nChange);
66283 pc = sqlite3VdbeFrameRestore(pFrame);
66284 lastRowid = db->lastRowid;
66285 if( pOp->p2==OE_Ignore ){
66286 /* Instruction pc is the OP_Program that invoked the sub-program
66287 ** currently being halted. If the p2 instruction of this OP_Halt
66288 ** instruction is set to OE_Ignore, then the sub-program is throwing
66289 ** an IGNORE exception. In this case jump to the address specified
66290 ** as the p2 of the calling OP_Program. */
66291 pc = p->aOp[pc].p2-1;
66293 aOp = p->aOp;
66294 aMem = p->aMem;
66295 break;
66298 p->rc = pOp->p1;
66299 p->errorAction = (u8)pOp->p2;
66300 p->pc = pc;
66301 if( pOp->p4.z ){
66302 assert( p->rc!=SQLITE_OK );
66303 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
66304 testcase( sqlite3GlobalConfig.xLog!=0 );
66305 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
66306 }else if( p->rc ){
66307 testcase( sqlite3GlobalConfig.xLog!=0 );
66308 sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
66310 rc = sqlite3VdbeHalt(p);
66311 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
66312 if( rc==SQLITE_BUSY ){
66313 p->rc = rc = SQLITE_BUSY;
66314 }else{
66315 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
66316 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
66317 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
66319 goto vdbe_return;
66322 /* Opcode: Integer P1 P2 * * *
66324 ** The 32-bit integer value P1 is written into register P2.
66326 case OP_Integer: { /* out2-prerelease */
66327 pOut->u.i = pOp->p1;
66328 break;
66331 /* Opcode: Int64 * P2 * P4 *
66333 ** P4 is a pointer to a 64-bit integer value.
66334 ** Write that value into register P2.
66336 case OP_Int64: { /* out2-prerelease */
66337 assert( pOp->p4.pI64!=0 );
66338 pOut->u.i = *pOp->p4.pI64;
66339 break;
66342 #ifndef SQLITE_OMIT_FLOATING_POINT
66343 /* Opcode: Real * P2 * P4 *
66345 ** P4 is a pointer to a 64-bit floating point value.
66346 ** Write that value into register P2.
66348 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
66349 pOut->flags = MEM_Real;
66350 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
66351 pOut->r = *pOp->p4.pReal;
66352 break;
66354 #endif
66356 /* Opcode: String8 * P2 * P4 *
66358 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
66359 ** into an OP_String before it is executed for the first time.
66361 case OP_String8: { /* same as TK_STRING, out2-prerelease */
66362 assert( pOp->p4.z!=0 );
66363 pOp->opcode = OP_String;
66364 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
66366 #ifndef SQLITE_OMIT_UTF16
66367 if( encoding!=SQLITE_UTF8 ){
66368 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
66369 if( rc==SQLITE_TOOBIG ) goto too_big;
66370 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
66371 assert( pOut->zMalloc==pOut->z );
66372 assert( pOut->flags & MEM_Dyn );
66373 pOut->zMalloc = 0;
66374 pOut->flags |= MEM_Static;
66375 pOut->flags &= ~MEM_Dyn;
66376 if( pOp->p4type==P4_DYNAMIC ){
66377 sqlite3DbFree(db, pOp->p4.z);
66379 pOp->p4type = P4_DYNAMIC;
66380 pOp->p4.z = pOut->z;
66381 pOp->p1 = pOut->n;
66383 #endif
66384 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66385 goto too_big;
66387 /* Fall through to the next case, OP_String */
66390 /* Opcode: String P1 P2 * P4 *
66392 ** The string value P4 of length P1 (bytes) is stored in register P2.
66394 case OP_String: { /* out2-prerelease */
66395 assert( pOp->p4.z!=0 );
66396 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
66397 pOut->z = pOp->p4.z;
66398 pOut->n = pOp->p1;
66399 pOut->enc = encoding;
66400 UPDATE_MAX_BLOBSIZE(pOut);
66401 break;
66404 /* Opcode: Null P1 P2 P3 * *
66406 ** Write a NULL into registers P2. If P3 greater than P2, then also write
66407 ** NULL into register P3 and every register in between P2 and P3. If P3
66408 ** is less than P2 (typically P3 is zero) then only register P2 is
66409 ** set to NULL.
66411 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
66412 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
66413 ** OP_Ne or OP_Eq.
66415 case OP_Null: { /* out2-prerelease */
66416 #if 0 /* local variables moved into u.ab */
66417 int cnt;
66418 u16 nullFlag;
66419 #endif /* local variables moved into u.ab */
66420 u.ab.cnt = pOp->p3-pOp->p2;
66421 assert( pOp->p3<=p->nMem );
66422 pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
66423 while( u.ab.cnt>0 ){
66424 pOut++;
66425 memAboutToChange(p, pOut);
66426 VdbeMemRelease(pOut);
66427 pOut->flags = u.ab.nullFlag;
66428 u.ab.cnt--;
66430 break;
66434 /* Opcode: Blob P1 P2 * P4
66436 ** P4 points to a blob of data P1 bytes long. Store this
66437 ** blob in register P2.
66439 case OP_Blob: { /* out2-prerelease */
66440 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
66441 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
66442 pOut->enc = encoding;
66443 UPDATE_MAX_BLOBSIZE(pOut);
66444 break;
66447 /* Opcode: Variable P1 P2 * P4 *
66449 ** Transfer the values of bound parameter P1 into register P2
66451 ** If the parameter is named, then its name appears in P4 and P3==1.
66452 ** The P4 value is used by sqlite3_bind_parameter_name().
66454 case OP_Variable: { /* out2-prerelease */
66455 #if 0 /* local variables moved into u.ac */
66456 Mem *pVar; /* Value being transferred */
66457 #endif /* local variables moved into u.ac */
66459 assert( pOp->p1>0 && pOp->p1<=p->nVar );
66460 assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
66461 u.ac.pVar = &p->aVar[pOp->p1 - 1];
66462 if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
66463 goto too_big;
66465 sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
66466 UPDATE_MAX_BLOBSIZE(pOut);
66467 break;
66470 /* Opcode: Move P1 P2 P3 * *
66472 ** Move the values in register P1..P1+P3 over into
66473 ** registers P2..P2+P3. Registers P1..P1+P3 are
66474 ** left holding a NULL. It is an error for register ranges
66475 ** P1..P1+P3 and P2..P2+P3 to overlap.
66477 case OP_Move: {
66478 #if 0 /* local variables moved into u.ad */
66479 char *zMalloc; /* Holding variable for allocated memory */
66480 int n; /* Number of registers left to copy */
66481 int p1; /* Register to copy from */
66482 int p2; /* Register to copy to */
66483 #endif /* local variables moved into u.ad */
66485 u.ad.n = pOp->p3 + 1;
66486 u.ad.p1 = pOp->p1;
66487 u.ad.p2 = pOp->p2;
66488 assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
66489 assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
66491 pIn1 = &aMem[u.ad.p1];
66492 pOut = &aMem[u.ad.p2];
66493 while( u.ad.n-- ){
66494 assert( pOut<=&aMem[p->nMem] );
66495 assert( pIn1<=&aMem[p->nMem] );
66496 assert( memIsValid(pIn1) );
66497 memAboutToChange(p, pOut);
66498 u.ad.zMalloc = pOut->zMalloc;
66499 pOut->zMalloc = 0;
66500 sqlite3VdbeMemMove(pOut, pIn1);
66501 #ifdef SQLITE_DEBUG
66502 if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
66503 pOut->pScopyFrom += u.ad.p1 - pOp->p2;
66505 #endif
66506 pIn1->zMalloc = u.ad.zMalloc;
66507 REGISTER_TRACE(u.ad.p2++, pOut);
66508 pIn1++;
66509 pOut++;
66511 break;
66514 /* Opcode: Copy P1 P2 P3 * *
66516 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
66518 ** This instruction makes a deep copy of the value. A duplicate
66519 ** is made of any string or blob constant. See also OP_SCopy.
66521 case OP_Copy: {
66522 #if 0 /* local variables moved into u.ae */
66523 int n;
66524 #endif /* local variables moved into u.ae */
66526 u.ae.n = pOp->p3;
66527 pIn1 = &aMem[pOp->p1];
66528 pOut = &aMem[pOp->p2];
66529 assert( pOut!=pIn1 );
66530 while( 1 ){
66531 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
66532 Deephemeralize(pOut);
66533 #ifdef SQLITE_DEBUG
66534 pOut->pScopyFrom = 0;
66535 #endif
66536 REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
66537 if( (u.ae.n--)==0 ) break;
66538 pOut++;
66539 pIn1++;
66541 break;
66544 /* Opcode: SCopy P1 P2 * * *
66546 ** Make a shallow copy of register P1 into register P2.
66548 ** This instruction makes a shallow copy of the value. If the value
66549 ** is a string or blob, then the copy is only a pointer to the
66550 ** original and hence if the original changes so will the copy.
66551 ** Worse, if the original is deallocated, the copy becomes invalid.
66552 ** Thus the program must guarantee that the original will not change
66553 ** during the lifetime of the copy. Use OP_Copy to make a complete
66554 ** copy.
66556 case OP_SCopy: { /* in1, out2 */
66557 pIn1 = &aMem[pOp->p1];
66558 pOut = &aMem[pOp->p2];
66559 assert( pOut!=pIn1 );
66560 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
66561 #ifdef SQLITE_DEBUG
66562 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
66563 #endif
66564 REGISTER_TRACE(pOp->p2, pOut);
66565 break;
66568 /* Opcode: ResultRow P1 P2 * * *
66570 ** The registers P1 through P1+P2-1 contain a single row of
66571 ** results. This opcode causes the sqlite3_step() call to terminate
66572 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
66573 ** structure to provide access to the top P1 values as the result
66574 ** row.
66576 case OP_ResultRow: {
66577 #if 0 /* local variables moved into u.af */
66578 Mem *pMem;
66579 int i;
66580 #endif /* local variables moved into u.af */
66581 assert( p->nResColumn==pOp->p2 );
66582 assert( pOp->p1>0 );
66583 assert( pOp->p1+pOp->p2<=p->nMem+1 );
66585 /* If this statement has violated immediate foreign key constraints, do
66586 ** not return the number of rows modified. And do not RELEASE the statement
66587 ** transaction. It needs to be rolled back. */
66588 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
66589 assert( db->flags&SQLITE_CountRows );
66590 assert( p->usesStmtJournal );
66591 break;
66594 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
66595 ** DML statements invoke this opcode to return the number of rows
66596 ** modified to the user. This is the only way that a VM that
66597 ** opens a statement transaction may invoke this opcode.
66599 ** In case this is such a statement, close any statement transaction
66600 ** opened by this VM before returning control to the user. This is to
66601 ** ensure that statement-transactions are always nested, not overlapping.
66602 ** If the open statement-transaction is not closed here, then the user
66603 ** may step another VM that opens its own statement transaction. This
66604 ** may lead to overlapping statement transactions.
66606 ** The statement transaction is never a top-level transaction. Hence
66607 ** the RELEASE call below can never fail.
66609 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
66610 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
66611 if( NEVER(rc!=SQLITE_OK) ){
66612 break;
66615 /* Invalidate all ephemeral cursor row caches */
66616 p->cacheCtr = (p->cacheCtr + 2)|1;
66618 /* Make sure the results of the current row are \000 terminated
66619 ** and have an assigned type. The results are de-ephemeralized as
66620 ** a side effect.
66622 u.af.pMem = p->pResultSet = &aMem[pOp->p1];
66623 for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
66624 assert( memIsValid(&u.af.pMem[u.af.i]) );
66625 Deephemeralize(&u.af.pMem[u.af.i]);
66626 assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
66627 || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
66628 sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
66629 sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
66630 REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
66632 if( db->mallocFailed ) goto no_mem;
66634 /* Return SQLITE_ROW
66636 p->pc = pc + 1;
66637 rc = SQLITE_ROW;
66638 goto vdbe_return;
66641 /* Opcode: Concat P1 P2 P3 * *
66643 ** Add the text in register P1 onto the end of the text in
66644 ** register P2 and store the result in register P3.
66645 ** If either the P1 or P2 text are NULL then store NULL in P3.
66647 ** P3 = P2 || P1
66649 ** It is illegal for P1 and P3 to be the same register. Sometimes,
66650 ** if P3 is the same register as P2, the implementation is able
66651 ** to avoid a memcpy().
66653 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
66654 #if 0 /* local variables moved into u.ag */
66655 i64 nByte;
66656 #endif /* local variables moved into u.ag */
66658 pIn1 = &aMem[pOp->p1];
66659 pIn2 = &aMem[pOp->p2];
66660 pOut = &aMem[pOp->p3];
66661 assert( pIn1!=pOut );
66662 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66663 sqlite3VdbeMemSetNull(pOut);
66664 break;
66666 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
66667 Stringify(pIn1, encoding);
66668 Stringify(pIn2, encoding);
66669 u.ag.nByte = pIn1->n + pIn2->n;
66670 if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66671 goto too_big;
66673 MemSetTypeFlag(pOut, MEM_Str);
66674 if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
66675 goto no_mem;
66677 if( pOut!=pIn2 ){
66678 memcpy(pOut->z, pIn2->z, pIn2->n);
66680 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
66681 pOut->z[u.ag.nByte] = 0;
66682 pOut->z[u.ag.nByte+1] = 0;
66683 pOut->flags |= MEM_Term;
66684 pOut->n = (int)u.ag.nByte;
66685 pOut->enc = encoding;
66686 UPDATE_MAX_BLOBSIZE(pOut);
66687 break;
66690 /* Opcode: Add P1 P2 P3 * *
66692 ** Add the value in register P1 to the value in register P2
66693 ** and store the result in register P3.
66694 ** If either input is NULL, the result is NULL.
66696 /* Opcode: Multiply P1 P2 P3 * *
66699 ** Multiply the value in register P1 by the value in register P2
66700 ** and store the result in register P3.
66701 ** If either input is NULL, the result is NULL.
66703 /* Opcode: Subtract P1 P2 P3 * *
66705 ** Subtract the value in register P1 from the value in register P2
66706 ** and store the result in register P3.
66707 ** If either input is NULL, the result is NULL.
66709 /* Opcode: Divide P1 P2 P3 * *
66711 ** Divide the value in register P1 by the value in register P2
66712 ** and store the result in register P3 (P3=P2/P1). If the value in
66713 ** register P1 is zero, then the result is NULL. If either input is
66714 ** NULL, the result is NULL.
66716 /* Opcode: Remainder P1 P2 P3 * *
66718 ** Compute the remainder after integer division of the value in
66719 ** register P1 by the value in register P2 and store the result in P3.
66720 ** If the value in register P2 is zero the result is NULL.
66721 ** If either operand is NULL, the result is NULL.
66723 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
66724 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
66725 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
66726 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
66727 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
66728 #if 0 /* local variables moved into u.ah */
66729 char bIntint; /* Started out as two integer operands */
66730 int flags; /* Combined MEM_* flags from both inputs */
66731 i64 iA; /* Integer value of left operand */
66732 i64 iB; /* Integer value of right operand */
66733 double rA; /* Real value of left operand */
66734 double rB; /* Real value of right operand */
66735 #endif /* local variables moved into u.ah */
66737 pIn1 = &aMem[pOp->p1];
66738 applyNumericAffinity(pIn1);
66739 pIn2 = &aMem[pOp->p2];
66740 applyNumericAffinity(pIn2);
66741 pOut = &aMem[pOp->p3];
66742 u.ah.flags = pIn1->flags | pIn2->flags;
66743 if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
66744 if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
66745 u.ah.iA = pIn1->u.i;
66746 u.ah.iB = pIn2->u.i;
66747 u.ah.bIntint = 1;
66748 switch( pOp->opcode ){
66749 case OP_Add: if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
66750 case OP_Subtract: if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
66751 case OP_Multiply: if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
66752 case OP_Divide: {
66753 if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66754 if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
66755 u.ah.iB /= u.ah.iA;
66756 break;
66758 default: {
66759 if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66760 if( u.ah.iA==-1 ) u.ah.iA = 1;
66761 u.ah.iB %= u.ah.iA;
66762 break;
66765 pOut->u.i = u.ah.iB;
66766 MemSetTypeFlag(pOut, MEM_Int);
66767 }else{
66768 u.ah.bIntint = 0;
66769 fp_math:
66770 u.ah.rA = sqlite3VdbeRealValue(pIn1);
66771 u.ah.rB = sqlite3VdbeRealValue(pIn2);
66772 switch( pOp->opcode ){
66773 case OP_Add: u.ah.rB += u.ah.rA; break;
66774 case OP_Subtract: u.ah.rB -= u.ah.rA; break;
66775 case OP_Multiply: u.ah.rB *= u.ah.rA; break;
66776 case OP_Divide: {
66777 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
66778 if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
66779 u.ah.rB /= u.ah.rA;
66780 break;
66782 default: {
66783 u.ah.iA = (i64)u.ah.rA;
66784 u.ah.iB = (i64)u.ah.rB;
66785 if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66786 if( u.ah.iA==-1 ) u.ah.iA = 1;
66787 u.ah.rB = (double)(u.ah.iB % u.ah.iA);
66788 break;
66791 #ifdef SQLITE_OMIT_FLOATING_POINT
66792 pOut->u.i = u.ah.rB;
66793 MemSetTypeFlag(pOut, MEM_Int);
66794 #else
66795 if( sqlite3IsNaN(u.ah.rB) ){
66796 goto arithmetic_result_is_null;
66798 pOut->r = u.ah.rB;
66799 MemSetTypeFlag(pOut, MEM_Real);
66800 if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
66801 sqlite3VdbeIntegerAffinity(pOut);
66803 #endif
66805 break;
66807 arithmetic_result_is_null:
66808 sqlite3VdbeMemSetNull(pOut);
66809 break;
66812 /* Opcode: CollSeq P1 * * P4
66814 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
66815 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
66816 ** be returned. This is used by the built-in min(), max() and nullif()
66817 ** functions.
66819 ** If P1 is not zero, then it is a register that a subsequent min() or
66820 ** max() aggregate will set to 1 if the current row is not the minimum or
66821 ** maximum. The P1 register is initialized to 0 by this instruction.
66823 ** The interface used by the implementation of the aforementioned functions
66824 ** to retrieve the collation sequence set by this opcode is not available
66825 ** publicly, only to user functions defined in func.c.
66827 case OP_CollSeq: {
66828 assert( pOp->p4type==P4_COLLSEQ );
66829 if( pOp->p1 ){
66830 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
66832 break;
66835 /* Opcode: Function P1 P2 P3 P4 P5
66837 ** Invoke a user function (P4 is a pointer to a Function structure that
66838 ** defines the function) with P5 arguments taken from register P2 and
66839 ** successors. The result of the function is stored in register P3.
66840 ** Register P3 must not be one of the function inputs.
66842 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
66843 ** function was determined to be constant at compile time. If the first
66844 ** argument was constant then bit 0 of P1 is set. This is used to determine
66845 ** whether meta data associated with a user function argument using the
66846 ** sqlite3_set_auxdata() API may be safely retained until the next
66847 ** invocation of this opcode.
66849 ** See also: AggStep and AggFinal
66851 case OP_Function: {
66852 #if 0 /* local variables moved into u.ai */
66853 int i;
66854 Mem *pArg;
66855 sqlite3_context ctx;
66856 sqlite3_value **apVal;
66857 int n;
66858 #endif /* local variables moved into u.ai */
66860 u.ai.n = pOp->p5;
66861 u.ai.apVal = p->apArg;
66862 assert( u.ai.apVal || u.ai.n==0 );
66863 assert( pOp->p3>0 && pOp->p3<=p->nMem );
66864 pOut = &aMem[pOp->p3];
66865 memAboutToChange(p, pOut);
66867 assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=p->nMem+1) );
66868 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
66869 u.ai.pArg = &aMem[pOp->p2];
66870 for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
66871 assert( memIsValid(u.ai.pArg) );
66872 u.ai.apVal[u.ai.i] = u.ai.pArg;
66873 Deephemeralize(u.ai.pArg);
66874 sqlite3VdbeMemStoreType(u.ai.pArg);
66875 REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
66878 assert( pOp->p4type==P4_FUNCDEF );
66879 u.ai.ctx.pFunc = pOp->p4.pFunc;
66880 u.ai.ctx.s.flags = MEM_Null;
66881 u.ai.ctx.s.db = db;
66882 u.ai.ctx.s.xDel = 0;
66883 u.ai.ctx.s.zMalloc = 0;
66884 u.ai.ctx.iOp = pc;
66885 u.ai.ctx.pVdbe = p;
66887 /* The output cell may already have a buffer allocated. Move
66888 ** the pointer to u.ai.ctx.s so in case the user-function can use
66889 ** the already allocated buffer instead of allocating a new one.
66891 sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
66892 MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
66894 u.ai.ctx.fErrorOrAux = 0;
66895 if( u.ai.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
66896 assert( pOp>aOp );
66897 assert( pOp[-1].p4type==P4_COLLSEQ );
66898 assert( pOp[-1].opcode==OP_CollSeq );
66899 u.ai.ctx.pColl = pOp[-1].p4.pColl;
66901 db->lastRowid = lastRowid;
66902 (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
66903 lastRowid = db->lastRowid;
66905 if( db->mallocFailed ){
66906 /* Even though a malloc() has failed, the implementation of the
66907 ** user function may have called an sqlite3_result_XXX() function
66908 ** to return a value. The following call releases any resources
66909 ** associated with such a value.
66911 sqlite3VdbeMemRelease(&u.ai.ctx.s);
66912 goto no_mem;
66915 /* If the function returned an error, throw an exception */
66916 if( u.ai.ctx.fErrorOrAux ){
66917 if( u.ai.ctx.isError ){
66918 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
66919 rc = u.ai.ctx.isError;
66921 sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
66924 /* Copy the result of the function into register P3 */
66925 sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
66926 sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
66927 if( sqlite3VdbeMemTooBig(pOut) ){
66928 goto too_big;
66931 #if 0
66932 /* The app-defined function has done something that as caused this
66933 ** statement to expire. (Perhaps the function called sqlite3_exec()
66934 ** with a CREATE TABLE statement.)
66936 if( p->expired ) rc = SQLITE_ABORT;
66937 #endif
66939 REGISTER_TRACE(pOp->p3, pOut);
66940 UPDATE_MAX_BLOBSIZE(pOut);
66941 break;
66944 /* Opcode: BitAnd P1 P2 P3 * *
66946 ** Take the bit-wise AND of the values in register P1 and P2 and
66947 ** store the result in register P3.
66948 ** If either input is NULL, the result is NULL.
66950 /* Opcode: BitOr P1 P2 P3 * *
66952 ** Take the bit-wise OR of the values in register P1 and P2 and
66953 ** store the result in register P3.
66954 ** If either input is NULL, the result is NULL.
66956 /* Opcode: ShiftLeft P1 P2 P3 * *
66958 ** Shift the integer value in register P2 to the left by the
66959 ** number of bits specified by the integer in register P1.
66960 ** Store the result in register P3.
66961 ** If either input is NULL, the result is NULL.
66963 /* Opcode: ShiftRight P1 P2 P3 * *
66965 ** Shift the integer value in register P2 to the right by the
66966 ** number of bits specified by the integer in register P1.
66967 ** Store the result in register P3.
66968 ** If either input is NULL, the result is NULL.
66970 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
66971 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
66972 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
66973 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
66974 #if 0 /* local variables moved into u.aj */
66975 i64 iA;
66976 u64 uA;
66977 i64 iB;
66978 u8 op;
66979 #endif /* local variables moved into u.aj */
66981 pIn1 = &aMem[pOp->p1];
66982 pIn2 = &aMem[pOp->p2];
66983 pOut = &aMem[pOp->p3];
66984 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66985 sqlite3VdbeMemSetNull(pOut);
66986 break;
66988 u.aj.iA = sqlite3VdbeIntValue(pIn2);
66989 u.aj.iB = sqlite3VdbeIntValue(pIn1);
66990 u.aj.op = pOp->opcode;
66991 if( u.aj.op==OP_BitAnd ){
66992 u.aj.iA &= u.aj.iB;
66993 }else if( u.aj.op==OP_BitOr ){
66994 u.aj.iA |= u.aj.iB;
66995 }else if( u.aj.iB!=0 ){
66996 assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
66998 /* If shifting by a negative amount, shift in the other direction */
66999 if( u.aj.iB<0 ){
67000 assert( OP_ShiftRight==OP_ShiftLeft+1 );
67001 u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
67002 u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
67005 if( u.aj.iB>=64 ){
67006 u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
67007 }else{
67008 memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
67009 if( u.aj.op==OP_ShiftLeft ){
67010 u.aj.uA <<= u.aj.iB;
67011 }else{
67012 u.aj.uA >>= u.aj.iB;
67013 /* Sign-extend on a right shift of a negative number */
67014 if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
67016 memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
67019 pOut->u.i = u.aj.iA;
67020 MemSetTypeFlag(pOut, MEM_Int);
67021 break;
67024 /* Opcode: AddImm P1 P2 * * *
67026 ** Add the constant P2 to the value in register P1.
67027 ** The result is always an integer.
67029 ** To force any register to be an integer, just add 0.
67031 case OP_AddImm: { /* in1 */
67032 pIn1 = &aMem[pOp->p1];
67033 memAboutToChange(p, pIn1);
67034 sqlite3VdbeMemIntegerify(pIn1);
67035 pIn1->u.i += pOp->p2;
67036 break;
67039 /* Opcode: MustBeInt P1 P2 * * *
67041 ** Force the value in register P1 to be an integer. If the value
67042 ** in P1 is not an integer and cannot be converted into an integer
67043 ** without data loss, then jump immediately to P2, or if P2==0
67044 ** raise an SQLITE_MISMATCH exception.
67046 case OP_MustBeInt: { /* jump, in1 */
67047 pIn1 = &aMem[pOp->p1];
67048 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
67049 if( (pIn1->flags & MEM_Int)==0 ){
67050 if( pOp->p2==0 ){
67051 rc = SQLITE_MISMATCH;
67052 goto abort_due_to_error;
67053 }else{
67054 pc = pOp->p2 - 1;
67056 }else{
67057 MemSetTypeFlag(pIn1, MEM_Int);
67059 break;
67062 #ifndef SQLITE_OMIT_FLOATING_POINT
67063 /* Opcode: RealAffinity P1 * * * *
67065 ** If register P1 holds an integer convert it to a real value.
67067 ** This opcode is used when extracting information from a column that
67068 ** has REAL affinity. Such column values may still be stored as
67069 ** integers, for space efficiency, but after extraction we want them
67070 ** to have only a real value.
67072 case OP_RealAffinity: { /* in1 */
67073 pIn1 = &aMem[pOp->p1];
67074 if( pIn1->flags & MEM_Int ){
67075 sqlite3VdbeMemRealify(pIn1);
67077 break;
67079 #endif
67081 #ifndef SQLITE_OMIT_CAST
67082 /* Opcode: ToText P1 * * * *
67084 ** Force the value in register P1 to be text.
67085 ** If the value is numeric, convert it to a string using the
67086 ** equivalent of printf(). Blob values are unchanged and
67087 ** are afterwards simply interpreted as text.
67089 ** A NULL value is not changed by this routine. It remains NULL.
67091 case OP_ToText: { /* same as TK_TO_TEXT, in1 */
67092 pIn1 = &aMem[pOp->p1];
67093 memAboutToChange(p, pIn1);
67094 if( pIn1->flags & MEM_Null ) break;
67095 assert( MEM_Str==(MEM_Blob>>3) );
67096 pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
67097 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
67098 rc = ExpandBlob(pIn1);
67099 assert( pIn1->flags & MEM_Str || db->mallocFailed );
67100 pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
67101 UPDATE_MAX_BLOBSIZE(pIn1);
67102 break;
67105 /* Opcode: ToBlob P1 * * * *
67107 ** Force the value in register P1 to be a BLOB.
67108 ** If the value is numeric, convert it to a string first.
67109 ** Strings are simply reinterpreted as blobs with no change
67110 ** to the underlying data.
67112 ** A NULL value is not changed by this routine. It remains NULL.
67114 case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
67115 pIn1 = &aMem[pOp->p1];
67116 if( pIn1->flags & MEM_Null ) break;
67117 if( (pIn1->flags & MEM_Blob)==0 ){
67118 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
67119 assert( pIn1->flags & MEM_Str || db->mallocFailed );
67120 MemSetTypeFlag(pIn1, MEM_Blob);
67121 }else{
67122 pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
67124 UPDATE_MAX_BLOBSIZE(pIn1);
67125 break;
67128 /* Opcode: ToNumeric P1 * * * *
67130 ** Force the value in register P1 to be numeric (either an
67131 ** integer or a floating-point number.)
67132 ** If the value is text or blob, try to convert it to an using the
67133 ** equivalent of atoi() or atof() and store 0 if no such conversion
67134 ** is possible.
67136 ** A NULL value is not changed by this routine. It remains NULL.
67138 case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
67139 pIn1 = &aMem[pOp->p1];
67140 sqlite3VdbeMemNumerify(pIn1);
67141 break;
67143 #endif /* SQLITE_OMIT_CAST */
67145 /* Opcode: ToInt P1 * * * *
67147 ** Force the value in register P1 to be an integer. If
67148 ** The value is currently a real number, drop its fractional part.
67149 ** If the value is text or blob, try to convert it to an integer using the
67150 ** equivalent of atoi() and store 0 if no such conversion is possible.
67152 ** A NULL value is not changed by this routine. It remains NULL.
67154 case OP_ToInt: { /* same as TK_TO_INT, in1 */
67155 pIn1 = &aMem[pOp->p1];
67156 if( (pIn1->flags & MEM_Null)==0 ){
67157 sqlite3VdbeMemIntegerify(pIn1);
67159 break;
67162 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
67163 /* Opcode: ToReal P1 * * * *
67165 ** Force the value in register P1 to be a floating point number.
67166 ** If The value is currently an integer, convert it.
67167 ** If the value is text or blob, try to convert it to an integer using the
67168 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
67170 ** A NULL value is not changed by this routine. It remains NULL.
67172 case OP_ToReal: { /* same as TK_TO_REAL, in1 */
67173 pIn1 = &aMem[pOp->p1];
67174 memAboutToChange(p, pIn1);
67175 if( (pIn1->flags & MEM_Null)==0 ){
67176 sqlite3VdbeMemRealify(pIn1);
67178 break;
67180 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
67182 /* Opcode: Lt P1 P2 P3 P4 P5
67184 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
67185 ** jump to address P2.
67187 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
67188 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
67189 ** bit is clear then fall through if either operand is NULL.
67191 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
67192 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
67193 ** to coerce both inputs according to this affinity before the
67194 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
67195 ** affinity is used. Note that the affinity conversions are stored
67196 ** back into the input registers P1 and P3. So this opcode can cause
67197 ** persistent changes to registers P1 and P3.
67199 ** Once any conversions have taken place, and neither value is NULL,
67200 ** the values are compared. If both values are blobs then memcmp() is
67201 ** used to determine the results of the comparison. If both values
67202 ** are text, then the appropriate collating function specified in
67203 ** P4 is used to do the comparison. If P4 is not specified then
67204 ** memcmp() is used to compare text string. If both values are
67205 ** numeric, then a numeric comparison is used. If the two values
67206 ** are of different types, then numbers are considered less than
67207 ** strings and strings are considered less than blobs.
67209 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
67210 ** store a boolean result (either 0, or 1, or NULL) in register P2.
67212 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
67213 ** equal to one another, provided that they do not have their MEM_Cleared
67214 ** bit set.
67216 /* Opcode: Ne P1 P2 P3 P4 P5
67218 ** This works just like the Lt opcode except that the jump is taken if
67219 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
67220 ** additional information.
67222 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
67223 ** true or false and is never NULL. If both operands are NULL then the result
67224 ** of comparison is false. If either operand is NULL then the result is true.
67225 ** If neither operand is NULL the result is the same as it would be if
67226 ** the SQLITE_NULLEQ flag were omitted from P5.
67228 /* Opcode: Eq P1 P2 P3 P4 P5
67230 ** This works just like the Lt opcode except that the jump is taken if
67231 ** the operands in registers P1 and P3 are equal.
67232 ** See the Lt opcode for additional information.
67234 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
67235 ** true or false and is never NULL. If both operands are NULL then the result
67236 ** of comparison is true. If either operand is NULL then the result is false.
67237 ** If neither operand is NULL the result is the same as it would be if
67238 ** the SQLITE_NULLEQ flag were omitted from P5.
67240 /* Opcode: Le P1 P2 P3 P4 P5
67242 ** This works just like the Lt opcode except that the jump is taken if
67243 ** the content of register P3 is less than or equal to the content of
67244 ** register P1. See the Lt opcode for additional information.
67246 /* Opcode: Gt P1 P2 P3 P4 P5
67248 ** This works just like the Lt opcode except that the jump is taken if
67249 ** the content of register P3 is greater than the content of
67250 ** register P1. See the Lt opcode for additional information.
67252 /* Opcode: Ge P1 P2 P3 P4 P5
67254 ** This works just like the Lt opcode except that the jump is taken if
67255 ** the content of register P3 is greater than or equal to the content of
67256 ** register P1. See the Lt opcode for additional information.
67258 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
67259 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
67260 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
67261 case OP_Le: /* same as TK_LE, jump, in1, in3 */
67262 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
67263 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
67264 #if 0 /* local variables moved into u.ak */
67265 int res; /* Result of the comparison of pIn1 against pIn3 */
67266 char affinity; /* Affinity to use for comparison */
67267 u16 flags1; /* Copy of initial value of pIn1->flags */
67268 u16 flags3; /* Copy of initial value of pIn3->flags */
67269 #endif /* local variables moved into u.ak */
67271 pIn1 = &aMem[pOp->p1];
67272 pIn3 = &aMem[pOp->p3];
67273 u.ak.flags1 = pIn1->flags;
67274 u.ak.flags3 = pIn3->flags;
67275 if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
67276 /* One or both operands are NULL */
67277 if( pOp->p5 & SQLITE_NULLEQ ){
67278 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
67279 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
67280 ** or not both operands are null.
67282 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
67283 assert( (u.ak.flags1 & MEM_Cleared)==0 );
67284 if( (u.ak.flags1&MEM_Null)!=0
67285 && (u.ak.flags3&MEM_Null)!=0
67286 && (u.ak.flags3&MEM_Cleared)==0
67288 u.ak.res = 0; /* Results are equal */
67289 }else{
67290 u.ak.res = 1; /* Results are not equal */
67292 }else{
67293 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
67294 ** then the result is always NULL.
67295 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
67297 if( pOp->p5 & SQLITE_JUMPIFNULL ){
67298 pc = pOp->p2-1;
67299 }else if( pOp->p5 & SQLITE_STOREP2 ){
67300 pOut = &aMem[pOp->p2];
67301 MemSetTypeFlag(pOut, MEM_Null);
67302 REGISTER_TRACE(pOp->p2, pOut);
67304 break;
67306 }else{
67307 /* Neither operand is NULL. Do a comparison. */
67308 u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
67309 if( u.ak.affinity ){
67310 applyAffinity(pIn1, u.ak.affinity, encoding);
67311 applyAffinity(pIn3, u.ak.affinity, encoding);
67312 if( db->mallocFailed ) goto no_mem;
67315 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
67316 ExpandBlob(pIn1);
67317 ExpandBlob(pIn3);
67318 u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
67320 switch( pOp->opcode ){
67321 case OP_Eq: u.ak.res = u.ak.res==0; break;
67322 case OP_Ne: u.ak.res = u.ak.res!=0; break;
67323 case OP_Lt: u.ak.res = u.ak.res<0; break;
67324 case OP_Le: u.ak.res = u.ak.res<=0; break;
67325 case OP_Gt: u.ak.res = u.ak.res>0; break;
67326 default: u.ak.res = u.ak.res>=0; break;
67329 if( pOp->p5 & SQLITE_STOREP2 ){
67330 pOut = &aMem[pOp->p2];
67331 memAboutToChange(p, pOut);
67332 MemSetTypeFlag(pOut, MEM_Int);
67333 pOut->u.i = u.ak.res;
67334 REGISTER_TRACE(pOp->p2, pOut);
67335 }else if( u.ak.res ){
67336 pc = pOp->p2-1;
67339 /* Undo any changes made by applyAffinity() to the input registers. */
67340 pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
67341 pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
67342 break;
67345 /* Opcode: Permutation * * * P4 *
67347 ** Set the permutation used by the OP_Compare operator to be the array
67348 ** of integers in P4.
67350 ** The permutation is only valid until the next OP_Compare that has
67351 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
67352 ** occur immediately prior to the OP_Compare.
67354 case OP_Permutation: {
67355 assert( pOp->p4type==P4_INTARRAY );
67356 assert( pOp->p4.ai );
67357 aPermute = pOp->p4.ai;
67358 break;
67361 /* Opcode: Compare P1 P2 P3 P4 P5
67363 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
67364 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
67365 ** the comparison for use by the next OP_Jump instruct.
67367 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
67368 ** determined by the most recent OP_Permutation operator. If the
67369 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
67370 ** order.
67372 ** P4 is a KeyInfo structure that defines collating sequences and sort
67373 ** orders for the comparison. The permutation applies to registers
67374 ** only. The KeyInfo elements are used sequentially.
67376 ** The comparison is a sort comparison, so NULLs compare equal,
67377 ** NULLs are less than numbers, numbers are less than strings,
67378 ** and strings are less than blobs.
67380 case OP_Compare: {
67381 #if 0 /* local variables moved into u.al */
67382 int n;
67383 int i;
67384 int p1;
67385 int p2;
67386 const KeyInfo *pKeyInfo;
67387 int idx;
67388 CollSeq *pColl; /* Collating sequence to use on this term */
67389 int bRev; /* True for DESCENDING sort order */
67390 #endif /* local variables moved into u.al */
67392 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
67393 u.al.n = pOp->p3;
67394 u.al.pKeyInfo = pOp->p4.pKeyInfo;
67395 assert( u.al.n>0 );
67396 assert( u.al.pKeyInfo!=0 );
67397 u.al.p1 = pOp->p1;
67398 u.al.p2 = pOp->p2;
67399 #if SQLITE_DEBUG
67400 if( aPermute ){
67401 int k, mx = 0;
67402 for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
67403 assert( u.al.p1>0 && u.al.p1+mx<=p->nMem+1 );
67404 assert( u.al.p2>0 && u.al.p2+mx<=p->nMem+1 );
67405 }else{
67406 assert( u.al.p1>0 && u.al.p1+u.al.n<=p->nMem+1 );
67407 assert( u.al.p2>0 && u.al.p2+u.al.n<=p->nMem+1 );
67409 #endif /* SQLITE_DEBUG */
67410 for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
67411 u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
67412 assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
67413 assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
67414 REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
67415 REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
67416 assert( u.al.i<u.al.pKeyInfo->nField );
67417 u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
67418 u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
67419 iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
67420 if( iCompare ){
67421 if( u.al.bRev ) iCompare = -iCompare;
67422 break;
67425 aPermute = 0;
67426 break;
67429 /* Opcode: Jump P1 P2 P3 * *
67431 ** Jump to the instruction at address P1, P2, or P3 depending on whether
67432 ** in the most recent OP_Compare instruction the P1 vector was less than
67433 ** equal to, or greater than the P2 vector, respectively.
67435 case OP_Jump: { /* jump */
67436 if( iCompare<0 ){
67437 pc = pOp->p1 - 1;
67438 }else if( iCompare==0 ){
67439 pc = pOp->p2 - 1;
67440 }else{
67441 pc = pOp->p3 - 1;
67443 break;
67446 /* Opcode: And P1 P2 P3 * *
67448 ** Take the logical AND of the values in registers P1 and P2 and
67449 ** write the result into register P3.
67451 ** If either P1 or P2 is 0 (false) then the result is 0 even if
67452 ** the other input is NULL. A NULL and true or two NULLs give
67453 ** a NULL output.
67455 /* Opcode: Or P1 P2 P3 * *
67457 ** Take the logical OR of the values in register P1 and P2 and
67458 ** store the answer in register P3.
67460 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
67461 ** even if the other input is NULL. A NULL and false or two NULLs
67462 ** give a NULL output.
67464 case OP_And: /* same as TK_AND, in1, in2, out3 */
67465 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
67466 #if 0 /* local variables moved into u.am */
67467 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
67468 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
67469 #endif /* local variables moved into u.am */
67471 pIn1 = &aMem[pOp->p1];
67472 if( pIn1->flags & MEM_Null ){
67473 u.am.v1 = 2;
67474 }else{
67475 u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
67477 pIn2 = &aMem[pOp->p2];
67478 if( pIn2->flags & MEM_Null ){
67479 u.am.v2 = 2;
67480 }else{
67481 u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
67483 if( pOp->opcode==OP_And ){
67484 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
67485 u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
67486 }else{
67487 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
67488 u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
67490 pOut = &aMem[pOp->p3];
67491 if( u.am.v1==2 ){
67492 MemSetTypeFlag(pOut, MEM_Null);
67493 }else{
67494 pOut->u.i = u.am.v1;
67495 MemSetTypeFlag(pOut, MEM_Int);
67497 break;
67500 /* Opcode: Not P1 P2 * * *
67502 ** Interpret the value in register P1 as a boolean value. Store the
67503 ** boolean complement in register P2. If the value in register P1 is
67504 ** NULL, then a NULL is stored in P2.
67506 case OP_Not: { /* same as TK_NOT, in1, out2 */
67507 pIn1 = &aMem[pOp->p1];
67508 pOut = &aMem[pOp->p2];
67509 if( pIn1->flags & MEM_Null ){
67510 sqlite3VdbeMemSetNull(pOut);
67511 }else{
67512 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
67514 break;
67517 /* Opcode: BitNot P1 P2 * * *
67519 ** Interpret the content of register P1 as an integer. Store the
67520 ** ones-complement of the P1 value into register P2. If P1 holds
67521 ** a NULL then store a NULL in P2.
67523 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
67524 pIn1 = &aMem[pOp->p1];
67525 pOut = &aMem[pOp->p2];
67526 if( pIn1->flags & MEM_Null ){
67527 sqlite3VdbeMemSetNull(pOut);
67528 }else{
67529 sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
67531 break;
67534 /* Opcode: Once P1 P2 * * *
67536 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
67537 ** set the flag and fall through to the next instruction.
67539 case OP_Once: { /* jump */
67540 assert( pOp->p1<p->nOnceFlag );
67541 if( p->aOnceFlag[pOp->p1] ){
67542 pc = pOp->p2-1;
67543 }else{
67544 p->aOnceFlag[pOp->p1] = 1;
67546 break;
67549 /* Opcode: If P1 P2 P3 * *
67551 ** Jump to P2 if the value in register P1 is true. The value
67552 ** is considered true if it is numeric and non-zero. If the value
67553 ** in P1 is NULL then take the jump if P3 is non-zero.
67555 /* Opcode: IfNot P1 P2 P3 * *
67557 ** Jump to P2 if the value in register P1 is False. The value
67558 ** is considered false if it has a numeric value of zero. If the value
67559 ** in P1 is NULL then take the jump if P3 is zero.
67561 case OP_If: /* jump, in1 */
67562 case OP_IfNot: { /* jump, in1 */
67563 #if 0 /* local variables moved into u.an */
67564 int c;
67565 #endif /* local variables moved into u.an */
67566 pIn1 = &aMem[pOp->p1];
67567 if( pIn1->flags & MEM_Null ){
67568 u.an.c = pOp->p3;
67569 }else{
67570 #ifdef SQLITE_OMIT_FLOATING_POINT
67571 u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
67572 #else
67573 u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
67574 #endif
67575 if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
67577 if( u.an.c ){
67578 pc = pOp->p2-1;
67580 break;
67583 /* Opcode: IsNull P1 P2 * * *
67585 ** Jump to P2 if the value in register P1 is NULL.
67587 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
67588 pIn1 = &aMem[pOp->p1];
67589 if( (pIn1->flags & MEM_Null)!=0 ){
67590 pc = pOp->p2 - 1;
67592 break;
67595 /* Opcode: NotNull P1 P2 * * *
67597 ** Jump to P2 if the value in register P1 is not NULL.
67599 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
67600 pIn1 = &aMem[pOp->p1];
67601 if( (pIn1->flags & MEM_Null)==0 ){
67602 pc = pOp->p2 - 1;
67604 break;
67607 /* Opcode: Column P1 P2 P3 P4 P5
67609 ** Interpret the data that cursor P1 points to as a structure built using
67610 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
67611 ** information about the format of the data.) Extract the P2-th column
67612 ** from this record. If there are less that (P2+1)
67613 ** values in the record, extract a NULL.
67615 ** The value extracted is stored in register P3.
67617 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
67618 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
67619 ** the result.
67621 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
67622 ** then the cache of the cursor is reset prior to extracting the column.
67623 ** The first OP_Column against a pseudo-table after the value of the content
67624 ** register has changed should have this bit set.
67626 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
67627 ** the result is guaranteed to only be used as the argument of a length()
67628 ** or typeof() function, respectively. The loading of large blobs can be
67629 ** skipped for length() and all content loading can be skipped for typeof().
67631 case OP_Column: {
67632 #if 0 /* local variables moved into u.ao */
67633 u32 payloadSize; /* Number of bytes in the record */
67634 i64 payloadSize64; /* Number of bytes in the record */
67635 int p1; /* P1 value of the opcode */
67636 int p2; /* column number to retrieve */
67637 VdbeCursor *pC; /* The VDBE cursor */
67638 char *zRec; /* Pointer to complete record-data */
67639 BtCursor *pCrsr; /* The BTree cursor */
67640 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
67641 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
67642 int nField; /* number of fields in the record */
67643 int len; /* The length of the serialized data for the column */
67644 int i; /* Loop counter */
67645 char *zData; /* Part of the record being decoded */
67646 Mem *pDest; /* Where to write the extracted value */
67647 Mem sMem; /* For storing the record being decoded */
67648 u8 *zIdx; /* Index into header */
67649 u8 *zEndHdr; /* Pointer to first byte after the header */
67650 u32 offset; /* Offset into the data */
67651 u32 szField; /* Number of bytes in the content of a field */
67652 int szHdr; /* Size of the header size field at start of record */
67653 int avail; /* Number of bytes of available data */
67654 u32 t; /* A type code from the record header */
67655 Mem *pReg; /* PseudoTable input register */
67656 #endif /* local variables moved into u.ao */
67659 u.ao.p1 = pOp->p1;
67660 u.ao.p2 = pOp->p2;
67661 u.ao.pC = 0;
67662 memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
67663 assert( u.ao.p1<p->nCursor );
67664 assert( pOp->p3>0 && pOp->p3<=p->nMem );
67665 u.ao.pDest = &aMem[pOp->p3];
67666 memAboutToChange(p, u.ao.pDest);
67667 u.ao.zRec = 0;
67669 /* This block sets the variable u.ao.payloadSize to be the total number of
67670 ** bytes in the record.
67672 ** u.ao.zRec is set to be the complete text of the record if it is available.
67673 ** The complete record text is always available for pseudo-tables
67674 ** If the record is stored in a cursor, the complete record text
67675 ** might be available in the u.ao.pC->aRow cache. Or it might not be.
67676 ** If the data is unavailable, u.ao.zRec is set to NULL.
67678 ** We also compute the number of columns in the record. For cursors,
67679 ** the number of columns is stored in the VdbeCursor.nField element.
67681 u.ao.pC = p->apCsr[u.ao.p1];
67682 assert( u.ao.pC!=0 );
67683 #ifndef SQLITE_OMIT_VIRTUALTABLE
67684 assert( u.ao.pC->pVtabCursor==0 );
67685 #endif
67686 u.ao.pCrsr = u.ao.pC->pCursor;
67687 if( u.ao.pCrsr!=0 ){
67688 /* The record is stored in a B-Tree */
67689 rc = sqlite3VdbeCursorMoveto(u.ao.pC);
67690 if( rc ) goto abort_due_to_error;
67691 if( u.ao.pC->nullRow ){
67692 u.ao.payloadSize = 0;
67693 }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
67694 u.ao.payloadSize = u.ao.pC->payloadSize;
67695 u.ao.zRec = (char*)u.ao.pC->aRow;
67696 }else if( u.ao.pC->isIndex ){
67697 assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
67698 VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
67699 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
67700 /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
67701 ** payload size, so it is impossible for u.ao.payloadSize64 to be
67702 ** larger than 32 bits. */
67703 assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
67704 u.ao.payloadSize = (u32)u.ao.payloadSize64;
67705 }else{
67706 assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
67707 VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
67708 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
67710 }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
67711 u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
67712 if( u.ao.pC->multiPseudo ){
67713 sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
67714 Deephemeralize(u.ao.pDest);
67715 goto op_column_out;
67717 assert( u.ao.pReg->flags & MEM_Blob );
67718 assert( memIsValid(u.ao.pReg) );
67719 u.ao.payloadSize = u.ao.pReg->n;
67720 u.ao.zRec = u.ao.pReg->z;
67721 u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
67722 assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
67723 }else{
67724 /* Consider the row to be NULL */
67725 u.ao.payloadSize = 0;
67728 /* If u.ao.payloadSize is 0, then just store a NULL. This can happen because of
67729 ** nullRow or because of a corrupt database. */
67730 if( u.ao.payloadSize==0 ){
67731 MemSetTypeFlag(u.ao.pDest, MEM_Null);
67732 goto op_column_out;
67734 assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
67735 if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
67736 goto too_big;
67739 u.ao.nField = u.ao.pC->nField;
67740 assert( u.ao.p2<u.ao.nField );
67742 /* Read and parse the table header. Store the results of the parse
67743 ** into the record header cache fields of the cursor.
67745 u.ao.aType = u.ao.pC->aType;
67746 if( u.ao.pC->cacheStatus==p->cacheCtr ){
67747 u.ao.aOffset = u.ao.pC->aOffset;
67748 }else{
67749 assert(u.ao.aType);
67750 u.ao.avail = 0;
67751 u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
67752 u.ao.pC->payloadSize = u.ao.payloadSize;
67753 u.ao.pC->cacheStatus = p->cacheCtr;
67755 /* Figure out how many bytes are in the header */
67756 if( u.ao.zRec ){
67757 u.ao.zData = u.ao.zRec;
67758 }else{
67759 if( u.ao.pC->isIndex ){
67760 u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
67761 }else{
67762 u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
67764 /* If KeyFetch()/DataFetch() managed to get the entire payload,
67765 ** save the payload in the u.ao.pC->aRow cache. That will save us from
67766 ** having to make additional calls to fetch the content portion of
67767 ** the record.
67769 assert( u.ao.avail>=0 );
67770 if( u.ao.payloadSize <= (u32)u.ao.avail ){
67771 u.ao.zRec = u.ao.zData;
67772 u.ao.pC->aRow = (u8*)u.ao.zData;
67773 }else{
67774 u.ao.pC->aRow = 0;
67777 /* The following assert is true in all cases except when
67778 ** the database file has been corrupted externally.
67779 ** assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
67780 u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
67782 /* Make sure a corrupt database has not given us an oversize header.
67783 ** Do this now to avoid an oversize memory allocation.
67785 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
67786 ** types use so much data space that there can only be 4096 and 32 of
67787 ** them, respectively. So the maximum header length results from a
67788 ** 3-byte type for each of the maximum of 32768 columns plus three
67789 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
67791 if( u.ao.offset > 98307 ){
67792 rc = SQLITE_CORRUPT_BKPT;
67793 goto op_column_out;
67796 /* Compute in u.ao.len the number of bytes of data we need to read in order
67797 ** to get u.ao.nField type values. u.ao.offset is an upper bound on this. But
67798 ** u.ao.nField might be significantly less than the true number of columns
67799 ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
67800 ** We want to minimize u.ao.len in order to limit the size of the memory
67801 ** allocation, especially if a corrupt database file has caused u.ao.offset
67802 ** to be oversized. Offset is limited to 98307 above. But 98307 might
67803 ** still exceed Robson memory allocation limits on some configurations.
67804 ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
67805 ** will likely be much smaller since u.ao.nField will likely be less than
67806 ** 20 or so. This insures that Robson memory allocation limits are
67807 ** not exceeded even for corrupt database files.
67809 u.ao.len = u.ao.nField*5 + 3;
67810 if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
67812 /* The KeyFetch() or DataFetch() above are fast and will get the entire
67813 ** record header in most cases. But they will fail to get the complete
67814 ** record header if the record header does not fit on a single page
67815 ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
67816 ** acquire the complete header text.
67818 if( !u.ao.zRec && u.ao.avail<u.ao.len ){
67819 u.ao.sMem.flags = 0;
67820 u.ao.sMem.db = 0;
67821 rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
67822 if( rc!=SQLITE_OK ){
67823 goto op_column_out;
67825 u.ao.zData = u.ao.sMem.z;
67827 u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
67828 u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
67830 /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
67831 ** arrays. u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
67832 ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
67833 ** of the record to the start of the data for the u.ao.i-th column
67835 for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
67836 if( u.ao.zIdx<u.ao.zEndHdr ){
67837 u.ao.aOffset[u.ao.i] = u.ao.offset;
67838 if( u.ao.zIdx[0]<0x80 ){
67839 u.ao.t = u.ao.zIdx[0];
67840 u.ao.zIdx++;
67841 }else{
67842 u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
67844 u.ao.aType[u.ao.i] = u.ao.t;
67845 u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
67846 u.ao.offset += u.ao.szField;
67847 if( u.ao.offset<u.ao.szField ){ /* True if u.ao.offset overflows */
67848 u.ao.zIdx = &u.ao.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
67849 break;
67851 }else{
67852 /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
67853 ** record than SetNumColumns indicated there are columns in the
67854 ** table. Set the u.ao.offset for any extra columns not present in
67855 ** the record to 0. This tells code below to store the default value
67856 ** for the column instead of deserializing a value from the record.
67858 u.ao.aOffset[u.ao.i] = 0;
67861 sqlite3VdbeMemRelease(&u.ao.sMem);
67862 u.ao.sMem.flags = MEM_Null;
67864 /* If we have read more header data than was contained in the header,
67865 ** or if the end of the last field appears to be past the end of the
67866 ** record, or if the end of the last field appears to be before the end
67867 ** of the record (when all fields present), then we must be dealing
67868 ** with a corrupt database.
67870 if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
67871 || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
67872 rc = SQLITE_CORRUPT_BKPT;
67873 goto op_column_out;
67877 /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
67878 ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
67879 ** then there are not enough fields in the record to satisfy the
67880 ** request. In this case, set the value NULL or to P4 if P4 is
67881 ** a pointer to a Mem object.
67883 if( u.ao.aOffset[u.ao.p2] ){
67884 assert( rc==SQLITE_OK );
67885 if( u.ao.zRec ){
67886 /* This is the common case where the whole row fits on a single page */
67887 VdbeMemRelease(u.ao.pDest);
67888 sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
67889 }else{
67890 /* This branch happens only when the row overflows onto multiple pages */
67891 u.ao.t = u.ao.aType[u.ao.p2];
67892 if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
67893 && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
67895 /* Content is irrelevant for the typeof() function and for
67896 ** the length(X) function if X is a blob. So we might as well use
67897 ** bogus content rather than reading content from disk. NULL works
67898 ** for text and blob and whatever is in the u.ao.payloadSize64 variable
67899 ** will work for everything else. */
67900 u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
67901 }else{
67902 u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
67903 sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
67904 rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len, u.ao.pC->isIndex,
67905 &u.ao.sMem);
67906 if( rc!=SQLITE_OK ){
67907 goto op_column_out;
67909 u.ao.zData = u.ao.sMem.z;
67911 sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
67913 u.ao.pDest->enc = encoding;
67914 }else{
67915 if( pOp->p4type==P4_MEM ){
67916 sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
67917 }else{
67918 MemSetTypeFlag(u.ao.pDest, MEM_Null);
67922 /* If we dynamically allocated space to hold the data (in the
67923 ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
67924 ** dynamically allocated space over to the u.ao.pDest structure.
67925 ** This prevents a memory copy.
67927 if( u.ao.sMem.zMalloc ){
67928 assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
67929 assert( !(u.ao.pDest->flags & MEM_Dyn) );
67930 assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
67931 u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
67932 u.ao.pDest->flags |= MEM_Term;
67933 u.ao.pDest->z = u.ao.sMem.z;
67934 u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
67937 rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
67939 op_column_out:
67940 UPDATE_MAX_BLOBSIZE(u.ao.pDest);
67941 REGISTER_TRACE(pOp->p3, u.ao.pDest);
67942 break;
67945 /* Opcode: Affinity P1 P2 * P4 *
67947 ** Apply affinities to a range of P2 registers starting with P1.
67949 ** P4 is a string that is P2 characters long. The nth character of the
67950 ** string indicates the column affinity that should be used for the nth
67951 ** memory cell in the range.
67953 case OP_Affinity: {
67954 #if 0 /* local variables moved into u.ap */
67955 const char *zAffinity; /* The affinity to be applied */
67956 char cAff; /* A single character of affinity */
67957 #endif /* local variables moved into u.ap */
67959 u.ap.zAffinity = pOp->p4.z;
67960 assert( u.ap.zAffinity!=0 );
67961 assert( u.ap.zAffinity[pOp->p2]==0 );
67962 pIn1 = &aMem[pOp->p1];
67963 while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
67964 assert( pIn1 <= &p->aMem[p->nMem] );
67965 assert( memIsValid(pIn1) );
67966 ExpandBlob(pIn1);
67967 applyAffinity(pIn1, u.ap.cAff, encoding);
67968 pIn1++;
67970 break;
67973 /* Opcode: MakeRecord P1 P2 P3 P4 *
67975 ** Convert P2 registers beginning with P1 into the [record format]
67976 ** use as a data record in a database table or as a key
67977 ** in an index. The OP_Column opcode can decode the record later.
67979 ** P4 may be a string that is P2 characters long. The nth character of the
67980 ** string indicates the column affinity that should be used for the nth
67981 ** field of the index key.
67983 ** The mapping from character to affinity is given by the SQLITE_AFF_
67984 ** macros defined in sqliteInt.h.
67986 ** If P4 is NULL then all index fields have the affinity NONE.
67988 case OP_MakeRecord: {
67989 #if 0 /* local variables moved into u.aq */
67990 u8 *zNewRecord; /* A buffer to hold the data for the new record */
67991 Mem *pRec; /* The new record */
67992 u64 nData; /* Number of bytes of data space */
67993 int nHdr; /* Number of bytes of header space */
67994 i64 nByte; /* Data space required for this record */
67995 int nZero; /* Number of zero bytes at the end of the record */
67996 int nVarint; /* Number of bytes in a varint */
67997 u32 serial_type; /* Type field */
67998 Mem *pData0; /* First field to be combined into the record */
67999 Mem *pLast; /* Last field of the record */
68000 int nField; /* Number of fields in the record */
68001 char *zAffinity; /* The affinity string for the record */
68002 int file_format; /* File format to use for encoding */
68003 int i; /* Space used in zNewRecord[] */
68004 int len; /* Length of a field */
68005 #endif /* local variables moved into u.aq */
68007 /* Assuming the record contains N fields, the record format looks
68008 ** like this:
68010 ** ------------------------------------------------------------------------
68011 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
68012 ** ------------------------------------------------------------------------
68014 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
68015 ** and so froth.
68017 ** Each type field is a varint representing the serial type of the
68018 ** corresponding data element (see sqlite3VdbeSerialType()). The
68019 ** hdr-size field is also a varint which is the offset from the beginning
68020 ** of the record to data0.
68022 u.aq.nData = 0; /* Number of bytes of data space */
68023 u.aq.nHdr = 0; /* Number of bytes of header space */
68024 u.aq.nZero = 0; /* Number of zero bytes at the end of the record */
68025 u.aq.nField = pOp->p1;
68026 u.aq.zAffinity = pOp->p4.z;
68027 assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=p->nMem+1 );
68028 u.aq.pData0 = &aMem[u.aq.nField];
68029 u.aq.nField = pOp->p2;
68030 u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
68031 u.aq.file_format = p->minWriteFileFormat;
68033 /* Identify the output register */
68034 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
68035 pOut = &aMem[pOp->p3];
68036 memAboutToChange(p, pOut);
68038 /* Loop through the elements that will make up the record to figure
68039 ** out how much space is required for the new record.
68041 for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
68042 assert( memIsValid(u.aq.pRec) );
68043 if( u.aq.zAffinity ){
68044 applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
68046 if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
68047 sqlite3VdbeMemExpandBlob(u.aq.pRec);
68049 u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
68050 u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
68051 u.aq.nData += u.aq.len;
68052 u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
68053 if( u.aq.pRec->flags & MEM_Zero ){
68054 /* Only pure zero-filled BLOBs can be input to this Opcode.
68055 ** We do not allow blobs with a prefix and a zero-filled tail. */
68056 u.aq.nZero += u.aq.pRec->u.nZero;
68057 }else if( u.aq.len ){
68058 u.aq.nZero = 0;
68062 /* Add the initial header varint and total the size */
68063 u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
68064 if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
68065 u.aq.nHdr++;
68067 u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
68068 if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
68069 goto too_big;
68072 /* Make sure the output register has a buffer large enough to store
68073 ** the new record. The output register (pOp->p3) is not allowed to
68074 ** be one of the input registers (because the following call to
68075 ** sqlite3VdbeMemGrow() could clobber the value before it is used).
68077 if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
68078 goto no_mem;
68080 u.aq.zNewRecord = (u8 *)pOut->z;
68082 /* Write the record */
68083 u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
68084 for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
68085 u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
68086 u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type); /* serial type */
68088 for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ /* serial data */
68089 u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
68091 assert( u.aq.i==u.aq.nByte );
68093 assert( pOp->p3>0 && pOp->p3<=p->nMem );
68094 pOut->n = (int)u.aq.nByte;
68095 pOut->flags = MEM_Blob | MEM_Dyn;
68096 pOut->xDel = 0;
68097 if( u.aq.nZero ){
68098 pOut->u.nZero = u.aq.nZero;
68099 pOut->flags |= MEM_Zero;
68101 pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
68102 REGISTER_TRACE(pOp->p3, pOut);
68103 UPDATE_MAX_BLOBSIZE(pOut);
68104 break;
68107 /* Opcode: Count P1 P2 * * *
68109 ** Store the number of entries (an integer value) in the table or index
68110 ** opened by cursor P1 in register P2
68112 #ifndef SQLITE_OMIT_BTREECOUNT
68113 case OP_Count: { /* out2-prerelease */
68114 #if 0 /* local variables moved into u.ar */
68115 i64 nEntry;
68116 BtCursor *pCrsr;
68117 #endif /* local variables moved into u.ar */
68119 u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
68120 if( ALWAYS(u.ar.pCrsr) ){
68121 rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
68122 }else{
68123 u.ar.nEntry = 0;
68125 pOut->u.i = u.ar.nEntry;
68126 break;
68128 #endif
68130 /* Opcode: Savepoint P1 * * P4 *
68132 ** Open, release or rollback the savepoint named by parameter P4, depending
68133 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
68134 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
68136 case OP_Savepoint: {
68137 #if 0 /* local variables moved into u.as */
68138 int p1; /* Value of P1 operand */
68139 char *zName; /* Name of savepoint */
68140 int nName;
68141 Savepoint *pNew;
68142 Savepoint *pSavepoint;
68143 Savepoint *pTmp;
68144 int iSavepoint;
68145 int ii;
68146 #endif /* local variables moved into u.as */
68148 u.as.p1 = pOp->p1;
68149 u.as.zName = pOp->p4.z;
68151 /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
68152 ** transaction, then there cannot be any savepoints.
68154 assert( db->pSavepoint==0 || db->autoCommit==0 );
68155 assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
68156 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
68157 assert( checkSavepointCount(db) );
68158 assert( p->bIsReader );
68160 if( u.as.p1==SAVEPOINT_BEGIN ){
68161 if( db->nVdbeWrite>0 ){
68162 /* A new savepoint cannot be created if there are active write
68163 ** statements (i.e. open read/write incremental blob handles).
68165 sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
68166 "SQL statements in progress");
68167 rc = SQLITE_BUSY;
68168 }else{
68169 u.as.nName = sqlite3Strlen30(u.as.zName);
68171 #ifndef SQLITE_OMIT_VIRTUALTABLE
68172 /* This call is Ok even if this savepoint is actually a transaction
68173 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
68174 ** If this is a transaction savepoint being opened, it is guaranteed
68175 ** that the db->aVTrans[] array is empty. */
68176 assert( db->autoCommit==0 || db->nVTrans==0 );
68177 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
68178 db->nStatement+db->nSavepoint);
68179 if( rc!=SQLITE_OK ) goto abort_due_to_error;
68180 #endif
68182 /* Create a new savepoint structure. */
68183 u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
68184 if( u.as.pNew ){
68185 u.as.pNew->zName = (char *)&u.as.pNew[1];
68186 memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
68188 /* If there is no open transaction, then mark this as a special
68189 ** "transaction savepoint". */
68190 if( db->autoCommit ){
68191 db->autoCommit = 0;
68192 db->isTransactionSavepoint = 1;
68193 }else{
68194 db->nSavepoint++;
68197 /* Link the new savepoint into the database handle's list. */
68198 u.as.pNew->pNext = db->pSavepoint;
68199 db->pSavepoint = u.as.pNew;
68200 u.as.pNew->nDeferredCons = db->nDeferredCons;
68201 u.as.pNew->nDeferredImmCons = db->nDeferredImmCons;
68204 }else{
68205 u.as.iSavepoint = 0;
68207 /* Find the named savepoint. If there is no such savepoint, then an
68208 ** an error is returned to the user. */
68209 for(
68210 u.as.pSavepoint = db->pSavepoint;
68211 u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
68212 u.as.pSavepoint = u.as.pSavepoint->pNext
68214 u.as.iSavepoint++;
68216 if( !u.as.pSavepoint ){
68217 sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
68218 rc = SQLITE_ERROR;
68219 }else if( db->nVdbeWrite>0 && u.as.p1==SAVEPOINT_RELEASE ){
68220 /* It is not possible to release (commit) a savepoint if there are
68221 ** active write statements.
68223 sqlite3SetString(&p->zErrMsg, db,
68224 "cannot release savepoint - SQL statements in progress"
68226 rc = SQLITE_BUSY;
68227 }else{
68229 /* Determine whether or not this is a transaction savepoint. If so,
68230 ** and this is a RELEASE command, then the current transaction
68231 ** is committed.
68233 int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
68234 if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
68235 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
68236 goto vdbe_return;
68238 db->autoCommit = 1;
68239 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
68240 p->pc = pc;
68241 db->autoCommit = 0;
68242 p->rc = rc = SQLITE_BUSY;
68243 goto vdbe_return;
68245 db->isTransactionSavepoint = 0;
68246 rc = p->rc;
68247 }else{
68248 u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
68249 if( u.as.p1==SAVEPOINT_ROLLBACK ){
68250 for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
68251 sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
68254 for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
68255 rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
68256 if( rc!=SQLITE_OK ){
68257 goto abort_due_to_error;
68260 if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
68261 sqlite3ExpirePreparedStatements(db);
68262 sqlite3ResetAllSchemasOfConnection(db);
68263 db->flags = (db->flags | SQLITE_InternChanges);
68267 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
68268 ** savepoints nested inside of the savepoint being operated on. */
68269 while( db->pSavepoint!=u.as.pSavepoint ){
68270 u.as.pTmp = db->pSavepoint;
68271 db->pSavepoint = u.as.pTmp->pNext;
68272 sqlite3DbFree(db, u.as.pTmp);
68273 db->nSavepoint--;
68276 /* If it is a RELEASE, then destroy the savepoint being operated on
68277 ** too. If it is a ROLLBACK TO, then set the number of deferred
68278 ** constraint violations present in the database to the value stored
68279 ** when the savepoint was created. */
68280 if( u.as.p1==SAVEPOINT_RELEASE ){
68281 assert( u.as.pSavepoint==db->pSavepoint );
68282 db->pSavepoint = u.as.pSavepoint->pNext;
68283 sqlite3DbFree(db, u.as.pSavepoint);
68284 if( !isTransaction ){
68285 db->nSavepoint--;
68287 }else{
68288 db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
68289 db->nDeferredImmCons = u.as.pSavepoint->nDeferredImmCons;
68292 if( !isTransaction ){
68293 rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
68294 if( rc!=SQLITE_OK ) goto abort_due_to_error;
68299 break;
68302 /* Opcode: AutoCommit P1 P2 * * *
68304 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
68305 ** back any currently active btree transactions. If there are any active
68306 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
68307 ** there are active writing VMs or active VMs that use shared cache.
68309 ** This instruction causes the VM to halt.
68311 case OP_AutoCommit: {
68312 #if 0 /* local variables moved into u.at */
68313 int desiredAutoCommit;
68314 int iRollback;
68315 int turnOnAC;
68316 #endif /* local variables moved into u.at */
68318 u.at.desiredAutoCommit = pOp->p1;
68319 u.at.iRollback = pOp->p2;
68320 u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
68321 assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
68322 assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
68323 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
68324 assert( p->bIsReader );
68326 #if 0
68327 if( u.at.turnOnAC && u.at.iRollback && db->nVdbeActive>1 ){
68328 /* If this instruction implements a ROLLBACK and other VMs are
68329 ** still running, and a transaction is active, return an error indicating
68330 ** that the other VMs must complete first.
68332 sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
68333 "SQL statements in progress");
68334 rc = SQLITE_BUSY;
68335 }else
68336 #endif
68337 if( u.at.turnOnAC && !u.at.iRollback && db->nVdbeWrite>0 ){
68338 /* If this instruction implements a COMMIT and other VMs are writing
68339 ** return an error indicating that the other VMs must complete first.
68341 sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
68342 "SQL statements in progress");
68343 rc = SQLITE_BUSY;
68344 }else if( u.at.desiredAutoCommit!=db->autoCommit ){
68345 if( u.at.iRollback ){
68346 assert( u.at.desiredAutoCommit==1 );
68347 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
68348 db->autoCommit = 1;
68349 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
68350 goto vdbe_return;
68351 }else{
68352 db->autoCommit = (u8)u.at.desiredAutoCommit;
68353 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
68354 p->pc = pc;
68355 db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
68356 p->rc = rc = SQLITE_BUSY;
68357 goto vdbe_return;
68360 assert( db->nStatement==0 );
68361 sqlite3CloseSavepoints(db);
68362 if( p->rc==SQLITE_OK ){
68363 rc = SQLITE_DONE;
68364 }else{
68365 rc = SQLITE_ERROR;
68367 goto vdbe_return;
68368 }else{
68369 sqlite3SetString(&p->zErrMsg, db,
68370 (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
68371 (u.at.iRollback)?"cannot rollback - no transaction is active":
68372 "cannot commit - no transaction is active"));
68374 rc = SQLITE_ERROR;
68376 break;
68379 /* Opcode: Transaction P1 P2 * * *
68381 ** Begin a transaction. The transaction ends when a Commit or Rollback
68382 ** opcode is encountered. Depending on the ON CONFLICT setting, the
68383 ** transaction might also be rolled back if an error is encountered.
68385 ** P1 is the index of the database file on which the transaction is
68386 ** started. Index 0 is the main database file and index 1 is the
68387 ** file used for temporary tables. Indices of 2 or more are used for
68388 ** attached databases.
68390 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
68391 ** obtained on the database file when a write-transaction is started. No
68392 ** other process can start another write transaction while this transaction is
68393 ** underway. Starting a write transaction also creates a rollback journal. A
68394 ** write transaction must be started before any changes can be made to the
68395 ** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
68396 ** also obtained on the file.
68398 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
68399 ** true (this flag is set if the Vdbe may modify more than one row and may
68400 ** throw an ABORT exception), a statement transaction may also be opened.
68401 ** More specifically, a statement transaction is opened iff the database
68402 ** connection is currently not in autocommit mode, or if there are other
68403 ** active statements. A statement transaction allows the changes made by this
68404 ** VDBE to be rolled back after an error without having to roll back the
68405 ** entire transaction. If no error is encountered, the statement transaction
68406 ** will automatically commit when the VDBE halts.
68408 ** If P2 is zero, then a read-lock is obtained on the database file.
68410 case OP_Transaction: {
68411 #if 0 /* local variables moved into u.au */
68412 Btree *pBt;
68413 #endif /* local variables moved into u.au */
68415 assert( p->bIsReader );
68416 assert( p->readOnly==0 || pOp->p2==0 );
68417 assert( pOp->p1>=0 && pOp->p1<db->nDb );
68418 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68419 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
68420 rc = SQLITE_READONLY;
68421 goto abort_due_to_error;
68423 u.au.pBt = db->aDb[pOp->p1].pBt;
68425 if( u.au.pBt ){
68426 rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
68427 if( rc==SQLITE_BUSY ){
68428 p->pc = pc;
68429 p->rc = rc = SQLITE_BUSY;
68430 goto vdbe_return;
68432 if( rc!=SQLITE_OK ){
68433 goto abort_due_to_error;
68436 if( pOp->p2 && p->usesStmtJournal
68437 && (db->autoCommit==0 || db->nVdbeRead>1)
68439 assert( sqlite3BtreeIsInTrans(u.au.pBt) );
68440 if( p->iStatement==0 ){
68441 assert( db->nStatement>=0 && db->nSavepoint>=0 );
68442 db->nStatement++;
68443 p->iStatement = db->nSavepoint + db->nStatement;
68446 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
68447 if( rc==SQLITE_OK ){
68448 rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
68451 /* Store the current value of the database handles deferred constraint
68452 ** counter. If the statement transaction needs to be rolled back,
68453 ** the value of this counter needs to be restored too. */
68454 p->nStmtDefCons = db->nDeferredCons;
68455 p->nStmtDefImmCons = db->nDeferredImmCons;
68458 break;
68461 /* Opcode: ReadCookie P1 P2 P3 * *
68463 ** Read cookie number P3 from database P1 and write it into register P2.
68464 ** P3==1 is the schema version. P3==2 is the database format.
68465 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
68466 ** the main database file and P1==1 is the database file used to store
68467 ** temporary tables.
68469 ** There must be a read-lock on the database (either a transaction
68470 ** must be started or there must be an open cursor) before
68471 ** executing this instruction.
68473 case OP_ReadCookie: { /* out2-prerelease */
68474 #if 0 /* local variables moved into u.av */
68475 int iMeta;
68476 int iDb;
68477 int iCookie;
68478 #endif /* local variables moved into u.av */
68480 assert( p->bIsReader );
68481 u.av.iDb = pOp->p1;
68482 u.av.iCookie = pOp->p3;
68483 assert( pOp->p3<SQLITE_N_BTREE_META );
68484 assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
68485 assert( db->aDb[u.av.iDb].pBt!=0 );
68486 assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
68488 sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
68489 pOut->u.i = u.av.iMeta;
68490 break;
68493 /* Opcode: SetCookie P1 P2 P3 * *
68495 ** Write the content of register P3 (interpreted as an integer)
68496 ** into cookie number P2 of database P1. P2==1 is the schema version.
68497 ** P2==2 is the database format. P2==3 is the recommended pager cache
68498 ** size, and so forth. P1==0 is the main database file and P1==1 is the
68499 ** database file used to store temporary tables.
68501 ** A transaction must be started before executing this opcode.
68503 case OP_SetCookie: { /* in3 */
68504 #if 0 /* local variables moved into u.aw */
68505 Db *pDb;
68506 #endif /* local variables moved into u.aw */
68507 assert( pOp->p2<SQLITE_N_BTREE_META );
68508 assert( pOp->p1>=0 && pOp->p1<db->nDb );
68509 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68510 assert( p->readOnly==0 );
68511 u.aw.pDb = &db->aDb[pOp->p1];
68512 assert( u.aw.pDb->pBt!=0 );
68513 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
68514 pIn3 = &aMem[pOp->p3];
68515 sqlite3VdbeMemIntegerify(pIn3);
68516 /* See note about index shifting on OP_ReadCookie */
68517 rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
68518 if( pOp->p2==BTREE_SCHEMA_VERSION ){
68519 /* When the schema cookie changes, record the new cookie internally */
68520 u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
68521 db->flags |= SQLITE_InternChanges;
68522 }else if( pOp->p2==BTREE_FILE_FORMAT ){
68523 /* Record changes in the file format */
68524 u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
68526 if( pOp->p1==1 ){
68527 /* Invalidate all prepared statements whenever the TEMP database
68528 ** schema is changed. Ticket #1644 */
68529 sqlite3ExpirePreparedStatements(db);
68530 p->expired = 0;
68532 break;
68535 /* Opcode: VerifyCookie P1 P2 P3 * *
68537 ** Check the value of global database parameter number 0 (the
68538 ** schema version) and make sure it is equal to P2 and that the
68539 ** generation counter on the local schema parse equals P3.
68541 ** P1 is the database number which is 0 for the main database file
68542 ** and 1 for the file holding temporary tables and some higher number
68543 ** for auxiliary databases.
68545 ** The cookie changes its value whenever the database schema changes.
68546 ** This operation is used to detect when that the cookie has changed
68547 ** and that the current process needs to reread the schema.
68549 ** Either a transaction needs to have been started or an OP_Open needs
68550 ** to be executed (to establish a read lock) before this opcode is
68551 ** invoked.
68553 case OP_VerifyCookie: {
68554 #if 0 /* local variables moved into u.ax */
68555 int iMeta;
68556 int iGen;
68557 Btree *pBt;
68558 #endif /* local variables moved into u.ax */
68560 assert( pOp->p1>=0 && pOp->p1<db->nDb );
68561 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68562 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
68563 assert( p->bIsReader );
68564 u.ax.pBt = db->aDb[pOp->p1].pBt;
68565 if( u.ax.pBt ){
68566 sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
68567 u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
68568 }else{
68569 u.ax.iGen = u.ax.iMeta = 0;
68571 if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
68572 sqlite3DbFree(db, p->zErrMsg);
68573 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
68574 /* If the schema-cookie from the database file matches the cookie
68575 ** stored with the in-memory representation of the schema, do
68576 ** not reload the schema from the database file.
68578 ** If virtual-tables are in use, this is not just an optimization.
68579 ** Often, v-tables store their data in other SQLite tables, which
68580 ** are queried from within xNext() and other v-table methods using
68581 ** prepared queries. If such a query is out-of-date, we do not want to
68582 ** discard the database schema, as the user code implementing the
68583 ** v-table would have to be ready for the sqlite3_vtab structure itself
68584 ** to be invalidated whenever sqlite3_step() is called from within
68585 ** a v-table method.
68587 if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
68588 sqlite3ResetOneSchema(db, pOp->p1);
68591 p->expired = 1;
68592 rc = SQLITE_SCHEMA;
68594 break;
68597 /* Opcode: OpenRead P1 P2 P3 P4 P5
68599 ** Open a read-only cursor for the database table whose root page is
68600 ** P2 in a database file. The database file is determined by P3.
68601 ** P3==0 means the main database, P3==1 means the database used for
68602 ** temporary tables, and P3>1 means used the corresponding attached
68603 ** database. Give the new cursor an identifier of P1. The P1
68604 ** values need not be contiguous but all P1 values should be small integers.
68605 ** It is an error for P1 to be negative.
68607 ** If P5!=0 then use the content of register P2 as the root page, not
68608 ** the value of P2 itself.
68610 ** There will be a read lock on the database whenever there is an
68611 ** open cursor. If the database was unlocked prior to this instruction
68612 ** then a read lock is acquired as part of this instruction. A read
68613 ** lock allows other processes to read the database but prohibits
68614 ** any other process from modifying the database. The read lock is
68615 ** released when all cursors are closed. If this instruction attempts
68616 ** to get a read lock but fails, the script terminates with an
68617 ** SQLITE_BUSY error code.
68619 ** The P4 value may be either an integer (P4_INT32) or a pointer to
68620 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
68621 ** structure, then said structure defines the content and collating
68622 ** sequence of the index being opened. Otherwise, if P4 is an integer
68623 ** value, it is set to the number of columns in the table.
68625 ** See also OpenWrite.
68627 /* Opcode: OpenWrite P1 P2 P3 P4 P5
68629 ** Open a read/write cursor named P1 on the table or index whose root
68630 ** page is P2. Or if P5!=0 use the content of register P2 to find the
68631 ** root page.
68633 ** The P4 value may be either an integer (P4_INT32) or a pointer to
68634 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
68635 ** structure, then said structure defines the content and collating
68636 ** sequence of the index being opened. Otherwise, if P4 is an integer
68637 ** value, it is set to the number of columns in the table, or to the
68638 ** largest index of any column of the table that is actually used.
68640 ** This instruction works just like OpenRead except that it opens the cursor
68641 ** in read/write mode. For a given table, there can be one or more read-only
68642 ** cursors or a single read/write cursor but not both.
68644 ** See also OpenRead.
68646 case OP_OpenRead:
68647 case OP_OpenWrite: {
68648 #if 0 /* local variables moved into u.ay */
68649 int nField;
68650 KeyInfo *pKeyInfo;
68651 int p2;
68652 int iDb;
68653 int wrFlag;
68654 Btree *pX;
68655 VdbeCursor *pCur;
68656 Db *pDb;
68657 #endif /* local variables moved into u.ay */
68659 assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
68660 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
68661 assert( p->bIsReader );
68662 assert( pOp->opcode==OP_OpenRead || p->readOnly==0 );
68664 if( p->expired ){
68665 rc = SQLITE_ABORT;
68666 break;
68669 u.ay.nField = 0;
68670 u.ay.pKeyInfo = 0;
68671 u.ay.p2 = pOp->p2;
68672 u.ay.iDb = pOp->p3;
68673 assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
68674 assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
68675 u.ay.pDb = &db->aDb[u.ay.iDb];
68676 u.ay.pX = u.ay.pDb->pBt;
68677 assert( u.ay.pX!=0 );
68678 if( pOp->opcode==OP_OpenWrite ){
68679 u.ay.wrFlag = 1;
68680 assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
68681 if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
68682 p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
68684 }else{
68685 u.ay.wrFlag = 0;
68687 if( pOp->p5 & OPFLAG_P2ISREG ){
68688 assert( u.ay.p2>0 );
68689 assert( u.ay.p2<=p->nMem );
68690 pIn2 = &aMem[u.ay.p2];
68691 assert( memIsValid(pIn2) );
68692 assert( (pIn2->flags & MEM_Int)!=0 );
68693 sqlite3VdbeMemIntegerify(pIn2);
68694 u.ay.p2 = (int)pIn2->u.i;
68695 /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
68696 ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
68697 ** If there were a failure, the prepared statement would have halted
68698 ** before reaching this instruction. */
68699 if( NEVER(u.ay.p2<2) ) {
68700 rc = SQLITE_CORRUPT_BKPT;
68701 goto abort_due_to_error;
68704 if( pOp->p4type==P4_KEYINFO ){
68705 u.ay.pKeyInfo = pOp->p4.pKeyInfo;
68706 u.ay.pKeyInfo->enc = ENC(p->db);
68707 u.ay.nField = u.ay.pKeyInfo->nField+1;
68708 }else if( pOp->p4type==P4_INT32 ){
68709 u.ay.nField = pOp->p4.i;
68711 assert( pOp->p1>=0 );
68712 u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
68713 if( u.ay.pCur==0 ) goto no_mem;
68714 u.ay.pCur->nullRow = 1;
68715 u.ay.pCur->isOrdered = 1;
68716 rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
68717 u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
68718 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
68719 sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
68721 /* Since it performs no memory allocation or IO, the only value that
68722 ** sqlite3BtreeCursor() may return is SQLITE_OK. */
68723 assert( rc==SQLITE_OK );
68725 /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
68726 ** SQLite used to check if the root-page flags were sane at this point
68727 ** and report database corruption if they were not, but this check has
68728 ** since moved into the btree layer. */
68729 u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
68730 u.ay.pCur->isIndex = !u.ay.pCur->isTable;
68731 break;
68734 /* Opcode: OpenEphemeral P1 P2 * P4 P5
68736 ** Open a new cursor P1 to a transient table.
68737 ** The cursor is always opened read/write even if
68738 ** the main database is read-only. The ephemeral
68739 ** table is deleted automatically when the cursor is closed.
68741 ** P2 is the number of columns in the ephemeral table.
68742 ** The cursor points to a BTree table if P4==0 and to a BTree index
68743 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
68744 ** that defines the format of keys in the index.
68746 ** This opcode was once called OpenTemp. But that created
68747 ** confusion because the term "temp table", might refer either
68748 ** to a TEMP table at the SQL level, or to a table opened by
68749 ** this opcode. Then this opcode was call OpenVirtual. But
68750 ** that created confusion with the whole virtual-table idea.
68752 ** The P5 parameter can be a mask of the BTREE_* flags defined
68753 ** in btree.h. These flags control aspects of the operation of
68754 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
68755 ** added automatically.
68757 /* Opcode: OpenAutoindex P1 P2 * P4 *
68759 ** This opcode works the same as OP_OpenEphemeral. It has a
68760 ** different name to distinguish its use. Tables created using
68761 ** by this opcode will be used for automatically created transient
68762 ** indices in joins.
68764 case OP_OpenAutoindex:
68765 case OP_OpenEphemeral: {
68766 #if 0 /* local variables moved into u.az */
68767 VdbeCursor *pCx;
68768 #endif /* local variables moved into u.az */
68769 static const int vfsFlags =
68770 SQLITE_OPEN_READWRITE |
68771 SQLITE_OPEN_CREATE |
68772 SQLITE_OPEN_EXCLUSIVE |
68773 SQLITE_OPEN_DELETEONCLOSE |
68774 SQLITE_OPEN_TRANSIENT_DB;
68776 assert( pOp->p1>=0 );
68777 u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68778 if( u.az.pCx==0 ) goto no_mem;
68779 u.az.pCx->nullRow = 1;
68780 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
68781 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
68782 if( rc==SQLITE_OK ){
68783 rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
68785 if( rc==SQLITE_OK ){
68786 /* If a transient index is required, create it by calling
68787 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
68788 ** opening it. If a transient table is required, just use the
68789 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
68791 if( pOp->p4.pKeyInfo ){
68792 int pgno;
68793 assert( pOp->p4type==P4_KEYINFO );
68794 rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
68795 if( rc==SQLITE_OK ){
68796 assert( pgno==MASTER_ROOT+1 );
68797 rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
68798 (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
68799 u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68800 u.az.pCx->pKeyInfo->enc = ENC(p->db);
68802 u.az.pCx->isTable = 0;
68803 }else{
68804 rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
68805 u.az.pCx->isTable = 1;
68808 u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
68809 u.az.pCx->isIndex = !u.az.pCx->isTable;
68810 break;
68813 /* Opcode: SorterOpen P1 P2 * P4 *
68815 ** This opcode works like OP_OpenEphemeral except that it opens
68816 ** a transient index that is specifically designed to sort large
68817 ** tables using an external merge-sort algorithm.
68819 case OP_SorterOpen: {
68820 #if 0 /* local variables moved into u.ba */
68821 VdbeCursor *pCx;
68822 #endif /* local variables moved into u.ba */
68824 u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68825 if( u.ba.pCx==0 ) goto no_mem;
68826 u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68827 u.ba.pCx->pKeyInfo->enc = ENC(p->db);
68828 u.ba.pCx->isSorter = 1;
68829 rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
68830 break;
68833 /* Opcode: OpenPseudo P1 P2 P3 * P5
68835 ** Open a new cursor that points to a fake table that contains a single
68836 ** row of data. The content of that one row in the content of memory
68837 ** register P2 when P5==0. In other words, cursor P1 becomes an alias for the
68838 ** MEM_Blob content contained in register P2. When P5==1, then the
68839 ** row is represented by P3 consecutive registers beginning with P2.
68841 ** A pseudo-table created by this opcode is used to hold a single
68842 ** row output from the sorter so that the row can be decomposed into
68843 ** individual columns using the OP_Column opcode. The OP_Column opcode
68844 ** is the only cursor opcode that works with a pseudo-table.
68846 ** P3 is the number of fields in the records that will be stored by
68847 ** the pseudo-table.
68849 case OP_OpenPseudo: {
68850 #if 0 /* local variables moved into u.bb */
68851 VdbeCursor *pCx;
68852 #endif /* local variables moved into u.bb */
68854 assert( pOp->p1>=0 );
68855 u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
68856 if( u.bb.pCx==0 ) goto no_mem;
68857 u.bb.pCx->nullRow = 1;
68858 u.bb.pCx->pseudoTableReg = pOp->p2;
68859 u.bb.pCx->isTable = 1;
68860 u.bb.pCx->isIndex = 0;
68861 u.bb.pCx->multiPseudo = pOp->p5;
68862 break;
68865 /* Opcode: Close P1 * * * *
68867 ** Close a cursor previously opened as P1. If P1 is not
68868 ** currently open, this instruction is a no-op.
68870 case OP_Close: {
68871 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68872 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
68873 p->apCsr[pOp->p1] = 0;
68874 break;
68877 /* Opcode: SeekGe P1 P2 P3 P4 *
68879 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68880 ** use the value in register P3 as the key. If cursor P1 refers
68881 ** to an SQL index, then P3 is the first in an array of P4 registers
68882 ** that are used as an unpacked index key.
68884 ** Reposition cursor P1 so that it points to the smallest entry that
68885 ** is greater than or equal to the key value. If there are no records
68886 ** greater than or equal to the key and P2 is not zero, then jump to P2.
68888 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
68890 /* Opcode: SeekGt P1 P2 P3 P4 *
68892 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68893 ** use the value in register P3 as a key. If cursor P1 refers
68894 ** to an SQL index, then P3 is the first in an array of P4 registers
68895 ** that are used as an unpacked index key.
68897 ** Reposition cursor P1 so that it points to the smallest entry that
68898 ** is greater than the key value. If there are no records greater than
68899 ** the key and P2 is not zero, then jump to P2.
68901 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
68903 /* Opcode: SeekLt P1 P2 P3 P4 *
68905 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68906 ** use the value in register P3 as a key. If cursor P1 refers
68907 ** to an SQL index, then P3 is the first in an array of P4 registers
68908 ** that are used as an unpacked index key.
68910 ** Reposition cursor P1 so that it points to the largest entry that
68911 ** is less than the key value. If there are no records less than
68912 ** the key and P2 is not zero, then jump to P2.
68914 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
68916 /* Opcode: SeekLe P1 P2 P3 P4 *
68918 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68919 ** use the value in register P3 as a key. If cursor P1 refers
68920 ** to an SQL index, then P3 is the first in an array of P4 registers
68921 ** that are used as an unpacked index key.
68923 ** Reposition cursor P1 so that it points to the largest entry that
68924 ** is less than or equal to the key value. If there are no records
68925 ** less than or equal to the key and P2 is not zero, then jump to P2.
68927 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
68929 case OP_SeekLt: /* jump, in3 */
68930 case OP_SeekLe: /* jump, in3 */
68931 case OP_SeekGe: /* jump, in3 */
68932 case OP_SeekGt: { /* jump, in3 */
68933 #if 0 /* local variables moved into u.bc */
68934 int res;
68935 int oc;
68936 VdbeCursor *pC;
68937 UnpackedRecord r;
68938 int nField;
68939 i64 iKey; /* The rowid we are to seek to */
68940 #endif /* local variables moved into u.bc */
68942 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68943 assert( pOp->p2!=0 );
68944 u.bc.pC = p->apCsr[pOp->p1];
68945 assert( u.bc.pC!=0 );
68946 assert( u.bc.pC->pseudoTableReg==0 );
68947 assert( OP_SeekLe == OP_SeekLt+1 );
68948 assert( OP_SeekGe == OP_SeekLt+2 );
68949 assert( OP_SeekGt == OP_SeekLt+3 );
68950 assert( u.bc.pC->isOrdered );
68951 if( ALWAYS(u.bc.pC->pCursor!=0) ){
68952 u.bc.oc = pOp->opcode;
68953 u.bc.pC->nullRow = 0;
68954 if( u.bc.pC->isTable ){
68955 /* The input value in P3 might be of any type: integer, real, string,
68956 ** blob, or NULL. But it needs to be an integer before we can do
68957 ** the seek, so covert it. */
68958 pIn3 = &aMem[pOp->p3];
68959 applyNumericAffinity(pIn3);
68960 u.bc.iKey = sqlite3VdbeIntValue(pIn3);
68961 u.bc.pC->rowidIsValid = 0;
68963 /* If the P3 value could not be converted into an integer without
68964 ** loss of information, then special processing is required... */
68965 if( (pIn3->flags & MEM_Int)==0 ){
68966 if( (pIn3->flags & MEM_Real)==0 ){
68967 /* If the P3 value cannot be converted into any kind of a number,
68968 ** then the seek is not possible, so jump to P2 */
68969 pc = pOp->p2 - 1;
68970 break;
68972 /* If we reach this point, then the P3 value must be a floating
68973 ** point number. */
68974 assert( (pIn3->flags & MEM_Real)!=0 );
68976 if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
68977 /* The P3 value is too large in magnitude to be expressed as an
68978 ** integer. */
68979 u.bc.res = 1;
68980 if( pIn3->r<0 ){
68981 if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
68982 rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
68983 if( rc!=SQLITE_OK ) goto abort_due_to_error;
68985 }else{
68986 if( u.bc.oc<=OP_SeekLe ){ assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
68987 rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
68988 if( rc!=SQLITE_OK ) goto abort_due_to_error;
68991 if( u.bc.res ){
68992 pc = pOp->p2 - 1;
68994 break;
68995 }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
68996 /* Use the ceiling() function to convert real->int */
68997 if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
68998 }else{
68999 /* Use the floor() function to convert real->int */
69000 assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
69001 if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
69004 rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
69005 if( rc!=SQLITE_OK ){
69006 goto abort_due_to_error;
69008 if( u.bc.res==0 ){
69009 u.bc.pC->rowidIsValid = 1;
69010 u.bc.pC->lastRowid = u.bc.iKey;
69012 }else{
69013 u.bc.nField = pOp->p4.i;
69014 assert( pOp->p4type==P4_INT32 );
69015 assert( u.bc.nField>0 );
69016 u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
69017 u.bc.r.nField = (u16)u.bc.nField;
69019 /* The next line of code computes as follows, only faster:
69020 ** if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
69021 ** u.bc.r.flags = UNPACKED_INCRKEY;
69022 ** }else{
69023 ** u.bc.r.flags = 0;
69024 ** }
69026 u.bc.r.flags = (u8)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
69027 assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
69028 assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
69029 assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
69030 assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
69032 u.bc.r.aMem = &aMem[pOp->p3];
69033 #ifdef SQLITE_DEBUG
69034 { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
69035 #endif
69036 ExpandBlob(u.bc.r.aMem);
69037 rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
69038 if( rc!=SQLITE_OK ){
69039 goto abort_due_to_error;
69041 u.bc.pC->rowidIsValid = 0;
69043 u.bc.pC->deferredMoveto = 0;
69044 u.bc.pC->cacheStatus = CACHE_STALE;
69045 #ifdef SQLITE_TEST
69046 sqlite3_search_count++;
69047 #endif
69048 if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
69049 if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
69050 rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
69051 if( rc!=SQLITE_OK ) goto abort_due_to_error;
69052 u.bc.pC->rowidIsValid = 0;
69053 }else{
69054 u.bc.res = 0;
69056 }else{
69057 assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
69058 if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
69059 rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
69060 if( rc!=SQLITE_OK ) goto abort_due_to_error;
69061 u.bc.pC->rowidIsValid = 0;
69062 }else{
69063 /* u.bc.res might be negative because the table is empty. Check to
69064 ** see if this is the case.
69066 u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
69069 assert( pOp->p2>0 );
69070 if( u.bc.res ){
69071 pc = pOp->p2 - 1;
69073 }else{
69074 /* This happens when attempting to open the sqlite3_master table
69075 ** for read access returns SQLITE_EMPTY. In this case always
69076 ** take the jump (since there are no records in the table).
69078 pc = pOp->p2 - 1;
69080 break;
69083 /* Opcode: Seek P1 P2 * * *
69085 ** P1 is an open table cursor and P2 is a rowid integer. Arrange
69086 ** for P1 to move so that it points to the rowid given by P2.
69088 ** This is actually a deferred seek. Nothing actually happens until
69089 ** the cursor is used to read a record. That way, if no reads
69090 ** occur, no unnecessary I/O happens.
69092 case OP_Seek: { /* in2 */
69093 #if 0 /* local variables moved into u.bd */
69094 VdbeCursor *pC;
69095 #endif /* local variables moved into u.bd */
69097 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69098 u.bd.pC = p->apCsr[pOp->p1];
69099 assert( u.bd.pC!=0 );
69100 if( ALWAYS(u.bd.pC->pCursor!=0) ){
69101 assert( u.bd.pC->isTable );
69102 u.bd.pC->nullRow = 0;
69103 pIn2 = &aMem[pOp->p2];
69104 u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
69105 u.bd.pC->rowidIsValid = 0;
69106 u.bd.pC->deferredMoveto = 1;
69108 break;
69112 /* Opcode: Found P1 P2 P3 P4 *
69114 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
69115 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
69116 ** record.
69118 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
69119 ** is a prefix of any entry in P1 then a jump is made to P2 and
69120 ** P1 is left pointing at the matching entry.
69122 /* Opcode: NotFound P1 P2 P3 P4 *
69124 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
69125 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
69126 ** record.
69128 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
69129 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
69130 ** does contain an entry whose prefix matches the P3/P4 record then control
69131 ** falls through to the next instruction and P1 is left pointing at the
69132 ** matching entry.
69134 ** See also: Found, NotExists, IsUnique
69136 case OP_NotFound: /* jump, in3 */
69137 case OP_Found: { /* jump, in3 */
69138 #if 0 /* local variables moved into u.be */
69139 int alreadyExists;
69140 VdbeCursor *pC;
69141 int res;
69142 char *pFree;
69143 UnpackedRecord *pIdxKey;
69144 UnpackedRecord r;
69145 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
69146 #endif /* local variables moved into u.be */
69148 #ifdef SQLITE_TEST
69149 sqlite3_found_count++;
69150 #endif
69152 u.be.alreadyExists = 0;
69153 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69154 assert( pOp->p4type==P4_INT32 );
69155 u.be.pC = p->apCsr[pOp->p1];
69156 assert( u.be.pC!=0 );
69157 pIn3 = &aMem[pOp->p3];
69158 if( ALWAYS(u.be.pC->pCursor!=0) ){
69160 assert( u.be.pC->isTable==0 );
69161 if( pOp->p4.i>0 ){
69162 u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
69163 u.be.r.nField = (u16)pOp->p4.i;
69164 u.be.r.aMem = pIn3;
69165 #ifdef SQLITE_DEBUG
69166 { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
69167 #endif
69168 u.be.r.flags = UNPACKED_PREFIX_MATCH;
69169 u.be.pIdxKey = &u.be.r;
69170 }else{
69171 u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
69172 u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
69174 if( u.be.pIdxKey==0 ) goto no_mem;
69175 assert( pIn3->flags & MEM_Blob );
69176 assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
69177 sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
69178 u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
69180 rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
69181 if( pOp->p4.i==0 ){
69182 sqlite3DbFree(db, u.be.pFree);
69184 if( rc!=SQLITE_OK ){
69185 break;
69187 u.be.alreadyExists = (u.be.res==0);
69188 u.be.pC->deferredMoveto = 0;
69189 u.be.pC->cacheStatus = CACHE_STALE;
69191 if( pOp->opcode==OP_Found ){
69192 if( u.be.alreadyExists ) pc = pOp->p2 - 1;
69193 }else{
69194 if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
69196 break;
69199 /* Opcode: IsUnique P1 P2 P3 P4 *
69201 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
69202 ** no data and where the key are records generated by OP_MakeRecord with
69203 ** the list field being the integer ROWID of the entry that the index
69204 ** entry refers to.
69206 ** The P3 register contains an integer record number. Call this record
69207 ** number R. Register P4 is the first in a set of N contiguous registers
69208 ** that make up an unpacked index key that can be used with cursor P1.
69209 ** The value of N can be inferred from the cursor. N includes the rowid
69210 ** value appended to the end of the index record. This rowid value may
69211 ** or may not be the same as R.
69213 ** If any of the N registers beginning with register P4 contains a NULL
69214 ** value, jump immediately to P2.
69216 ** Otherwise, this instruction checks if cursor P1 contains an entry
69217 ** where the first (N-1) fields match but the rowid value at the end
69218 ** of the index entry is not R. If there is no such entry, control jumps
69219 ** to instruction P2. Otherwise, the rowid of the conflicting index
69220 ** entry is copied to register P3 and control falls through to the next
69221 ** instruction.
69223 ** See also: NotFound, NotExists, Found
69225 case OP_IsUnique: { /* jump, in3 */
69226 #if 0 /* local variables moved into u.bf */
69227 u16 ii;
69228 VdbeCursor *pCx;
69229 BtCursor *pCrsr;
69230 u16 nField;
69231 Mem *aMx;
69232 UnpackedRecord r; /* B-Tree index search key */
69233 i64 R; /* Rowid stored in register P3 */
69234 #endif /* local variables moved into u.bf */
69236 pIn3 = &aMem[pOp->p3];
69237 u.bf.aMx = &aMem[pOp->p4.i];
69238 /* Assert that the values of parameters P1 and P4 are in range. */
69239 assert( pOp->p4type==P4_INT32 );
69240 assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
69241 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69243 /* Find the index cursor. */
69244 u.bf.pCx = p->apCsr[pOp->p1];
69245 assert( u.bf.pCx->deferredMoveto==0 );
69246 u.bf.pCx->seekResult = 0;
69247 u.bf.pCx->cacheStatus = CACHE_STALE;
69248 u.bf.pCrsr = u.bf.pCx->pCursor;
69250 /* If any of the values are NULL, take the jump. */
69251 u.bf.nField = u.bf.pCx->pKeyInfo->nField;
69252 for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
69253 if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
69254 pc = pOp->p2 - 1;
69255 u.bf.pCrsr = 0;
69256 break;
69259 assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
69261 if( u.bf.pCrsr!=0 ){
69262 /* Populate the index search key. */
69263 u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
69264 u.bf.r.nField = u.bf.nField + 1;
69265 u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
69266 u.bf.r.aMem = u.bf.aMx;
69267 #ifdef SQLITE_DEBUG
69268 { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
69269 #endif
69271 /* Extract the value of u.bf.R from register P3. */
69272 sqlite3VdbeMemIntegerify(pIn3);
69273 u.bf.R = pIn3->u.i;
69275 /* Search the B-Tree index. If no conflicting record is found, jump
69276 ** to P2. Otherwise, copy the rowid of the conflicting record to
69277 ** register P3 and fall through to the next instruction. */
69278 rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
69279 if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
69280 pc = pOp->p2 - 1;
69281 }else{
69282 pIn3->u.i = u.bf.r.rowid;
69285 break;
69288 /* Opcode: NotExists P1 P2 P3 * *
69290 ** Use the content of register P3 as an integer key. If a record
69291 ** with that key does not exist in table of P1, then jump to P2.
69292 ** If the record does exist, then fall through. The cursor is left
69293 ** pointing to the record if it exists.
69295 ** The difference between this operation and NotFound is that this
69296 ** operation assumes the key is an integer and that P1 is a table whereas
69297 ** NotFound assumes key is a blob constructed from MakeRecord and
69298 ** P1 is an index.
69300 ** See also: Found, NotFound, IsUnique
69302 case OP_NotExists: { /* jump, in3 */
69303 #if 0 /* local variables moved into u.bg */
69304 VdbeCursor *pC;
69305 BtCursor *pCrsr;
69306 int res;
69307 u64 iKey;
69308 #endif /* local variables moved into u.bg */
69310 pIn3 = &aMem[pOp->p3];
69311 assert( pIn3->flags & MEM_Int );
69312 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69313 u.bg.pC = p->apCsr[pOp->p1];
69314 assert( u.bg.pC!=0 );
69315 assert( u.bg.pC->isTable );
69316 assert( u.bg.pC->pseudoTableReg==0 );
69317 u.bg.pCrsr = u.bg.pC->pCursor;
69318 if( ALWAYS(u.bg.pCrsr!=0) ){
69319 u.bg.res = 0;
69320 u.bg.iKey = pIn3->u.i;
69321 rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
69322 u.bg.pC->lastRowid = pIn3->u.i;
69323 u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
69324 u.bg.pC->nullRow = 0;
69325 u.bg.pC->cacheStatus = CACHE_STALE;
69326 u.bg.pC->deferredMoveto = 0;
69327 if( u.bg.res!=0 ){
69328 pc = pOp->p2 - 1;
69329 assert( u.bg.pC->rowidIsValid==0 );
69331 u.bg.pC->seekResult = u.bg.res;
69332 }else{
69333 /* This happens when an attempt to open a read cursor on the
69334 ** sqlite_master table returns SQLITE_EMPTY.
69336 pc = pOp->p2 - 1;
69337 assert( u.bg.pC->rowidIsValid==0 );
69338 u.bg.pC->seekResult = 0;
69340 break;
69343 /* Opcode: Sequence P1 P2 * * *
69345 ** Find the next available sequence number for cursor P1.
69346 ** Write the sequence number into register P2.
69347 ** The sequence number on the cursor is incremented after this
69348 ** instruction.
69350 case OP_Sequence: { /* out2-prerelease */
69351 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69352 assert( p->apCsr[pOp->p1]!=0 );
69353 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
69354 break;
69358 /* Opcode: NewRowid P1 P2 P3 * *
69360 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
69361 ** The record number is not previously used as a key in the database
69362 ** table that cursor P1 points to. The new record number is written
69363 ** written to register P2.
69365 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
69366 ** the largest previously generated record number. No new record numbers are
69367 ** allowed to be less than this value. When this value reaches its maximum,
69368 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
69369 ** generated record number. This P3 mechanism is used to help implement the
69370 ** AUTOINCREMENT feature.
69372 case OP_NewRowid: { /* out2-prerelease */
69373 #if 0 /* local variables moved into u.bh */
69374 i64 v; /* The new rowid */
69375 VdbeCursor *pC; /* Cursor of table to get the new rowid */
69376 int res; /* Result of an sqlite3BtreeLast() */
69377 int cnt; /* Counter to limit the number of searches */
69378 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
69379 VdbeFrame *pFrame; /* Root frame of VDBE */
69380 #endif /* local variables moved into u.bh */
69382 u.bh.v = 0;
69383 u.bh.res = 0;
69384 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69385 u.bh.pC = p->apCsr[pOp->p1];
69386 assert( u.bh.pC!=0 );
69387 if( NEVER(u.bh.pC->pCursor==0) ){
69388 /* The zero initialization above is all that is needed */
69389 }else{
69390 /* The next rowid or record number (different terms for the same
69391 ** thing) is obtained in a two-step algorithm.
69393 ** First we attempt to find the largest existing rowid and add one
69394 ** to that. But if the largest existing rowid is already the maximum
69395 ** positive integer, we have to fall through to the second
69396 ** probabilistic algorithm
69398 ** The second algorithm is to select a rowid at random and see if
69399 ** it already exists in the table. If it does not exist, we have
69400 ** succeeded. If the random rowid does exist, we select a new one
69401 ** and try again, up to 100 times.
69403 assert( u.bh.pC->isTable );
69405 #ifdef SQLITE_32BIT_ROWID
69406 # define MAX_ROWID 0x7fffffff
69407 #else
69408 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
69409 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
69410 ** to provide the constant while making all compilers happy.
69412 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
69413 #endif
69415 if( !u.bh.pC->useRandomRowid ){
69416 u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
69417 if( u.bh.v==0 ){
69418 rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
69419 if( rc!=SQLITE_OK ){
69420 goto abort_due_to_error;
69422 if( u.bh.res ){
69423 u.bh.v = 1; /* IMP: R-61914-48074 */
69424 }else{
69425 assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
69426 rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
69427 assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
69428 if( u.bh.v>=MAX_ROWID ){
69429 u.bh.pC->useRandomRowid = 1;
69430 }else{
69431 u.bh.v++; /* IMP: R-29538-34987 */
69436 #ifndef SQLITE_OMIT_AUTOINCREMENT
69437 if( pOp->p3 ){
69438 /* Assert that P3 is a valid memory cell. */
69439 assert( pOp->p3>0 );
69440 if( p->pFrame ){
69441 for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
69442 /* Assert that P3 is a valid memory cell. */
69443 assert( pOp->p3<=u.bh.pFrame->nMem );
69444 u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
69445 }else{
69446 /* Assert that P3 is a valid memory cell. */
69447 assert( pOp->p3<=p->nMem );
69448 u.bh.pMem = &aMem[pOp->p3];
69449 memAboutToChange(p, u.bh.pMem);
69451 assert( memIsValid(u.bh.pMem) );
69453 REGISTER_TRACE(pOp->p3, u.bh.pMem);
69454 sqlite3VdbeMemIntegerify(u.bh.pMem);
69455 assert( (u.bh.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
69456 if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
69457 rc = SQLITE_FULL; /* IMP: R-12275-61338 */
69458 goto abort_due_to_error;
69460 if( u.bh.v<u.bh.pMem->u.i+1 ){
69461 u.bh.v = u.bh.pMem->u.i + 1;
69463 u.bh.pMem->u.i = u.bh.v;
69465 #endif
69467 sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
69469 if( u.bh.pC->useRandomRowid ){
69470 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
69471 ** largest possible integer (9223372036854775807) then the database
69472 ** engine starts picking positive candidate ROWIDs at random until
69473 ** it finds one that is not previously used. */
69474 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
69475 ** an AUTOINCREMENT table. */
69476 /* on the first attempt, simply do one more than previous */
69477 u.bh.v = lastRowid;
69478 u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
69479 u.bh.v++; /* ensure non-zero */
69480 u.bh.cnt = 0;
69481 while( ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
69482 0, &u.bh.res))==SQLITE_OK)
69483 && (u.bh.res==0)
69484 && (++u.bh.cnt<100)){
69485 /* collision - try another random rowid */
69486 sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
69487 if( u.bh.cnt<5 ){
69488 /* try "small" random rowids for the initial attempts */
69489 u.bh.v &= 0xffffff;
69490 }else{
69491 u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
69493 u.bh.v++; /* ensure non-zero */
69495 if( rc==SQLITE_OK && u.bh.res==0 ){
69496 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
69497 goto abort_due_to_error;
69499 assert( u.bh.v>0 ); /* EV: R-40812-03570 */
69501 u.bh.pC->rowidIsValid = 0;
69502 u.bh.pC->deferredMoveto = 0;
69503 u.bh.pC->cacheStatus = CACHE_STALE;
69505 pOut->u.i = u.bh.v;
69506 break;
69509 /* Opcode: Insert P1 P2 P3 P4 P5
69511 ** Write an entry into the table of cursor P1. A new entry is
69512 ** created if it doesn't already exist or the data for an existing
69513 ** entry is overwritten. The data is the value MEM_Blob stored in register
69514 ** number P2. The key is stored in register P3. The key must
69515 ** be a MEM_Int.
69517 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
69518 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
69519 ** then rowid is stored for subsequent return by the
69520 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
69522 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
69523 ** the last seek operation (OP_NotExists) was a success, then this
69524 ** operation will not attempt to find the appropriate row before doing
69525 ** the insert but will instead overwrite the row that the cursor is
69526 ** currently pointing to. Presumably, the prior OP_NotExists opcode
69527 ** has already positioned the cursor correctly. This is an optimization
69528 ** that boosts performance by avoiding redundant seeks.
69530 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
69531 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
69532 ** is part of an INSERT operation. The difference is only important to
69533 ** the update hook.
69535 ** Parameter P4 may point to a string containing the table-name, or
69536 ** may be NULL. If it is not NULL, then the update-hook
69537 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
69539 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
69540 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
69541 ** and register P2 becomes ephemeral. If the cursor is changed, the
69542 ** value of register P2 will then change. Make sure this does not
69543 ** cause any problems.)
69545 ** This instruction only works on tables. The equivalent instruction
69546 ** for indices is OP_IdxInsert.
69548 /* Opcode: InsertInt P1 P2 P3 P4 P5
69550 ** This works exactly like OP_Insert except that the key is the
69551 ** integer value P3, not the value of the integer stored in register P3.
69553 case OP_Insert:
69554 case OP_InsertInt: {
69555 #if 0 /* local variables moved into u.bi */
69556 Mem *pData; /* MEM cell holding data for the record to be inserted */
69557 Mem *pKey; /* MEM cell holding key for the record */
69558 i64 iKey; /* The integer ROWID or key for the record to be inserted */
69559 VdbeCursor *pC; /* Cursor to table into which insert is written */
69560 int nZero; /* Number of zero-bytes to append */
69561 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
69562 const char *zDb; /* database name - used by the update hook */
69563 const char *zTbl; /* Table name - used by the opdate hook */
69564 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
69565 #endif /* local variables moved into u.bi */
69567 u.bi.pData = &aMem[pOp->p2];
69568 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69569 assert( memIsValid(u.bi.pData) );
69570 u.bi.pC = p->apCsr[pOp->p1];
69571 assert( u.bi.pC!=0 );
69572 assert( u.bi.pC->pCursor!=0 );
69573 assert( u.bi.pC->pseudoTableReg==0 );
69574 assert( u.bi.pC->isTable );
69575 REGISTER_TRACE(pOp->p2, u.bi.pData);
69577 if( pOp->opcode==OP_Insert ){
69578 u.bi.pKey = &aMem[pOp->p3];
69579 assert( u.bi.pKey->flags & MEM_Int );
69580 assert( memIsValid(u.bi.pKey) );
69581 REGISTER_TRACE(pOp->p3, u.bi.pKey);
69582 u.bi.iKey = u.bi.pKey->u.i;
69583 }else{
69584 assert( pOp->opcode==OP_InsertInt );
69585 u.bi.iKey = pOp->p3;
69588 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
69589 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
69590 if( u.bi.pData->flags & MEM_Null ){
69591 u.bi.pData->z = 0;
69592 u.bi.pData->n = 0;
69593 }else{
69594 assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
69596 u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
69597 if( u.bi.pData->flags & MEM_Zero ){
69598 u.bi.nZero = u.bi.pData->u.nZero;
69599 }else{
69600 u.bi.nZero = 0;
69602 sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
69603 rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
69604 u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
69605 pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
69607 u.bi.pC->rowidIsValid = 0;
69608 u.bi.pC->deferredMoveto = 0;
69609 u.bi.pC->cacheStatus = CACHE_STALE;
69611 /* Invoke the update-hook if required. */
69612 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69613 u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
69614 u.bi.zTbl = pOp->p4.z;
69615 u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
69616 assert( u.bi.pC->isTable );
69617 db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
69618 assert( u.bi.pC->iDb>=0 );
69620 break;
69623 /* Opcode: Delete P1 P2 * P4 *
69625 ** Delete the record at which the P1 cursor is currently pointing.
69627 ** The cursor will be left pointing at either the next or the previous
69628 ** record in the table. If it is left pointing at the next record, then
69629 ** the next Next instruction will be a no-op. Hence it is OK to delete
69630 ** a record from within an Next loop.
69632 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
69633 ** incremented (otherwise not).
69635 ** P1 must not be pseudo-table. It has to be a real table with
69636 ** multiple rows.
69638 ** If P4 is not NULL, then it is the name of the table that P1 is
69639 ** pointing to. The update hook will be invoked, if it exists.
69640 ** If P4 is not NULL then the P1 cursor must have been positioned
69641 ** using OP_NotFound prior to invoking this opcode.
69643 case OP_Delete: {
69644 #if 0 /* local variables moved into u.bj */
69645 i64 iKey;
69646 VdbeCursor *pC;
69647 #endif /* local variables moved into u.bj */
69649 u.bj.iKey = 0;
69650 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69651 u.bj.pC = p->apCsr[pOp->p1];
69652 assert( u.bj.pC!=0 );
69653 assert( u.bj.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
69655 /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
69656 ** row being deleted.
69658 if( db->xUpdateCallback && pOp->p4.z ){
69659 assert( u.bj.pC->isTable );
69660 assert( u.bj.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
69661 u.bj.iKey = u.bj.pC->lastRowid;
69664 /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
69665 ** OP_Column on the same table without any intervening operations that
69666 ** might move or invalidate the cursor. Hence cursor u.bj.pC is always pointing
69667 ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
69668 ** below is always a no-op and cannot fail. We will run it anyhow, though,
69669 ** to guard against future changes to the code generator.
69671 assert( u.bj.pC->deferredMoveto==0 );
69672 rc = sqlite3VdbeCursorMoveto(u.bj.pC);
69673 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69675 sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
69676 rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
69677 u.bj.pC->cacheStatus = CACHE_STALE;
69679 /* Invoke the update-hook if required. */
69680 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69681 const char *zDb = db->aDb[u.bj.pC->iDb].zName;
69682 const char *zTbl = pOp->p4.z;
69683 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
69684 assert( u.bj.pC->iDb>=0 );
69686 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
69687 break;
69689 /* Opcode: ResetCount * * * * *
69691 ** The value of the change counter is copied to the database handle
69692 ** change counter (returned by subsequent calls to sqlite3_changes()).
69693 ** Then the VMs internal change counter resets to 0.
69694 ** This is used by trigger programs.
69696 case OP_ResetCount: {
69697 sqlite3VdbeSetChanges(db, p->nChange);
69698 p->nChange = 0;
69699 break;
69702 /* Opcode: SorterCompare P1 P2 P3
69704 ** P1 is a sorter cursor. This instruction compares the record blob in
69705 ** register P3 with the entry that the sorter cursor currently points to.
69706 ** If, excluding the rowid fields at the end, the two records are a match,
69707 ** fall through to the next instruction. Otherwise, jump to instruction P2.
69709 case OP_SorterCompare: {
69710 #if 0 /* local variables moved into u.bk */
69711 VdbeCursor *pC;
69712 int res;
69713 #endif /* local variables moved into u.bk */
69715 u.bk.pC = p->apCsr[pOp->p1];
69716 assert( isSorter(u.bk.pC) );
69717 pIn3 = &aMem[pOp->p3];
69718 rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
69719 if( u.bk.res ){
69720 pc = pOp->p2-1;
69722 break;
69725 /* Opcode: SorterData P1 P2 * * *
69727 ** Write into register P2 the current sorter data for sorter cursor P1.
69729 case OP_SorterData: {
69730 #if 0 /* local variables moved into u.bl */
69731 VdbeCursor *pC;
69732 #endif /* local variables moved into u.bl */
69734 pOut = &aMem[pOp->p2];
69735 u.bl.pC = p->apCsr[pOp->p1];
69736 assert( u.bl.pC->isSorter );
69737 rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
69738 break;
69741 /* Opcode: RowData P1 P2 * * *
69743 ** Write into register P2 the complete row data for cursor P1.
69744 ** There is no interpretation of the data.
69745 ** It is just copied onto the P2 register exactly as
69746 ** it is found in the database file.
69748 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69749 ** of a real table, not a pseudo-table.
69751 /* Opcode: RowKey P1 P2 * * *
69753 ** Write into register P2 the complete row key for cursor P1.
69754 ** There is no interpretation of the data.
69755 ** The key is copied onto the P3 register exactly as
69756 ** it is found in the database file.
69758 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69759 ** of a real table, not a pseudo-table.
69761 case OP_RowKey:
69762 case OP_RowData: {
69763 #if 0 /* local variables moved into u.bm */
69764 VdbeCursor *pC;
69765 BtCursor *pCrsr;
69766 u32 n;
69767 i64 n64;
69768 #endif /* local variables moved into u.bm */
69770 pOut = &aMem[pOp->p2];
69771 memAboutToChange(p, pOut);
69773 /* Note that RowKey and RowData are really exactly the same instruction */
69774 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69775 u.bm.pC = p->apCsr[pOp->p1];
69776 assert( u.bm.pC->isSorter==0 );
69777 assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
69778 assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
69779 assert( u.bm.pC!=0 );
69780 assert( u.bm.pC->nullRow==0 );
69781 assert( u.bm.pC->pseudoTableReg==0 );
69782 assert( u.bm.pC->pCursor!=0 );
69783 u.bm.pCrsr = u.bm.pC->pCursor;
69784 assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
69786 /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
69787 ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
69788 ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
69789 ** a no-op and can never fail. But we leave it in place as a safety.
69791 assert( u.bm.pC->deferredMoveto==0 );
69792 rc = sqlite3VdbeCursorMoveto(u.bm.pC);
69793 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69795 if( u.bm.pC->isIndex ){
69796 assert( !u.bm.pC->isTable );
69797 VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
69798 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
69799 if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
69800 goto too_big;
69802 u.bm.n = (u32)u.bm.n64;
69803 }else{
69804 VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
69805 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
69806 if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
69807 goto too_big;
69810 if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
69811 goto no_mem;
69813 pOut->n = u.bm.n;
69814 MemSetTypeFlag(pOut, MEM_Blob);
69815 if( u.bm.pC->isIndex ){
69816 rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
69817 }else{
69818 rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
69820 pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
69821 UPDATE_MAX_BLOBSIZE(pOut);
69822 break;
69825 /* Opcode: Rowid P1 P2 * * *
69827 ** Store in register P2 an integer which is the key of the table entry that
69828 ** P1 is currently point to.
69830 ** P1 can be either an ordinary table or a virtual table. There used to
69831 ** be a separate OP_VRowid opcode for use with virtual tables, but this
69832 ** one opcode now works for both table types.
69834 case OP_Rowid: { /* out2-prerelease */
69835 #if 0 /* local variables moved into u.bn */
69836 VdbeCursor *pC;
69837 i64 v;
69838 sqlite3_vtab *pVtab;
69839 const sqlite3_module *pModule;
69840 #endif /* local variables moved into u.bn */
69842 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69843 u.bn.pC = p->apCsr[pOp->p1];
69844 assert( u.bn.pC!=0 );
69845 assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
69846 if( u.bn.pC->nullRow ){
69847 pOut->flags = MEM_Null;
69848 break;
69849 }else if( u.bn.pC->deferredMoveto ){
69850 u.bn.v = u.bn.pC->movetoTarget;
69851 #ifndef SQLITE_OMIT_VIRTUALTABLE
69852 }else if( u.bn.pC->pVtabCursor ){
69853 u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
69854 u.bn.pModule = u.bn.pVtab->pModule;
69855 assert( u.bn.pModule->xRowid );
69856 rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
69857 sqlite3VtabImportErrmsg(p, u.bn.pVtab);
69858 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69859 }else{
69860 assert( u.bn.pC->pCursor!=0 );
69861 rc = sqlite3VdbeCursorMoveto(u.bn.pC);
69862 if( rc ) goto abort_due_to_error;
69863 if( u.bn.pC->rowidIsValid ){
69864 u.bn.v = u.bn.pC->lastRowid;
69865 }else{
69866 rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
69867 assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
69870 pOut->u.i = u.bn.v;
69871 break;
69874 /* Opcode: NullRow P1 * * * *
69876 ** Move the cursor P1 to a null row. Any OP_Column operations
69877 ** that occur while the cursor is on the null row will always
69878 ** write a NULL.
69880 case OP_NullRow: {
69881 #if 0 /* local variables moved into u.bo */
69882 VdbeCursor *pC;
69883 #endif /* local variables moved into u.bo */
69885 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69886 u.bo.pC = p->apCsr[pOp->p1];
69887 assert( u.bo.pC!=0 );
69888 u.bo.pC->nullRow = 1;
69889 u.bo.pC->rowidIsValid = 0;
69890 assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
69891 if( u.bo.pC->pCursor ){
69892 sqlite3BtreeClearCursor(u.bo.pC->pCursor);
69894 break;
69897 /* Opcode: Last P1 P2 * * *
69899 ** The next use of the Rowid or Column or Next instruction for P1
69900 ** will refer to the last entry in the database table or index.
69901 ** If the table or index is empty and P2>0, then jump immediately to P2.
69902 ** If P2 is 0 or if the table or index is not empty, fall through
69903 ** to the following instruction.
69905 case OP_Last: { /* jump */
69906 #if 0 /* local variables moved into u.bp */
69907 VdbeCursor *pC;
69908 BtCursor *pCrsr;
69909 int res;
69910 #endif /* local variables moved into u.bp */
69912 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69913 u.bp.pC = p->apCsr[pOp->p1];
69914 assert( u.bp.pC!=0 );
69915 u.bp.pCrsr = u.bp.pC->pCursor;
69916 u.bp.res = 0;
69917 if( ALWAYS(u.bp.pCrsr!=0) ){
69918 rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
69920 u.bp.pC->nullRow = (u8)u.bp.res;
69921 u.bp.pC->deferredMoveto = 0;
69922 u.bp.pC->rowidIsValid = 0;
69923 u.bp.pC->cacheStatus = CACHE_STALE;
69924 if( pOp->p2>0 && u.bp.res ){
69925 pc = pOp->p2 - 1;
69927 break;
69931 /* Opcode: Sort P1 P2 * * *
69933 ** This opcode does exactly the same thing as OP_Rewind except that
69934 ** it increments an undocumented global variable used for testing.
69936 ** Sorting is accomplished by writing records into a sorting index,
69937 ** then rewinding that index and playing it back from beginning to
69938 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
69939 ** rewinding so that the global variable will be incremented and
69940 ** regression tests can determine whether or not the optimizer is
69941 ** correctly optimizing out sorts.
69943 case OP_SorterSort: /* jump */
69944 case OP_Sort: { /* jump */
69945 #ifdef SQLITE_TEST
69946 sqlite3_sort_count++;
69947 sqlite3_search_count--;
69948 #endif
69949 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
69950 /* Fall through into OP_Rewind */
69952 /* Opcode: Rewind P1 P2 * * *
69954 ** The next use of the Rowid or Column or Next instruction for P1
69955 ** will refer to the first entry in the database table or index.
69956 ** If the table or index is empty and P2>0, then jump immediately to P2.
69957 ** If P2 is 0 or if the table or index is not empty, fall through
69958 ** to the following instruction.
69960 case OP_Rewind: { /* jump */
69961 #if 0 /* local variables moved into u.bq */
69962 VdbeCursor *pC;
69963 BtCursor *pCrsr;
69964 int res;
69965 #endif /* local variables moved into u.bq */
69967 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69968 u.bq.pC = p->apCsr[pOp->p1];
69969 assert( u.bq.pC!=0 );
69970 assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
69971 u.bq.res = 1;
69972 if( isSorter(u.bq.pC) ){
69973 rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
69974 }else{
69975 u.bq.pCrsr = u.bq.pC->pCursor;
69976 assert( u.bq.pCrsr );
69977 rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
69978 u.bq.pC->atFirst = u.bq.res==0 ?1:0;
69979 u.bq.pC->deferredMoveto = 0;
69980 u.bq.pC->cacheStatus = CACHE_STALE;
69981 u.bq.pC->rowidIsValid = 0;
69983 u.bq.pC->nullRow = (u8)u.bq.res;
69984 assert( pOp->p2>0 && pOp->p2<p->nOp );
69985 if( u.bq.res ){
69986 pc = pOp->p2 - 1;
69988 break;
69991 /* Opcode: Next P1 P2 * P4 P5
69993 ** Advance cursor P1 so that it points to the next key/data pair in its
69994 ** table or index. If there are no more key/value pairs then fall through
69995 ** to the following instruction. But if the cursor advance was successful,
69996 ** jump immediately to P2.
69998 ** The P1 cursor must be for a real table, not a pseudo-table.
70000 ** P4 is always of type P4_ADVANCE. The function pointer points to
70001 ** sqlite3BtreeNext().
70003 ** If P5 is positive and the jump is taken, then event counter
70004 ** number P5-1 in the prepared statement is incremented.
70006 ** See also: Prev
70008 /* Opcode: Prev P1 P2 * * P5
70010 ** Back up cursor P1 so that it points to the previous key/data pair in its
70011 ** table or index. If there is no previous key/value pairs then fall through
70012 ** to the following instruction. But if the cursor backup was successful,
70013 ** jump immediately to P2.
70015 ** The P1 cursor must be for a real table, not a pseudo-table.
70017 ** P4 is always of type P4_ADVANCE. The function pointer points to
70018 ** sqlite3BtreePrevious().
70020 ** If P5 is positive and the jump is taken, then event counter
70021 ** number P5-1 in the prepared statement is incremented.
70023 case OP_SorterNext: /* jump */
70024 case OP_Prev: /* jump */
70025 case OP_Next: { /* jump */
70026 #if 0 /* local variables moved into u.br */
70027 VdbeCursor *pC;
70028 int res;
70029 #endif /* local variables moved into u.br */
70031 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70032 assert( pOp->p5<ArraySize(p->aCounter) );
70033 u.br.pC = p->apCsr[pOp->p1];
70034 if( u.br.pC==0 ){
70035 break; /* See ticket #2273 */
70037 assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
70038 if( isSorter(u.br.pC) ){
70039 assert( pOp->opcode==OP_SorterNext );
70040 rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
70041 }else{
70042 /* u.br.res = 1; // Always initialized by the xAdvance() call */
70043 assert( u.br.pC->deferredMoveto==0 );
70044 assert( u.br.pC->pCursor );
70045 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
70046 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
70047 rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
70049 u.br.pC->nullRow = (u8)u.br.res;
70050 u.br.pC->cacheStatus = CACHE_STALE;
70051 if( u.br.res==0 ){
70052 pc = pOp->p2 - 1;
70053 p->aCounter[pOp->p5]++;
70054 #ifdef SQLITE_TEST
70055 sqlite3_search_count++;
70056 #endif
70058 u.br.pC->rowidIsValid = 0;
70059 goto check_for_interrupt;
70062 /* Opcode: IdxInsert P1 P2 P3 * P5
70064 ** Register P2 holds an SQL index key made using the
70065 ** MakeRecord instructions. This opcode writes that key
70066 ** into the index P1. Data for the entry is nil.
70068 ** P3 is a flag that provides a hint to the b-tree layer that this
70069 ** insert is likely to be an append.
70071 ** This instruction only works for indices. The equivalent instruction
70072 ** for tables is OP_Insert.
70074 case OP_SorterInsert: /* in2 */
70075 case OP_IdxInsert: { /* in2 */
70076 #if 0 /* local variables moved into u.bs */
70077 VdbeCursor *pC;
70078 BtCursor *pCrsr;
70079 int nKey;
70080 const char *zKey;
70081 #endif /* local variables moved into u.bs */
70083 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70084 u.bs.pC = p->apCsr[pOp->p1];
70085 assert( u.bs.pC!=0 );
70086 assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
70087 pIn2 = &aMem[pOp->p2];
70088 assert( pIn2->flags & MEM_Blob );
70089 u.bs.pCrsr = u.bs.pC->pCursor;
70090 if( ALWAYS(u.bs.pCrsr!=0) ){
70091 assert( u.bs.pC->isTable==0 );
70092 rc = ExpandBlob(pIn2);
70093 if( rc==SQLITE_OK ){
70094 if( isSorter(u.bs.pC) ){
70095 rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
70096 }else{
70097 u.bs.nKey = pIn2->n;
70098 u.bs.zKey = pIn2->z;
70099 rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
70100 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
70102 assert( u.bs.pC->deferredMoveto==0 );
70103 u.bs.pC->cacheStatus = CACHE_STALE;
70107 break;
70110 /* Opcode: IdxDelete P1 P2 P3 * *
70112 ** The content of P3 registers starting at register P2 form
70113 ** an unpacked index key. This opcode removes that entry from the
70114 ** index opened by cursor P1.
70116 case OP_IdxDelete: {
70117 #if 0 /* local variables moved into u.bt */
70118 VdbeCursor *pC;
70119 BtCursor *pCrsr;
70120 int res;
70121 UnpackedRecord r;
70122 #endif /* local variables moved into u.bt */
70124 assert( pOp->p3>0 );
70125 assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
70126 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70127 u.bt.pC = p->apCsr[pOp->p1];
70128 assert( u.bt.pC!=0 );
70129 u.bt.pCrsr = u.bt.pC->pCursor;
70130 if( ALWAYS(u.bt.pCrsr!=0) ){
70131 u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
70132 u.bt.r.nField = (u16)pOp->p3;
70133 u.bt.r.flags = 0;
70134 u.bt.r.aMem = &aMem[pOp->p2];
70135 #ifdef SQLITE_DEBUG
70136 { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
70137 #endif
70138 rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
70139 if( rc==SQLITE_OK && u.bt.res==0 ){
70140 rc = sqlite3BtreeDelete(u.bt.pCrsr);
70142 assert( u.bt.pC->deferredMoveto==0 );
70143 u.bt.pC->cacheStatus = CACHE_STALE;
70145 break;
70148 /* Opcode: IdxRowid P1 P2 * * *
70150 ** Write into register P2 an integer which is the last entry in the record at
70151 ** the end of the index key pointed to by cursor P1. This integer should be
70152 ** the rowid of the table entry to which this index entry points.
70154 ** See also: Rowid, MakeRecord.
70156 case OP_IdxRowid: { /* out2-prerelease */
70157 #if 0 /* local variables moved into u.bu */
70158 BtCursor *pCrsr;
70159 VdbeCursor *pC;
70160 i64 rowid;
70161 #endif /* local variables moved into u.bu */
70163 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70164 u.bu.pC = p->apCsr[pOp->p1];
70165 assert( u.bu.pC!=0 );
70166 u.bu.pCrsr = u.bu.pC->pCursor;
70167 pOut->flags = MEM_Null;
70168 if( ALWAYS(u.bu.pCrsr!=0) ){
70169 rc = sqlite3VdbeCursorMoveto(u.bu.pC);
70170 if( NEVER(rc) ) goto abort_due_to_error;
70171 assert( u.bu.pC->deferredMoveto==0 );
70172 assert( u.bu.pC->isTable==0 );
70173 if( !u.bu.pC->nullRow ){
70174 rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
70175 if( rc!=SQLITE_OK ){
70176 goto abort_due_to_error;
70178 pOut->u.i = u.bu.rowid;
70179 pOut->flags = MEM_Int;
70182 break;
70185 /* Opcode: IdxGE P1 P2 P3 P4 P5
70187 ** The P4 register values beginning with P3 form an unpacked index
70188 ** key that omits the ROWID. Compare this key value against the index
70189 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
70191 ** If the P1 index entry is greater than or equal to the key value
70192 ** then jump to P2. Otherwise fall through to the next instruction.
70194 ** If P5 is non-zero then the key value is increased by an epsilon
70195 ** prior to the comparison. This make the opcode work like IdxGT except
70196 ** that if the key from register P3 is a prefix of the key in the cursor,
70197 ** the result is false whereas it would be true with IdxGT.
70199 /* Opcode: IdxLT P1 P2 P3 P4 P5
70201 ** The P4 register values beginning with P3 form an unpacked index
70202 ** key that omits the ROWID. Compare this key value against the index
70203 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
70205 ** If the P1 index entry is less than the key value then jump to P2.
70206 ** Otherwise fall through to the next instruction.
70208 ** If P5 is non-zero then the key value is increased by an epsilon prior
70209 ** to the comparison. This makes the opcode work like IdxLE.
70211 case OP_IdxLT: /* jump */
70212 case OP_IdxGE: { /* jump */
70213 #if 0 /* local variables moved into u.bv */
70214 VdbeCursor *pC;
70215 int res;
70216 UnpackedRecord r;
70217 #endif /* local variables moved into u.bv */
70219 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70220 u.bv.pC = p->apCsr[pOp->p1];
70221 assert( u.bv.pC!=0 );
70222 assert( u.bv.pC->isOrdered );
70223 if( ALWAYS(u.bv.pC->pCursor!=0) ){
70224 assert( u.bv.pC->deferredMoveto==0 );
70225 assert( pOp->p5==0 || pOp->p5==1 );
70226 assert( pOp->p4type==P4_INT32 );
70227 u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
70228 u.bv.r.nField = (u16)pOp->p4.i;
70229 if( pOp->p5 ){
70230 u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
70231 }else{
70232 u.bv.r.flags = UNPACKED_PREFIX_MATCH;
70234 u.bv.r.aMem = &aMem[pOp->p3];
70235 #ifdef SQLITE_DEBUG
70236 { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
70237 #endif
70238 rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
70239 if( pOp->opcode==OP_IdxLT ){
70240 u.bv.res = -u.bv.res;
70241 }else{
70242 assert( pOp->opcode==OP_IdxGE );
70243 u.bv.res++;
70245 if( u.bv.res>0 ){
70246 pc = pOp->p2 - 1 ;
70249 break;
70252 /* Opcode: Destroy P1 P2 P3 * *
70254 ** Delete an entire database table or index whose root page in the database
70255 ** file is given by P1.
70257 ** The table being destroyed is in the main database file if P3==0. If
70258 ** P3==1 then the table to be clear is in the auxiliary database file
70259 ** that is used to store tables create using CREATE TEMPORARY TABLE.
70261 ** If AUTOVACUUM is enabled then it is possible that another root page
70262 ** might be moved into the newly deleted root page in order to keep all
70263 ** root pages contiguous at the beginning of the database. The former
70264 ** value of the root page that moved - its value before the move occurred -
70265 ** is stored in register P2. If no page
70266 ** movement was required (because the table being dropped was already
70267 ** the last one in the database) then a zero is stored in register P2.
70268 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
70270 ** See also: Clear
70272 case OP_Destroy: { /* out2-prerelease */
70273 #if 0 /* local variables moved into u.bw */
70274 int iMoved;
70275 int iCnt;
70276 Vdbe *pVdbe;
70277 int iDb;
70278 #endif /* local variables moved into u.bw */
70280 assert( p->readOnly==0 );
70281 #ifndef SQLITE_OMIT_VIRTUALTABLE
70282 u.bw.iCnt = 0;
70283 for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
70284 if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->bIsReader
70285 && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0
70287 u.bw.iCnt++;
70290 #else
70291 u.bw.iCnt = db->nVdbeRead;
70292 #endif
70293 pOut->flags = MEM_Null;
70294 if( u.bw.iCnt>1 ){
70295 rc = SQLITE_LOCKED;
70296 p->errorAction = OE_Abort;
70297 }else{
70298 u.bw.iDb = pOp->p3;
70299 assert( u.bw.iCnt==1 );
70300 assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
70301 rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
70302 pOut->flags = MEM_Int;
70303 pOut->u.i = u.bw.iMoved;
70304 #ifndef SQLITE_OMIT_AUTOVACUUM
70305 if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
70306 sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
70307 /* All OP_Destroy operations occur on the same btree */
70308 assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
70309 resetSchemaOnFault = u.bw.iDb+1;
70311 #endif
70313 break;
70316 /* Opcode: Clear P1 P2 P3
70318 ** Delete all contents of the database table or index whose root page
70319 ** in the database file is given by P1. But, unlike Destroy, do not
70320 ** remove the table or index from the database file.
70322 ** The table being clear is in the main database file if P2==0. If
70323 ** P2==1 then the table to be clear is in the auxiliary database file
70324 ** that is used to store tables create using CREATE TEMPORARY TABLE.
70326 ** If the P3 value is non-zero, then the table referred to must be an
70327 ** intkey table (an SQL table, not an index). In this case the row change
70328 ** count is incremented by the number of rows in the table being cleared.
70329 ** If P3 is greater than zero, then the value stored in register P3 is
70330 ** also incremented by the number of rows in the table being cleared.
70332 ** See also: Destroy
70334 case OP_Clear: {
70335 #if 0 /* local variables moved into u.bx */
70336 int nChange;
70337 #endif /* local variables moved into u.bx */
70339 u.bx.nChange = 0;
70340 assert( p->readOnly==0 );
70341 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
70342 rc = sqlite3BtreeClearTable(
70343 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
70345 if( pOp->p3 ){
70346 p->nChange += u.bx.nChange;
70347 if( pOp->p3>0 ){
70348 assert( memIsValid(&aMem[pOp->p3]) );
70349 memAboutToChange(p, &aMem[pOp->p3]);
70350 aMem[pOp->p3].u.i += u.bx.nChange;
70353 break;
70356 /* Opcode: CreateTable P1 P2 * * *
70358 ** Allocate a new table in the main database file if P1==0 or in the
70359 ** auxiliary database file if P1==1 or in an attached database if
70360 ** P1>1. Write the root page number of the new table into
70361 ** register P2
70363 ** The difference between a table and an index is this: A table must
70364 ** have a 4-byte integer key and can have arbitrary data. An index
70365 ** has an arbitrary key but no data.
70367 ** See also: CreateIndex
70369 /* Opcode: CreateIndex P1 P2 * * *
70371 ** Allocate a new index in the main database file if P1==0 or in the
70372 ** auxiliary database file if P1==1 or in an attached database if
70373 ** P1>1. Write the root page number of the new table into
70374 ** register P2.
70376 ** See documentation on OP_CreateTable for additional information.
70378 case OP_CreateIndex: /* out2-prerelease */
70379 case OP_CreateTable: { /* out2-prerelease */
70380 #if 0 /* local variables moved into u.by */
70381 int pgno;
70382 int flags;
70383 Db *pDb;
70384 #endif /* local variables moved into u.by */
70386 u.by.pgno = 0;
70387 assert( pOp->p1>=0 && pOp->p1<db->nDb );
70388 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70389 assert( p->readOnly==0 );
70390 u.by.pDb = &db->aDb[pOp->p1];
70391 assert( u.by.pDb->pBt!=0 );
70392 if( pOp->opcode==OP_CreateTable ){
70393 /* u.by.flags = BTREE_INTKEY; */
70394 u.by.flags = BTREE_INTKEY;
70395 }else{
70396 u.by.flags = BTREE_BLOBKEY;
70398 rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
70399 pOut->u.i = u.by.pgno;
70400 break;
70403 /* Opcode: ParseSchema P1 * * P4 *
70405 ** Read and parse all entries from the SQLITE_MASTER table of database P1
70406 ** that match the WHERE clause P4.
70408 ** This opcode invokes the parser to create a new virtual machine,
70409 ** then runs the new virtual machine. It is thus a re-entrant opcode.
70411 case OP_ParseSchema: {
70412 #if 0 /* local variables moved into u.bz */
70413 int iDb;
70414 const char *zMaster;
70415 char *zSql;
70416 InitData initData;
70417 #endif /* local variables moved into u.bz */
70419 /* Any prepared statement that invokes this opcode will hold mutexes
70420 ** on every btree. This is a prerequisite for invoking
70421 ** sqlite3InitCallback().
70423 #ifdef SQLITE_DEBUG
70424 for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
70425 assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
70427 #endif
70429 u.bz.iDb = pOp->p1;
70430 assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
70431 assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
70432 /* Used to be a conditional */ {
70433 u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
70434 u.bz.initData.db = db;
70435 u.bz.initData.iDb = pOp->p1;
70436 u.bz.initData.pzErrMsg = &p->zErrMsg;
70437 u.bz.zSql = sqlite3MPrintf(db,
70438 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
70439 db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
70440 if( u.bz.zSql==0 ){
70441 rc = SQLITE_NOMEM;
70442 }else{
70443 assert( db->init.busy==0 );
70444 db->init.busy = 1;
70445 u.bz.initData.rc = SQLITE_OK;
70446 assert( !db->mallocFailed );
70447 rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
70448 if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
70449 sqlite3DbFree(db, u.bz.zSql);
70450 db->init.busy = 0;
70453 if( rc ) sqlite3ResetAllSchemasOfConnection(db);
70454 if( rc==SQLITE_NOMEM ){
70455 goto no_mem;
70457 break;
70460 #if !defined(SQLITE_OMIT_ANALYZE)
70461 /* Opcode: LoadAnalysis P1 * * * *
70463 ** Read the sqlite_stat1 table for database P1 and load the content
70464 ** of that table into the internal index hash table. This will cause
70465 ** the analysis to be used when preparing all subsequent queries.
70467 case OP_LoadAnalysis: {
70468 assert( pOp->p1>=0 && pOp->p1<db->nDb );
70469 rc = sqlite3AnalysisLoad(db, pOp->p1);
70470 break;
70472 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
70474 /* Opcode: DropTable P1 * * P4 *
70476 ** Remove the internal (in-memory) data structures that describe
70477 ** the table named P4 in database P1. This is called after a table
70478 ** is dropped in order to keep the internal representation of the
70479 ** schema consistent with what is on disk.
70481 case OP_DropTable: {
70482 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
70483 break;
70486 /* Opcode: DropIndex P1 * * P4 *
70488 ** Remove the internal (in-memory) data structures that describe
70489 ** the index named P4 in database P1. This is called after an index
70490 ** is dropped in order to keep the internal representation of the
70491 ** schema consistent with what is on disk.
70493 case OP_DropIndex: {
70494 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
70495 break;
70498 /* Opcode: DropTrigger P1 * * P4 *
70500 ** Remove the internal (in-memory) data structures that describe
70501 ** the trigger named P4 in database P1. This is called after a trigger
70502 ** is dropped in order to keep the internal representation of the
70503 ** schema consistent with what is on disk.
70505 case OP_DropTrigger: {
70506 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
70507 break;
70511 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
70512 /* Opcode: IntegrityCk P1 P2 P3 * P5
70514 ** Do an analysis of the currently open database. Store in
70515 ** register P1 the text of an error message describing any problems.
70516 ** If no problems are found, store a NULL in register P1.
70518 ** The register P3 contains the maximum number of allowed errors.
70519 ** At most reg(P3) errors will be reported.
70520 ** In other words, the analysis stops as soon as reg(P1) errors are
70521 ** seen. Reg(P1) is updated with the number of errors remaining.
70523 ** The root page numbers of all tables in the database are integer
70524 ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
70525 ** total.
70527 ** If P5 is not zero, the check is done on the auxiliary database
70528 ** file, not the main database file.
70530 ** This opcode is used to implement the integrity_check pragma.
70532 case OP_IntegrityCk: {
70533 #if 0 /* local variables moved into u.ca */
70534 int nRoot; /* Number of tables to check. (Number of root pages.) */
70535 int *aRoot; /* Array of rootpage numbers for tables to be checked */
70536 int j; /* Loop counter */
70537 int nErr; /* Number of errors reported */
70538 char *z; /* Text of the error report */
70539 Mem *pnErr; /* Register keeping track of errors remaining */
70540 #endif /* local variables moved into u.ca */
70542 assert( p->bIsReader );
70543 u.ca.nRoot = pOp->p2;
70544 assert( u.ca.nRoot>0 );
70545 u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
70546 if( u.ca.aRoot==0 ) goto no_mem;
70547 assert( pOp->p3>0 && pOp->p3<=p->nMem );
70548 u.ca.pnErr = &aMem[pOp->p3];
70549 assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
70550 assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
70551 pIn1 = &aMem[pOp->p1];
70552 for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
70553 u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
70555 u.ca.aRoot[u.ca.j] = 0;
70556 assert( pOp->p5<db->nDb );
70557 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
70558 u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
70559 (int)u.ca.pnErr->u.i, &u.ca.nErr);
70560 sqlite3DbFree(db, u.ca.aRoot);
70561 u.ca.pnErr->u.i -= u.ca.nErr;
70562 sqlite3VdbeMemSetNull(pIn1);
70563 if( u.ca.nErr==0 ){
70564 assert( u.ca.z==0 );
70565 }else if( u.ca.z==0 ){
70566 goto no_mem;
70567 }else{
70568 sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
70570 UPDATE_MAX_BLOBSIZE(pIn1);
70571 sqlite3VdbeChangeEncoding(pIn1, encoding);
70572 break;
70574 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
70576 /* Opcode: RowSetAdd P1 P2 * * *
70578 ** Insert the integer value held by register P2 into a boolean index
70579 ** held in register P1.
70581 ** An assertion fails if P2 is not an integer.
70583 case OP_RowSetAdd: { /* in1, in2 */
70584 pIn1 = &aMem[pOp->p1];
70585 pIn2 = &aMem[pOp->p2];
70586 assert( (pIn2->flags & MEM_Int)!=0 );
70587 if( (pIn1->flags & MEM_RowSet)==0 ){
70588 sqlite3VdbeMemSetRowSet(pIn1);
70589 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70591 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
70592 break;
70595 /* Opcode: RowSetRead P1 P2 P3 * *
70597 ** Extract the smallest value from boolean index P1 and put that value into
70598 ** register P3. Or, if boolean index P1 is initially empty, leave P3
70599 ** unchanged and jump to instruction P2.
70601 case OP_RowSetRead: { /* jump, in1, out3 */
70602 #if 0 /* local variables moved into u.cb */
70603 i64 val;
70604 #endif /* local variables moved into u.cb */
70606 pIn1 = &aMem[pOp->p1];
70607 if( (pIn1->flags & MEM_RowSet)==0
70608 || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
70610 /* The boolean index is empty */
70611 sqlite3VdbeMemSetNull(pIn1);
70612 pc = pOp->p2 - 1;
70613 }else{
70614 /* A value was pulled from the index */
70615 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
70617 goto check_for_interrupt;
70620 /* Opcode: RowSetTest P1 P2 P3 P4
70622 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
70623 ** contains a RowSet object and that RowSet object contains
70624 ** the value held in P3, jump to register P2. Otherwise, insert the
70625 ** integer in P3 into the RowSet and continue on to the
70626 ** next opcode.
70628 ** The RowSet object is optimized for the case where successive sets
70629 ** of integers, where each set contains no duplicates. Each set
70630 ** of values is identified by a unique P4 value. The first set
70631 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
70632 ** non-negative. For non-negative values of P4 only the lower 4
70633 ** bits are significant.
70635 ** This allows optimizations: (a) when P4==0 there is no need to test
70636 ** the rowset object for P3, as it is guaranteed not to contain it,
70637 ** (b) when P4==-1 there is no need to insert the value, as it will
70638 ** never be tested for, and (c) when a value that is part of set X is
70639 ** inserted, there is no need to search to see if the same value was
70640 ** previously inserted as part of set X (only if it was previously
70641 ** inserted as part of some other set).
70643 case OP_RowSetTest: { /* jump, in1, in3 */
70644 #if 0 /* local variables moved into u.cc */
70645 int iSet;
70646 int exists;
70647 #endif /* local variables moved into u.cc */
70649 pIn1 = &aMem[pOp->p1];
70650 pIn3 = &aMem[pOp->p3];
70651 u.cc.iSet = pOp->p4.i;
70652 assert( pIn3->flags&MEM_Int );
70654 /* If there is anything other than a rowset object in memory cell P1,
70655 ** delete it now and initialize P1 with an empty rowset
70657 if( (pIn1->flags & MEM_RowSet)==0 ){
70658 sqlite3VdbeMemSetRowSet(pIn1);
70659 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70662 assert( pOp->p4type==P4_INT32 );
70663 assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
70664 if( u.cc.iSet ){
70665 u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
70666 (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
70667 pIn3->u.i);
70668 if( u.cc.exists ){
70669 pc = pOp->p2 - 1;
70670 break;
70673 if( u.cc.iSet>=0 ){
70674 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
70676 break;
70680 #ifndef SQLITE_OMIT_TRIGGER
70682 /* Opcode: Program P1 P2 P3 P4 *
70684 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
70686 ** P1 contains the address of the memory cell that contains the first memory
70687 ** cell in an array of values used as arguments to the sub-program. P2
70688 ** contains the address to jump to if the sub-program throws an IGNORE
70689 ** exception using the RAISE() function. Register P3 contains the address
70690 ** of a memory cell in this (the parent) VM that is used to allocate the
70691 ** memory required by the sub-vdbe at runtime.
70693 ** P4 is a pointer to the VM containing the trigger program.
70695 case OP_Program: { /* jump */
70696 #if 0 /* local variables moved into u.cd */
70697 int nMem; /* Number of memory registers for sub-program */
70698 int nByte; /* Bytes of runtime space required for sub-program */
70699 Mem *pRt; /* Register to allocate runtime space */
70700 Mem *pMem; /* Used to iterate through memory cells */
70701 Mem *pEnd; /* Last memory cell in new array */
70702 VdbeFrame *pFrame; /* New vdbe frame to execute in */
70703 SubProgram *pProgram; /* Sub-program to execute */
70704 void *t; /* Token identifying trigger */
70705 #endif /* local variables moved into u.cd */
70707 u.cd.pProgram = pOp->p4.pProgram;
70708 u.cd.pRt = &aMem[pOp->p3];
70709 assert( u.cd.pProgram->nOp>0 );
70711 /* If the p5 flag is clear, then recursive invocation of triggers is
70712 ** disabled for backwards compatibility (p5 is set if this sub-program
70713 ** is really a trigger, not a foreign key action, and the flag set
70714 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
70716 ** It is recursive invocation of triggers, at the SQL level, that is
70717 ** disabled. In some cases a single trigger may generate more than one
70718 ** SubProgram (if the trigger may be executed with more than one different
70719 ** ON CONFLICT algorithm). SubProgram structures associated with a
70720 ** single trigger all have the same value for the SubProgram.token
70721 ** variable. */
70722 if( pOp->p5 ){
70723 u.cd.t = u.cd.pProgram->token;
70724 for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
70725 if( u.cd.pFrame ) break;
70728 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
70729 rc = SQLITE_ERROR;
70730 sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
70731 break;
70734 /* Register u.cd.pRt is used to store the memory required to save the state
70735 ** of the current program, and the memory required at runtime to execute
70736 ** the trigger program. If this trigger has been fired before, then u.cd.pRt
70737 ** is already allocated. Otherwise, it must be initialized. */
70738 if( (u.cd.pRt->flags&MEM_Frame)==0 ){
70739 /* SubProgram.nMem is set to the number of memory cells used by the
70740 ** program stored in SubProgram.aOp. As well as these, one memory
70741 ** cell is required for each cursor used by the program. Set local
70742 ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
70744 u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
70745 u.cd.nByte = ROUND8(sizeof(VdbeFrame))
70746 + u.cd.nMem * sizeof(Mem)
70747 + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
70748 + u.cd.pProgram->nOnce * sizeof(u8);
70749 u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
70750 if( !u.cd.pFrame ){
70751 goto no_mem;
70753 sqlite3VdbeMemRelease(u.cd.pRt);
70754 u.cd.pRt->flags = MEM_Frame;
70755 u.cd.pRt->u.pFrame = u.cd.pFrame;
70757 u.cd.pFrame->v = p;
70758 u.cd.pFrame->nChildMem = u.cd.nMem;
70759 u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
70760 u.cd.pFrame->pc = pc;
70761 u.cd.pFrame->aMem = p->aMem;
70762 u.cd.pFrame->nMem = p->nMem;
70763 u.cd.pFrame->apCsr = p->apCsr;
70764 u.cd.pFrame->nCursor = p->nCursor;
70765 u.cd.pFrame->aOp = p->aOp;
70766 u.cd.pFrame->nOp = p->nOp;
70767 u.cd.pFrame->token = u.cd.pProgram->token;
70768 u.cd.pFrame->aOnceFlag = p->aOnceFlag;
70769 u.cd.pFrame->nOnceFlag = p->nOnceFlag;
70771 u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
70772 for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
70773 u.cd.pMem->flags = MEM_Invalid;
70774 u.cd.pMem->db = db;
70776 }else{
70777 u.cd.pFrame = u.cd.pRt->u.pFrame;
70778 assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
70779 assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
70780 assert( pc==u.cd.pFrame->pc );
70783 p->nFrame++;
70784 u.cd.pFrame->pParent = p->pFrame;
70785 u.cd.pFrame->lastRowid = lastRowid;
70786 u.cd.pFrame->nChange = p->nChange;
70787 p->nChange = 0;
70788 p->pFrame = u.cd.pFrame;
70789 p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
70790 p->nMem = u.cd.pFrame->nChildMem;
70791 p->nCursor = (u16)u.cd.pFrame->nChildCsr;
70792 p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
70793 p->aOp = aOp = u.cd.pProgram->aOp;
70794 p->nOp = u.cd.pProgram->nOp;
70795 p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
70796 p->nOnceFlag = u.cd.pProgram->nOnce;
70797 pc = -1;
70798 memset(p->aOnceFlag, 0, p->nOnceFlag);
70800 break;
70803 /* Opcode: Param P1 P2 * * *
70805 ** This opcode is only ever present in sub-programs called via the
70806 ** OP_Program instruction. Copy a value currently stored in a memory
70807 ** cell of the calling (parent) frame to cell P2 in the current frames
70808 ** address space. This is used by trigger programs to access the new.*
70809 ** and old.* values.
70811 ** The address of the cell in the parent frame is determined by adding
70812 ** the value of the P1 argument to the value of the P1 argument to the
70813 ** calling OP_Program instruction.
70815 case OP_Param: { /* out2-prerelease */
70816 #if 0 /* local variables moved into u.ce */
70817 VdbeFrame *pFrame;
70818 Mem *pIn;
70819 #endif /* local variables moved into u.ce */
70820 u.ce.pFrame = p->pFrame;
70821 u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
70822 sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
70823 break;
70826 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
70828 #ifndef SQLITE_OMIT_FOREIGN_KEY
70829 /* Opcode: FkCounter P1 P2 * * *
70831 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
70832 ** If P1 is non-zero, the database constraint counter is incremented
70833 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
70834 ** statement counter is incremented (immediate foreign key constraints).
70836 case OP_FkCounter: {
70837 if( db->flags & SQLITE_DeferFKs ){
70838 db->nDeferredImmCons += pOp->p2;
70839 }else if( pOp->p1 ){
70840 db->nDeferredCons += pOp->p2;
70841 }else{
70842 p->nFkConstraint += pOp->p2;
70844 break;
70847 /* Opcode: FkIfZero P1 P2 * * *
70849 ** This opcode tests if a foreign key constraint-counter is currently zero.
70850 ** If so, jump to instruction P2. Otherwise, fall through to the next
70851 ** instruction.
70853 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
70854 ** is zero (the one that counts deferred constraint violations). If P1 is
70855 ** zero, the jump is taken if the statement constraint-counter is zero
70856 ** (immediate foreign key constraint violations).
70858 case OP_FkIfZero: { /* jump */
70859 if( pOp->p1 ){
70860 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
70861 }else{
70862 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
70864 break;
70866 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
70868 #ifndef SQLITE_OMIT_AUTOINCREMENT
70869 /* Opcode: MemMax P1 P2 * * *
70871 ** P1 is a register in the root frame of this VM (the root frame is
70872 ** different from the current frame if this instruction is being executed
70873 ** within a sub-program). Set the value of register P1 to the maximum of
70874 ** its current value and the value in register P2.
70876 ** This instruction throws an error if the memory cell is not initially
70877 ** an integer.
70879 case OP_MemMax: { /* in2 */
70880 #if 0 /* local variables moved into u.cf */
70881 Mem *pIn1;
70882 VdbeFrame *pFrame;
70883 #endif /* local variables moved into u.cf */
70884 if( p->pFrame ){
70885 for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
70886 u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
70887 }else{
70888 u.cf.pIn1 = &aMem[pOp->p1];
70890 assert( memIsValid(u.cf.pIn1) );
70891 sqlite3VdbeMemIntegerify(u.cf.pIn1);
70892 pIn2 = &aMem[pOp->p2];
70893 sqlite3VdbeMemIntegerify(pIn2);
70894 if( u.cf.pIn1->u.i<pIn2->u.i){
70895 u.cf.pIn1->u.i = pIn2->u.i;
70897 break;
70899 #endif /* SQLITE_OMIT_AUTOINCREMENT */
70901 /* Opcode: IfPos P1 P2 * * *
70903 ** If the value of register P1 is 1 or greater, jump to P2.
70905 ** It is illegal to use this instruction on a register that does
70906 ** not contain an integer. An assertion fault will result if you try.
70908 case OP_IfPos: { /* jump, in1 */
70909 pIn1 = &aMem[pOp->p1];
70910 assert( pIn1->flags&MEM_Int );
70911 if( pIn1->u.i>0 ){
70912 pc = pOp->p2 - 1;
70914 break;
70917 /* Opcode: IfNeg P1 P2 * * *
70919 ** If the value of register P1 is less than zero, jump to P2.
70921 ** It is illegal to use this instruction on a register that does
70922 ** not contain an integer. An assertion fault will result if you try.
70924 case OP_IfNeg: { /* jump, in1 */
70925 pIn1 = &aMem[pOp->p1];
70926 assert( pIn1->flags&MEM_Int );
70927 if( pIn1->u.i<0 ){
70928 pc = pOp->p2 - 1;
70930 break;
70933 /* Opcode: IfZero P1 P2 P3 * *
70935 ** The register P1 must contain an integer. Add literal P3 to the
70936 ** value in register P1. If the result is exactly 0, jump to P2.
70938 ** It is illegal to use this instruction on a register that does
70939 ** not contain an integer. An assertion fault will result if you try.
70941 case OP_IfZero: { /* jump, in1 */
70942 pIn1 = &aMem[pOp->p1];
70943 assert( pIn1->flags&MEM_Int );
70944 pIn1->u.i += pOp->p3;
70945 if( pIn1->u.i==0 ){
70946 pc = pOp->p2 - 1;
70948 break;
70951 /* Opcode: AggStep * P2 P3 P4 P5
70953 ** Execute the step function for an aggregate. The
70954 ** function has P5 arguments. P4 is a pointer to the FuncDef
70955 ** structure that specifies the function. Use register
70956 ** P3 as the accumulator.
70958 ** The P5 arguments are taken from register P2 and its
70959 ** successors.
70961 case OP_AggStep: {
70962 #if 0 /* local variables moved into u.cg */
70963 int n;
70964 int i;
70965 Mem *pMem;
70966 Mem *pRec;
70967 sqlite3_context ctx;
70968 sqlite3_value **apVal;
70969 #endif /* local variables moved into u.cg */
70971 u.cg.n = pOp->p5;
70972 assert( u.cg.n>=0 );
70973 u.cg.pRec = &aMem[pOp->p2];
70974 u.cg.apVal = p->apArg;
70975 assert( u.cg.apVal || u.cg.n==0 );
70976 for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
70977 assert( memIsValid(u.cg.pRec) );
70978 u.cg.apVal[u.cg.i] = u.cg.pRec;
70979 memAboutToChange(p, u.cg.pRec);
70980 sqlite3VdbeMemStoreType(u.cg.pRec);
70982 u.cg.ctx.pFunc = pOp->p4.pFunc;
70983 assert( pOp->p3>0 && pOp->p3<=p->nMem );
70984 u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
70985 u.cg.pMem->n++;
70986 u.cg.ctx.s.flags = MEM_Null;
70987 u.cg.ctx.s.z = 0;
70988 u.cg.ctx.s.zMalloc = 0;
70989 u.cg.ctx.s.xDel = 0;
70990 u.cg.ctx.s.db = db;
70991 u.cg.ctx.isError = 0;
70992 u.cg.ctx.pColl = 0;
70993 u.cg.ctx.skipFlag = 0;
70994 if( u.cg.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
70995 assert( pOp>p->aOp );
70996 assert( pOp[-1].p4type==P4_COLLSEQ );
70997 assert( pOp[-1].opcode==OP_CollSeq );
70998 u.cg.ctx.pColl = pOp[-1].p4.pColl;
71000 (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
71001 if( u.cg.ctx.isError ){
71002 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
71003 rc = u.cg.ctx.isError;
71005 if( u.cg.ctx.skipFlag ){
71006 assert( pOp[-1].opcode==OP_CollSeq );
71007 u.cg.i = pOp[-1].p1;
71008 if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
71011 sqlite3VdbeMemRelease(&u.cg.ctx.s);
71013 break;
71016 /* Opcode: AggFinal P1 P2 * P4 *
71018 ** Execute the finalizer function for an aggregate. P1 is
71019 ** the memory location that is the accumulator for the aggregate.
71021 ** P2 is the number of arguments that the step function takes and
71022 ** P4 is a pointer to the FuncDef for this function. The P2
71023 ** argument is not used by this opcode. It is only there to disambiguate
71024 ** functions that can take varying numbers of arguments. The
71025 ** P4 argument is only needed for the degenerate case where
71026 ** the step function was not previously called.
71028 case OP_AggFinal: {
71029 #if 0 /* local variables moved into u.ch */
71030 Mem *pMem;
71031 #endif /* local variables moved into u.ch */
71032 assert( pOp->p1>0 && pOp->p1<=p->nMem );
71033 u.ch.pMem = &aMem[pOp->p1];
71034 assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
71035 rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
71036 if( rc ){
71037 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
71039 sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
71040 UPDATE_MAX_BLOBSIZE(u.ch.pMem);
71041 if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
71042 goto too_big;
71044 break;
71047 #ifndef SQLITE_OMIT_WAL
71048 /* Opcode: Checkpoint P1 P2 P3 * *
71050 ** Checkpoint database P1. This is a no-op if P1 is not currently in
71051 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
71052 ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
71053 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
71054 ** WAL after the checkpoint into mem[P3+1] and the number of pages
71055 ** in the WAL that have been checkpointed after the checkpoint
71056 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
71057 ** mem[P3+2] are initialized to -1.
71059 case OP_Checkpoint: {
71060 #if 0 /* local variables moved into u.ci */
71061 int i; /* Loop counter */
71062 int aRes[3]; /* Results */
71063 Mem *pMem; /* Write results here */
71064 #endif /* local variables moved into u.ci */
71066 assert( p->readOnly==0 );
71067 u.ci.aRes[0] = 0;
71068 u.ci.aRes[1] = u.ci.aRes[2] = -1;
71069 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
71070 || pOp->p2==SQLITE_CHECKPOINT_FULL
71071 || pOp->p2==SQLITE_CHECKPOINT_RESTART
71073 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
71074 if( rc==SQLITE_BUSY ){
71075 rc = SQLITE_OK;
71076 u.ci.aRes[0] = 1;
71078 for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
71079 sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
71081 break;
71083 #endif
71085 #ifndef SQLITE_OMIT_PRAGMA
71086 /* Opcode: JournalMode P1 P2 P3 * P5
71088 ** Change the journal mode of database P1 to P3. P3 must be one of the
71089 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
71090 ** modes (delete, truncate, persist, off and memory), this is a simple
71091 ** operation. No IO is required.
71093 ** If changing into or out of WAL mode the procedure is more complicated.
71095 ** Write a string containing the final journal-mode to register P2.
71097 case OP_JournalMode: { /* out2-prerelease */
71098 #if 0 /* local variables moved into u.cj */
71099 Btree *pBt; /* Btree to change journal mode of */
71100 Pager *pPager; /* Pager associated with pBt */
71101 int eNew; /* New journal mode */
71102 int eOld; /* The old journal mode */
71103 #ifndef SQLITE_OMIT_WAL
71104 const char *zFilename; /* Name of database file for pPager */
71105 #endif
71106 #endif /* local variables moved into u.cj */
71108 u.cj.eNew = pOp->p3;
71109 assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
71110 || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
71111 || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
71112 || u.cj.eNew==PAGER_JOURNALMODE_OFF
71113 || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
71114 || u.cj.eNew==PAGER_JOURNALMODE_WAL
71115 || u.cj.eNew==PAGER_JOURNALMODE_QUERY
71117 assert( pOp->p1>=0 && pOp->p1<db->nDb );
71118 assert( p->readOnly==0 );
71120 u.cj.pBt = db->aDb[pOp->p1].pBt;
71121 u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
71122 u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
71123 if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
71124 if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
71126 #ifndef SQLITE_OMIT_WAL
71127 u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
71129 /* Do not allow a transition to journal_mode=WAL for a database
71130 ** in temporary storage or if the VFS does not support shared memory
71132 if( u.cj.eNew==PAGER_JOURNALMODE_WAL
71133 && (sqlite3Strlen30(u.cj.zFilename)==0 /* Temp file */
71134 || !sqlite3PagerWalSupported(u.cj.pPager)) /* No shared-memory support */
71136 u.cj.eNew = u.cj.eOld;
71139 if( (u.cj.eNew!=u.cj.eOld)
71140 && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
71142 if( !db->autoCommit || db->nVdbeRead>1 ){
71143 rc = SQLITE_ERROR;
71144 sqlite3SetString(&p->zErrMsg, db,
71145 "cannot change %s wal mode from within a transaction",
71146 (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
71148 break;
71149 }else{
71151 if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
71152 /* If leaving WAL mode, close the log file. If successful, the call
71153 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
71154 ** file. An EXCLUSIVE lock may still be held on the database file
71155 ** after a successful return.
71157 rc = sqlite3PagerCloseWal(u.cj.pPager);
71158 if( rc==SQLITE_OK ){
71159 sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
71161 }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
71162 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
71163 ** as an intermediate */
71164 sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
71167 /* Open a transaction on the database file. Regardless of the journal
71168 ** mode, this transaction always uses a rollback journal.
71170 assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
71171 if( rc==SQLITE_OK ){
71172 rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
71176 #endif /* ifndef SQLITE_OMIT_WAL */
71178 if( rc ){
71179 u.cj.eNew = u.cj.eOld;
71181 u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
71183 pOut = &aMem[pOp->p2];
71184 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
71185 pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
71186 pOut->n = sqlite3Strlen30(pOut->z);
71187 pOut->enc = SQLITE_UTF8;
71188 sqlite3VdbeChangeEncoding(pOut, encoding);
71189 break;
71191 #endif /* SQLITE_OMIT_PRAGMA */
71193 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
71194 /* Opcode: Vacuum * * * * *
71196 ** Vacuum the entire database. This opcode will cause other virtual
71197 ** machines to be created and run. It may not be called from within
71198 ** a transaction.
71200 case OP_Vacuum: {
71201 assert( p->readOnly==0 );
71202 rc = sqlite3RunVacuum(&p->zErrMsg, db);
71203 break;
71205 #endif
71207 #if !defined(SQLITE_OMIT_AUTOVACUUM)
71208 /* Opcode: IncrVacuum P1 P2 * * *
71210 ** Perform a single step of the incremental vacuum procedure on
71211 ** the P1 database. If the vacuum has finished, jump to instruction
71212 ** P2. Otherwise, fall through to the next instruction.
71214 case OP_IncrVacuum: { /* jump */
71215 #if 0 /* local variables moved into u.ck */
71216 Btree *pBt;
71217 #endif /* local variables moved into u.ck */
71219 assert( pOp->p1>=0 && pOp->p1<db->nDb );
71220 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
71221 assert( p->readOnly==0 );
71222 u.ck.pBt = db->aDb[pOp->p1].pBt;
71223 rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
71224 if( rc==SQLITE_DONE ){
71225 pc = pOp->p2 - 1;
71226 rc = SQLITE_OK;
71228 break;
71230 #endif
71232 /* Opcode: Expire P1 * * * *
71234 ** Cause precompiled statements to become expired. An expired statement
71235 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
71236 ** (via sqlite3_step()).
71238 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
71239 ** then only the currently executing statement is affected.
71241 case OP_Expire: {
71242 if( !pOp->p1 ){
71243 sqlite3ExpirePreparedStatements(db);
71244 }else{
71245 p->expired = 1;
71247 break;
71250 #ifndef SQLITE_OMIT_SHARED_CACHE
71251 /* Opcode: TableLock P1 P2 P3 P4 *
71253 ** Obtain a lock on a particular table. This instruction is only used when
71254 ** the shared-cache feature is enabled.
71256 ** P1 is the index of the database in sqlite3.aDb[] of the database
71257 ** on which the lock is acquired. A readlock is obtained if P3==0 or
71258 ** a write lock if P3==1.
71260 ** P2 contains the root-page of the table to lock.
71262 ** P4 contains a pointer to the name of the table being locked. This is only
71263 ** used to generate an error message if the lock cannot be obtained.
71265 case OP_TableLock: {
71266 u8 isWriteLock = (u8)pOp->p3;
71267 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
71268 int p1 = pOp->p1;
71269 assert( p1>=0 && p1<db->nDb );
71270 assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
71271 assert( isWriteLock==0 || isWriteLock==1 );
71272 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
71273 if( (rc&0xFF)==SQLITE_LOCKED ){
71274 const char *z = pOp->p4.z;
71275 sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
71278 break;
71280 #endif /* SQLITE_OMIT_SHARED_CACHE */
71282 #ifndef SQLITE_OMIT_VIRTUALTABLE
71283 /* Opcode: VBegin * * * P4 *
71285 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
71286 ** xBegin method for that table.
71288 ** Also, whether or not P4 is set, check that this is not being called from
71289 ** within a callback to a virtual table xSync() method. If it is, the error
71290 ** code will be set to SQLITE_LOCKED.
71292 case OP_VBegin: {
71293 #if 0 /* local variables moved into u.cl */
71294 VTable *pVTab;
71295 #endif /* local variables moved into u.cl */
71296 u.cl.pVTab = pOp->p4.pVtab;
71297 rc = sqlite3VtabBegin(db, u.cl.pVTab);
71298 if( u.cl.pVTab ) sqlite3VtabImportErrmsg(p, u.cl.pVTab->pVtab);
71299 break;
71301 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71303 #ifndef SQLITE_OMIT_VIRTUALTABLE
71304 /* Opcode: VCreate P1 * * P4 *
71306 ** P4 is the name of a virtual table in database P1. Call the xCreate method
71307 ** for that table.
71309 case OP_VCreate: {
71310 rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
71311 break;
71313 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71315 #ifndef SQLITE_OMIT_VIRTUALTABLE
71316 /* Opcode: VDestroy P1 * * P4 *
71318 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
71319 ** of that table.
71321 case OP_VDestroy: {
71322 p->inVtabMethod = 2;
71323 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
71324 p->inVtabMethod = 0;
71325 break;
71327 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71329 #ifndef SQLITE_OMIT_VIRTUALTABLE
71330 /* Opcode: VOpen P1 * * P4 *
71332 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71333 ** P1 is a cursor number. This opcode opens a cursor to the virtual
71334 ** table and stores that cursor in P1.
71336 case OP_VOpen: {
71337 #if 0 /* local variables moved into u.cm */
71338 VdbeCursor *pCur;
71339 sqlite3_vtab_cursor *pVtabCursor;
71340 sqlite3_vtab *pVtab;
71341 sqlite3_module *pModule;
71342 #endif /* local variables moved into u.cm */
71344 assert( p->bIsReader );
71345 u.cm.pCur = 0;
71346 u.cm.pVtabCursor = 0;
71347 u.cm.pVtab = pOp->p4.pVtab->pVtab;
71348 u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
71349 assert(u.cm.pVtab && u.cm.pModule);
71350 rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
71351 sqlite3VtabImportErrmsg(p, u.cm.pVtab);
71352 if( SQLITE_OK==rc ){
71353 /* Initialize sqlite3_vtab_cursor base class */
71354 u.cm.pVtabCursor->pVtab = u.cm.pVtab;
71356 /* Initialize vdbe cursor object */
71357 u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
71358 if( u.cm.pCur ){
71359 u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
71360 u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
71361 }else{
71362 db->mallocFailed = 1;
71363 u.cm.pModule->xClose(u.cm.pVtabCursor);
71366 break;
71368 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71370 #ifndef SQLITE_OMIT_VIRTUALTABLE
71371 /* Opcode: VFilter P1 P2 P3 P4 *
71373 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
71374 ** the filtered result set is empty.
71376 ** P4 is either NULL or a string that was generated by the xBestIndex
71377 ** method of the module. The interpretation of the P4 string is left
71378 ** to the module implementation.
71380 ** This opcode invokes the xFilter method on the virtual table specified
71381 ** by P1. The integer query plan parameter to xFilter is stored in register
71382 ** P3. Register P3+1 stores the argc parameter to be passed to the
71383 ** xFilter method. Registers P3+2..P3+1+argc are the argc
71384 ** additional parameters which are passed to
71385 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
71387 ** A jump is made to P2 if the result set after filtering would be empty.
71389 case OP_VFilter: { /* jump */
71390 #if 0 /* local variables moved into u.cn */
71391 int nArg;
71392 int iQuery;
71393 const sqlite3_module *pModule;
71394 Mem *pQuery;
71395 Mem *pArgc;
71396 sqlite3_vtab_cursor *pVtabCursor;
71397 sqlite3_vtab *pVtab;
71398 VdbeCursor *pCur;
71399 int res;
71400 int i;
71401 Mem **apArg;
71402 #endif /* local variables moved into u.cn */
71404 u.cn.pQuery = &aMem[pOp->p3];
71405 u.cn.pArgc = &u.cn.pQuery[1];
71406 u.cn.pCur = p->apCsr[pOp->p1];
71407 assert( memIsValid(u.cn.pQuery) );
71408 REGISTER_TRACE(pOp->p3, u.cn.pQuery);
71409 assert( u.cn.pCur->pVtabCursor );
71410 u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
71411 u.cn.pVtab = u.cn.pVtabCursor->pVtab;
71412 u.cn.pModule = u.cn.pVtab->pModule;
71414 /* Grab the index number and argc parameters */
71415 assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
71416 u.cn.nArg = (int)u.cn.pArgc->u.i;
71417 u.cn.iQuery = (int)u.cn.pQuery->u.i;
71419 /* Invoke the xFilter method */
71421 u.cn.res = 0;
71422 u.cn.apArg = p->apArg;
71423 for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
71424 u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
71425 sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
71428 p->inVtabMethod = 1;
71429 rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
71430 p->inVtabMethod = 0;
71431 sqlite3VtabImportErrmsg(p, u.cn.pVtab);
71432 if( rc==SQLITE_OK ){
71433 u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
71436 if( u.cn.res ){
71437 pc = pOp->p2 - 1;
71440 u.cn.pCur->nullRow = 0;
71442 break;
71444 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71446 #ifndef SQLITE_OMIT_VIRTUALTABLE
71447 /* Opcode: VColumn P1 P2 P3 * *
71449 ** Store the value of the P2-th column of
71450 ** the row of the virtual-table that the
71451 ** P1 cursor is pointing to into register P3.
71453 case OP_VColumn: {
71454 #if 0 /* local variables moved into u.co */
71455 sqlite3_vtab *pVtab;
71456 const sqlite3_module *pModule;
71457 Mem *pDest;
71458 sqlite3_context sContext;
71459 #endif /* local variables moved into u.co */
71461 VdbeCursor *pCur = p->apCsr[pOp->p1];
71462 assert( pCur->pVtabCursor );
71463 assert( pOp->p3>0 && pOp->p3<=p->nMem );
71464 u.co.pDest = &aMem[pOp->p3];
71465 memAboutToChange(p, u.co.pDest);
71466 if( pCur->nullRow ){
71467 sqlite3VdbeMemSetNull(u.co.pDest);
71468 break;
71470 u.co.pVtab = pCur->pVtabCursor->pVtab;
71471 u.co.pModule = u.co.pVtab->pModule;
71472 assert( u.co.pModule->xColumn );
71473 memset(&u.co.sContext, 0, sizeof(u.co.sContext));
71475 /* The output cell may already have a buffer allocated. Move
71476 ** the current contents to u.co.sContext.s so in case the user-function
71477 ** can use the already allocated buffer instead of allocating a
71478 ** new one.
71480 sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
71481 MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
71483 rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
71484 sqlite3VtabImportErrmsg(p, u.co.pVtab);
71485 if( u.co.sContext.isError ){
71486 rc = u.co.sContext.isError;
71489 /* Copy the result of the function to the P3 register. We
71490 ** do this regardless of whether or not an error occurred to ensure any
71491 ** dynamic allocation in u.co.sContext.s (a Mem struct) is released.
71493 sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
71494 sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
71495 REGISTER_TRACE(pOp->p3, u.co.pDest);
71496 UPDATE_MAX_BLOBSIZE(u.co.pDest);
71498 if( sqlite3VdbeMemTooBig(u.co.pDest) ){
71499 goto too_big;
71501 break;
71503 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71505 #ifndef SQLITE_OMIT_VIRTUALTABLE
71506 /* Opcode: VNext P1 P2 * * *
71508 ** Advance virtual table P1 to the next row in its result set and
71509 ** jump to instruction P2. Or, if the virtual table has reached
71510 ** the end of its result set, then fall through to the next instruction.
71512 case OP_VNext: { /* jump */
71513 #if 0 /* local variables moved into u.cp */
71514 sqlite3_vtab *pVtab;
71515 const sqlite3_module *pModule;
71516 int res;
71517 VdbeCursor *pCur;
71518 #endif /* local variables moved into u.cp */
71520 u.cp.res = 0;
71521 u.cp.pCur = p->apCsr[pOp->p1];
71522 assert( u.cp.pCur->pVtabCursor );
71523 if( u.cp.pCur->nullRow ){
71524 break;
71526 u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
71527 u.cp.pModule = u.cp.pVtab->pModule;
71528 assert( u.cp.pModule->xNext );
71530 /* Invoke the xNext() method of the module. There is no way for the
71531 ** underlying implementation to return an error if one occurs during
71532 ** xNext(). Instead, if an error occurs, true is returned (indicating that
71533 ** data is available) and the error code returned when xColumn or
71534 ** some other method is next invoked on the save virtual table cursor.
71536 p->inVtabMethod = 1;
71537 rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
71538 p->inVtabMethod = 0;
71539 sqlite3VtabImportErrmsg(p, u.cp.pVtab);
71540 if( rc==SQLITE_OK ){
71541 u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
71544 if( !u.cp.res ){
71545 /* If there is data, jump to P2 */
71546 pc = pOp->p2 - 1;
71548 goto check_for_interrupt;
71550 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71552 #ifndef SQLITE_OMIT_VIRTUALTABLE
71553 /* Opcode: VRename P1 * * P4 *
71555 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71556 ** This opcode invokes the corresponding xRename method. The value
71557 ** in register P1 is passed as the zName argument to the xRename method.
71559 case OP_VRename: {
71560 #if 0 /* local variables moved into u.cq */
71561 sqlite3_vtab *pVtab;
71562 Mem *pName;
71563 #endif /* local variables moved into u.cq */
71565 u.cq.pVtab = pOp->p4.pVtab->pVtab;
71566 u.cq.pName = &aMem[pOp->p1];
71567 assert( u.cq.pVtab->pModule->xRename );
71568 assert( memIsValid(u.cq.pName) );
71569 assert( p->readOnly==0 );
71570 REGISTER_TRACE(pOp->p1, u.cq.pName);
71571 assert( u.cq.pName->flags & MEM_Str );
71572 testcase( u.cq.pName->enc==SQLITE_UTF8 );
71573 testcase( u.cq.pName->enc==SQLITE_UTF16BE );
71574 testcase( u.cq.pName->enc==SQLITE_UTF16LE );
71575 rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
71576 if( rc==SQLITE_OK ){
71577 rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
71578 sqlite3VtabImportErrmsg(p, u.cq.pVtab);
71579 p->expired = 0;
71581 break;
71583 #endif
71585 #ifndef SQLITE_OMIT_VIRTUALTABLE
71586 /* Opcode: VUpdate P1 P2 P3 P4 *
71588 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71589 ** This opcode invokes the corresponding xUpdate method. P2 values
71590 ** are contiguous memory cells starting at P3 to pass to the xUpdate
71591 ** invocation. The value in register (P3+P2-1) corresponds to the
71592 ** p2th element of the argv array passed to xUpdate.
71594 ** The xUpdate method will do a DELETE or an INSERT or both.
71595 ** The argv[0] element (which corresponds to memory cell P3)
71596 ** is the rowid of a row to delete. If argv[0] is NULL then no
71597 ** deletion occurs. The argv[1] element is the rowid of the new
71598 ** row. This can be NULL to have the virtual table select the new
71599 ** rowid for itself. The subsequent elements in the array are
71600 ** the values of columns in the new row.
71602 ** If P2==1 then no insert is performed. argv[0] is the rowid of
71603 ** a row to delete.
71605 ** P1 is a boolean flag. If it is set to true and the xUpdate call
71606 ** is successful, then the value returned by sqlite3_last_insert_rowid()
71607 ** is set to the value of the rowid for the row just inserted.
71609 case OP_VUpdate: {
71610 #if 0 /* local variables moved into u.cr */
71611 sqlite3_vtab *pVtab;
71612 sqlite3_module *pModule;
71613 int nArg;
71614 int i;
71615 sqlite_int64 rowid;
71616 Mem **apArg;
71617 Mem *pX;
71618 #endif /* local variables moved into u.cr */
71620 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
71621 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
71623 assert( p->readOnly==0 );
71624 u.cr.pVtab = pOp->p4.pVtab->pVtab;
71625 u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
71626 u.cr.nArg = pOp->p2;
71627 assert( pOp->p4type==P4_VTAB );
71628 if( ALWAYS(u.cr.pModule->xUpdate) ){
71629 u8 vtabOnConflict = db->vtabOnConflict;
71630 u.cr.apArg = p->apArg;
71631 u.cr.pX = &aMem[pOp->p3];
71632 for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
71633 assert( memIsValid(u.cr.pX) );
71634 memAboutToChange(p, u.cr.pX);
71635 sqlite3VdbeMemStoreType(u.cr.pX);
71636 u.cr.apArg[u.cr.i] = u.cr.pX;
71637 u.cr.pX++;
71639 db->vtabOnConflict = pOp->p5;
71640 rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
71641 db->vtabOnConflict = vtabOnConflict;
71642 sqlite3VtabImportErrmsg(p, u.cr.pVtab);
71643 if( rc==SQLITE_OK && pOp->p1 ){
71644 assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
71645 db->lastRowid = lastRowid = u.cr.rowid;
71647 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
71648 if( pOp->p5==OE_Ignore ){
71649 rc = SQLITE_OK;
71650 }else{
71651 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
71653 }else{
71654 p->nChange++;
71657 break;
71659 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71661 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
71662 /* Opcode: Pagecount P1 P2 * * *
71664 ** Write the current number of pages in database P1 to memory cell P2.
71666 case OP_Pagecount: { /* out2-prerelease */
71667 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
71668 break;
71670 #endif
71673 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
71674 /* Opcode: MaxPgcnt P1 P2 P3 * *
71676 ** Try to set the maximum page count for database P1 to the value in P3.
71677 ** Do not let the maximum page count fall below the current page count and
71678 ** do not change the maximum page count value if P3==0.
71680 ** Store the maximum page count after the change in register P2.
71682 case OP_MaxPgcnt: { /* out2-prerelease */
71683 unsigned int newMax;
71684 Btree *pBt;
71686 pBt = db->aDb[pOp->p1].pBt;
71687 newMax = 0;
71688 if( pOp->p3 ){
71689 newMax = sqlite3BtreeLastPage(pBt);
71690 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
71692 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
71693 break;
71695 #endif
71698 #ifndef SQLITE_OMIT_TRACE
71699 /* Opcode: Trace * * * P4 *
71701 ** If tracing is enabled (by the sqlite3_trace()) interface, then
71702 ** the UTF-8 string contained in P4 is emitted on the trace callback.
71704 case OP_Trace: {
71705 #if 0 /* local variables moved into u.cs */
71706 char *zTrace;
71707 char *z;
71708 #endif /* local variables moved into u.cs */
71710 if( db->xTrace
71711 && !p->doingRerun
71712 && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71714 u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
71715 db->xTrace(db->pTraceArg, u.cs.z);
71716 sqlite3DbFree(db, u.cs.z);
71718 #ifdef SQLITE_DEBUG
71719 if( (db->flags & SQLITE_SqlTrace)!=0
71720 && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71722 sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
71724 #endif /* SQLITE_DEBUG */
71725 break;
71727 #endif
71730 /* Opcode: Noop * * * * *
71732 ** Do nothing. This instruction is often useful as a jump
71733 ** destination.
71736 ** The magic Explain opcode are only inserted when explain==2 (which
71737 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
71738 ** This opcode records information from the optimizer. It is the
71739 ** the same as a no-op. This opcodesnever appears in a real VM program.
71741 default: { /* This is really OP_Noop and OP_Explain */
71742 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
71743 break;
71746 /*****************************************************************************
71747 ** The cases of the switch statement above this line should all be indented
71748 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
71749 ** readability. From this point on down, the normal indentation rules are
71750 ** restored.
71751 *****************************************************************************/
71754 #ifdef VDBE_PROFILE
71756 u64 elapsed = sqlite3Hwtime() - start;
71757 pOp->cycles += elapsed;
71758 pOp->cnt++;
71759 #if 0
71760 fprintf(stdout, "%10llu ", elapsed);
71761 sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
71762 #endif
71764 #endif
71766 /* The following code adds nothing to the actual functionality
71767 ** of the program. It is only here for testing and debugging.
71768 ** On the other hand, it does burn CPU cycles every time through
71769 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
71771 #ifndef NDEBUG
71772 assert( pc>=-1 && pc<p->nOp );
71774 #ifdef SQLITE_DEBUG
71775 if( p->trace ){
71776 if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
71777 if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
71778 registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
71780 if( pOp->opflags & OPFLG_OUT3 ){
71781 registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
71784 #endif /* SQLITE_DEBUG */
71785 #endif /* NDEBUG */
71786 } /* The end of the for(;;) loop the loops through opcodes */
71788 /* If we reach this point, it means that execution is finished with
71789 ** an error of some kind.
71791 vdbe_error_halt:
71792 assert( rc );
71793 p->rc = rc;
71794 testcase( sqlite3GlobalConfig.xLog!=0 );
71795 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
71796 pc, p->zSql, p->zErrMsg);
71797 sqlite3VdbeHalt(p);
71798 if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
71799 rc = SQLITE_ERROR;
71800 if( resetSchemaOnFault>0 ){
71801 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
71804 /* This is the only way out of this procedure. We have to
71805 ** release the mutexes on btrees that were acquired at the
71806 ** top. */
71807 vdbe_return:
71808 db->lastRowid = lastRowid;
71809 testcase( nVmStep>0 );
71810 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
71811 sqlite3VdbeLeave(p);
71812 return rc;
71814 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
71815 ** is encountered.
71817 too_big:
71818 sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
71819 rc = SQLITE_TOOBIG;
71820 goto vdbe_error_halt;
71822 /* Jump to here if a malloc() fails.
71824 no_mem:
71825 db->mallocFailed = 1;
71826 sqlite3SetString(&p->zErrMsg, db, "out of memory");
71827 rc = SQLITE_NOMEM;
71828 goto vdbe_error_halt;
71830 /* Jump to here for any other kind of fatal error. The "rc" variable
71831 ** should hold the error number.
71833 abort_due_to_error:
71834 assert( p->zErrMsg==0 );
71835 if( db->mallocFailed ) rc = SQLITE_NOMEM;
71836 if( rc!=SQLITE_IOERR_NOMEM ){
71837 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71839 goto vdbe_error_halt;
71841 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
71842 ** flag.
71844 abort_due_to_interrupt:
71845 assert( db->u1.isInterrupted );
71846 rc = SQLITE_INTERRUPT;
71847 p->rc = rc;
71848 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71849 goto vdbe_error_halt;
71852 /************** End of vdbe.c ************************************************/
71853 /************** Begin file vdbeblob.c ****************************************/
71855 ** 2007 May 1
71857 ** The author disclaims copyright to this source code. In place of
71858 ** a legal notice, here is a blessing:
71860 ** May you do good and not evil.
71861 ** May you find forgiveness for yourself and forgive others.
71862 ** May you share freely, never taking more than you give.
71864 *************************************************************************
71866 ** This file contains code used to implement incremental BLOB I/O.
71870 #ifndef SQLITE_OMIT_INCRBLOB
71873 ** Valid sqlite3_blob* handles point to Incrblob structures.
71875 typedef struct Incrblob Incrblob;
71876 struct Incrblob {
71877 int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
71878 int nByte; /* Size of open blob, in bytes */
71879 int iOffset; /* Byte offset of blob in cursor data */
71880 int iCol; /* Table column this handle is open on */
71881 BtCursor *pCsr; /* Cursor pointing at blob row */
71882 sqlite3_stmt *pStmt; /* Statement holding cursor open */
71883 sqlite3 *db; /* The associated database */
71888 ** This function is used by both blob_open() and blob_reopen(). It seeks
71889 ** the b-tree cursor associated with blob handle p to point to row iRow.
71890 ** If successful, SQLITE_OK is returned and subsequent calls to
71891 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
71893 ** If an error occurs, or if the specified row does not exist or does not
71894 ** contain a value of type TEXT or BLOB in the column nominated when the
71895 ** blob handle was opened, then an error code is returned and *pzErr may
71896 ** be set to point to a buffer containing an error message. It is the
71897 ** responsibility of the caller to free the error message buffer using
71898 ** sqlite3DbFree().
71900 ** If an error does occur, then the b-tree cursor is closed. All subsequent
71901 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
71902 ** immediately return SQLITE_ABORT.
71904 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
71905 int rc; /* Error code */
71906 char *zErr = 0; /* Error message */
71907 Vdbe *v = (Vdbe *)p->pStmt;
71909 /* Set the value of the SQL statements only variable to integer iRow.
71910 ** This is done directly instead of using sqlite3_bind_int64() to avoid
71911 ** triggering asserts related to mutexes.
71913 assert( v->aVar[0].flags&MEM_Int );
71914 v->aVar[0].u.i = iRow;
71916 rc = sqlite3_step(p->pStmt);
71917 if( rc==SQLITE_ROW ){
71918 u32 type = v->apCsr[0]->aType[p->iCol];
71919 if( type<12 ){
71920 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
71921 type==0?"null": type==7?"real": "integer"
71923 rc = SQLITE_ERROR;
71924 sqlite3_finalize(p->pStmt);
71925 p->pStmt = 0;
71926 }else{
71927 p->iOffset = v->apCsr[0]->aOffset[p->iCol];
71928 p->nByte = sqlite3VdbeSerialTypeLen(type);
71929 p->pCsr = v->apCsr[0]->pCursor;
71930 sqlite3BtreeEnterCursor(p->pCsr);
71931 sqlite3BtreeCacheOverflow(p->pCsr);
71932 sqlite3BtreeLeaveCursor(p->pCsr);
71936 if( rc==SQLITE_ROW ){
71937 rc = SQLITE_OK;
71938 }else if( p->pStmt ){
71939 rc = sqlite3_finalize(p->pStmt);
71940 p->pStmt = 0;
71941 if( rc==SQLITE_OK ){
71942 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
71943 rc = SQLITE_ERROR;
71944 }else{
71945 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
71949 assert( rc!=SQLITE_OK || zErr==0 );
71950 assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
71952 *pzErr = zErr;
71953 return rc;
71957 ** Open a blob handle.
71959 SQLITE_API int sqlite3_blob_open(
71960 sqlite3* db, /* The database connection */
71961 const char *zDb, /* The attached database containing the blob */
71962 const char *zTable, /* The table containing the blob */
71963 const char *zColumn, /* The column containing the blob */
71964 sqlite_int64 iRow, /* The row containing the glob */
71965 int flags, /* True -> read/write access, false -> read-only */
71966 sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
71968 int nAttempt = 0;
71969 int iCol; /* Index of zColumn in row-record */
71971 /* This VDBE program seeks a btree cursor to the identified
71972 ** db/table/row entry. The reason for using a vdbe program instead
71973 ** of writing code to use the b-tree layer directly is that the
71974 ** vdbe program will take advantage of the various transaction,
71975 ** locking and error handling infrastructure built into the vdbe.
71977 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
71978 ** Code external to the Vdbe then "borrows" the b-tree cursor and
71979 ** uses it to implement the blob_read(), blob_write() and
71980 ** blob_bytes() functions.
71982 ** The sqlite3_blob_close() function finalizes the vdbe program,
71983 ** which closes the b-tree cursor and (possibly) commits the
71984 ** transaction.
71986 static const VdbeOpList openBlob[] = {
71987 {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
71988 {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
71989 {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
71991 /* One of the following two instructions is replaced by an OP_Noop. */
71992 {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
71993 {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
71995 {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
71996 {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
71997 {OP_Column, 0, 0, 1}, /* 7 */
71998 {OP_ResultRow, 1, 0, 0}, /* 8 */
71999 {OP_Goto, 0, 5, 0}, /* 9 */
72000 {OP_Close, 0, 0, 0}, /* 10 */
72001 {OP_Halt, 0, 0, 0}, /* 11 */
72004 int rc = SQLITE_OK;
72005 char *zErr = 0;
72006 Table *pTab;
72007 Parse *pParse = 0;
72008 Incrblob *pBlob = 0;
72010 flags = !!flags; /* flags = (flags ? 1 : 0); */
72011 *ppBlob = 0;
72013 sqlite3_mutex_enter(db->mutex);
72015 pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
72016 if( !pBlob ) goto blob_open_out;
72017 pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
72018 if( !pParse ) goto blob_open_out;
72020 do {
72021 memset(pParse, 0, sizeof(Parse));
72022 pParse->db = db;
72023 sqlite3DbFree(db, zErr);
72024 zErr = 0;
72026 sqlite3BtreeEnterAll(db);
72027 pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
72028 if( pTab && IsVirtual(pTab) ){
72029 pTab = 0;
72030 sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
72032 #ifndef SQLITE_OMIT_VIEW
72033 if( pTab && pTab->pSelect ){
72034 pTab = 0;
72035 sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
72037 #endif
72038 if( !pTab ){
72039 if( pParse->zErrMsg ){
72040 sqlite3DbFree(db, zErr);
72041 zErr = pParse->zErrMsg;
72042 pParse->zErrMsg = 0;
72044 rc = SQLITE_ERROR;
72045 sqlite3BtreeLeaveAll(db);
72046 goto blob_open_out;
72049 /* Now search pTab for the exact column. */
72050 for(iCol=0; iCol<pTab->nCol; iCol++) {
72051 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
72052 break;
72055 if( iCol==pTab->nCol ){
72056 sqlite3DbFree(db, zErr);
72057 zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
72058 rc = SQLITE_ERROR;
72059 sqlite3BtreeLeaveAll(db);
72060 goto blob_open_out;
72063 /* If the value is being opened for writing, check that the
72064 ** column is not indexed, and that it is not part of a foreign key.
72065 ** It is against the rules to open a column to which either of these
72066 ** descriptions applies for writing. */
72067 if( flags ){
72068 const char *zFault = 0;
72069 Index *pIdx;
72070 #ifndef SQLITE_OMIT_FOREIGN_KEY
72071 if( db->flags&SQLITE_ForeignKeys ){
72072 /* Check that the column is not part of an FK child key definition. It
72073 ** is not necessary to check if it is part of a parent key, as parent
72074 ** key columns must be indexed. The check below will pick up this
72075 ** case. */
72076 FKey *pFKey;
72077 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
72078 int j;
72079 for(j=0; j<pFKey->nCol; j++){
72080 if( pFKey->aCol[j].iFrom==iCol ){
72081 zFault = "foreign key";
72086 #endif
72087 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
72088 int j;
72089 for(j=0; j<pIdx->nColumn; j++){
72090 if( pIdx->aiColumn[j]==iCol ){
72091 zFault = "indexed";
72095 if( zFault ){
72096 sqlite3DbFree(db, zErr);
72097 zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
72098 rc = SQLITE_ERROR;
72099 sqlite3BtreeLeaveAll(db);
72100 goto blob_open_out;
72104 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
72105 assert( pBlob->pStmt || db->mallocFailed );
72106 if( pBlob->pStmt ){
72107 Vdbe *v = (Vdbe *)pBlob->pStmt;
72108 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72110 sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
72113 /* Configure the OP_Transaction */
72114 sqlite3VdbeChangeP1(v, 0, iDb);
72115 sqlite3VdbeChangeP2(v, 0, flags);
72117 /* Configure the OP_VerifyCookie */
72118 sqlite3VdbeChangeP1(v, 1, iDb);
72119 sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
72120 sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
72122 /* Make sure a mutex is held on the table to be accessed */
72123 sqlite3VdbeUsesBtree(v, iDb);
72125 /* Configure the OP_TableLock instruction */
72126 #ifdef SQLITE_OMIT_SHARED_CACHE
72127 sqlite3VdbeChangeToNoop(v, 2);
72128 #else
72129 sqlite3VdbeChangeP1(v, 2, iDb);
72130 sqlite3VdbeChangeP2(v, 2, pTab->tnum);
72131 sqlite3VdbeChangeP3(v, 2, flags);
72132 sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
72133 #endif
72135 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
72136 ** parameter of the other to pTab->tnum. */
72137 sqlite3VdbeChangeToNoop(v, 4 - flags);
72138 sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
72139 sqlite3VdbeChangeP3(v, 3 + flags, iDb);
72141 /* Configure the number of columns. Configure the cursor to
72142 ** think that the table has one more column than it really
72143 ** does. An OP_Column to retrieve this imaginary column will
72144 ** always return an SQL NULL. This is useful because it means
72145 ** we can invoke OP_Column to fill in the vdbe cursors type
72146 ** and offset cache without causing any IO.
72148 sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
72149 sqlite3VdbeChangeP2(v, 7, pTab->nCol);
72150 if( !db->mallocFailed ){
72151 pParse->nVar = 1;
72152 pParse->nMem = 1;
72153 pParse->nTab = 1;
72154 sqlite3VdbeMakeReady(v, pParse);
72158 pBlob->flags = flags;
72159 pBlob->iCol = iCol;
72160 pBlob->db = db;
72161 sqlite3BtreeLeaveAll(db);
72162 if( db->mallocFailed ){
72163 goto blob_open_out;
72165 sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
72166 rc = blobSeekToRow(pBlob, iRow, &zErr);
72167 } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
72169 blob_open_out:
72170 if( rc==SQLITE_OK && db->mallocFailed==0 ){
72171 *ppBlob = (sqlite3_blob *)pBlob;
72172 }else{
72173 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
72174 sqlite3DbFree(db, pBlob);
72176 sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
72177 sqlite3DbFree(db, zErr);
72178 sqlite3StackFree(db, pParse);
72179 rc = sqlite3ApiExit(db, rc);
72180 sqlite3_mutex_leave(db->mutex);
72181 return rc;
72185 ** Close a blob handle that was previously created using
72186 ** sqlite3_blob_open().
72188 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
72189 Incrblob *p = (Incrblob *)pBlob;
72190 int rc;
72191 sqlite3 *db;
72193 if( p ){
72194 db = p->db;
72195 sqlite3_mutex_enter(db->mutex);
72196 rc = sqlite3_finalize(p->pStmt);
72197 sqlite3DbFree(db, p);
72198 sqlite3_mutex_leave(db->mutex);
72199 }else{
72200 rc = SQLITE_OK;
72202 return rc;
72206 ** Perform a read or write operation on a blob
72208 static int blobReadWrite(
72209 sqlite3_blob *pBlob,
72210 void *z,
72211 int n,
72212 int iOffset,
72213 int (*xCall)(BtCursor*, u32, u32, void*)
72215 int rc;
72216 Incrblob *p = (Incrblob *)pBlob;
72217 Vdbe *v;
72218 sqlite3 *db;
72220 if( p==0 ) return SQLITE_MISUSE_BKPT;
72221 db = p->db;
72222 sqlite3_mutex_enter(db->mutex);
72223 v = (Vdbe*)p->pStmt;
72225 if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
72226 /* Request is out of range. Return a transient error. */
72227 rc = SQLITE_ERROR;
72228 sqlite3Error(db, SQLITE_ERROR, 0);
72229 }else if( v==0 ){
72230 /* If there is no statement handle, then the blob-handle has
72231 ** already been invalidated. Return SQLITE_ABORT in this case.
72233 rc = SQLITE_ABORT;
72234 }else{
72235 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
72236 ** returned, clean-up the statement handle.
72238 assert( db == v->db );
72239 sqlite3BtreeEnterCursor(p->pCsr);
72240 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
72241 sqlite3BtreeLeaveCursor(p->pCsr);
72242 if( rc==SQLITE_ABORT ){
72243 sqlite3VdbeFinalize(v);
72244 p->pStmt = 0;
72245 }else{
72246 db->errCode = rc;
72247 v->rc = rc;
72250 rc = sqlite3ApiExit(db, rc);
72251 sqlite3_mutex_leave(db->mutex);
72252 return rc;
72256 ** Read data from a blob handle.
72258 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
72259 return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
72263 ** Write data to a blob handle.
72265 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
72266 return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
72270 ** Query a blob handle for the size of the data.
72272 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
72273 ** so no mutex is required for access.
72275 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
72276 Incrblob *p = (Incrblob *)pBlob;
72277 return (p && p->pStmt) ? p->nByte : 0;
72281 ** Move an existing blob handle to point to a different row of the same
72282 ** database table.
72284 ** If an error occurs, or if the specified row does not exist or does not
72285 ** contain a blob or text value, then an error code is returned and the
72286 ** database handle error code and message set. If this happens, then all
72287 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
72288 ** immediately return SQLITE_ABORT.
72290 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
72291 int rc;
72292 Incrblob *p = (Incrblob *)pBlob;
72293 sqlite3 *db;
72295 if( p==0 ) return SQLITE_MISUSE_BKPT;
72296 db = p->db;
72297 sqlite3_mutex_enter(db->mutex);
72299 if( p->pStmt==0 ){
72300 /* If there is no statement handle, then the blob-handle has
72301 ** already been invalidated. Return SQLITE_ABORT in this case.
72303 rc = SQLITE_ABORT;
72304 }else{
72305 char *zErr;
72306 rc = blobSeekToRow(p, iRow, &zErr);
72307 if( rc!=SQLITE_OK ){
72308 sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
72309 sqlite3DbFree(db, zErr);
72311 assert( rc!=SQLITE_SCHEMA );
72314 rc = sqlite3ApiExit(db, rc);
72315 assert( rc==SQLITE_OK || p->pStmt==0 );
72316 sqlite3_mutex_leave(db->mutex);
72317 return rc;
72320 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
72322 /************** End of vdbeblob.c ********************************************/
72323 /************** Begin file vdbesort.c ****************************************/
72325 ** 2011 July 9
72327 ** The author disclaims copyright to this source code. In place of
72328 ** a legal notice, here is a blessing:
72330 ** May you do good and not evil.
72331 ** May you find forgiveness for yourself and forgive others.
72332 ** May you share freely, never taking more than you give.
72334 *************************************************************************
72335 ** This file contains code for the VdbeSorter object, used in concert with
72336 ** a VdbeCursor to sort large numbers of keys (as may be required, for
72337 ** example, by CREATE INDEX statements on tables too large to fit in main
72338 ** memory).
72343 typedef struct VdbeSorterIter VdbeSorterIter;
72344 typedef struct SorterRecord SorterRecord;
72345 typedef struct FileWriter FileWriter;
72348 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
72350 ** As keys are added to the sorter, they are written to disk in a series
72351 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
72352 ** the same as the cache-size allowed for temporary databases. In order
72353 ** to allow the caller to extract keys from the sorter in sorted order,
72354 ** all PMAs currently stored on disk must be merged together. This comment
72355 ** describes the data structure used to do so. The structure supports
72356 ** merging any number of arrays in a single pass with no redundant comparison
72357 ** operations.
72359 ** The aIter[] array contains an iterator for each of the PMAs being merged.
72360 ** An aIter[] iterator either points to a valid key or else is at EOF. For
72361 ** the purposes of the paragraphs below, we assume that the array is actually
72362 ** N elements in size, where N is the smallest power of 2 greater to or equal
72363 ** to the number of iterators being merged. The extra aIter[] elements are
72364 ** treated as if they are empty (always at EOF).
72366 ** The aTree[] array is also N elements in size. The value of N is stored in
72367 ** the VdbeSorter.nTree variable.
72369 ** The final (N/2) elements of aTree[] contain the results of comparing
72370 ** pairs of iterator keys together. Element i contains the result of
72371 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
72372 ** aTree element is set to the index of it.
72374 ** For the purposes of this comparison, EOF is considered greater than any
72375 ** other key value. If the keys are equal (only possible with two EOF
72376 ** values), it doesn't matter which index is stored.
72378 ** The (N/4) elements of aTree[] that precede the final (N/2) described
72379 ** above contains the index of the smallest of each block of 4 iterators.
72380 ** And so on. So that aTree[1] contains the index of the iterator that
72381 ** currently points to the smallest key value. aTree[0] is unused.
72383 ** Example:
72385 ** aIter[0] -> Banana
72386 ** aIter[1] -> Feijoa
72387 ** aIter[2] -> Elderberry
72388 ** aIter[3] -> Currant
72389 ** aIter[4] -> Grapefruit
72390 ** aIter[5] -> Apple
72391 ** aIter[6] -> Durian
72392 ** aIter[7] -> EOF
72394 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
72396 ** The current element is "Apple" (the value of the key indicated by
72397 ** iterator 5). When the Next() operation is invoked, iterator 5 will
72398 ** be advanced to the next key in its segment. Say the next key is
72399 ** "Eggplant":
72401 ** aIter[5] -> Eggplant
72403 ** The contents of aTree[] are updated first by comparing the new iterator
72404 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
72405 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
72406 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
72407 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
72408 ** so the value written into element 1 of the array is 0. As follows:
72410 ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
72412 ** In other words, each time we advance to the next sorter element, log2(N)
72413 ** key comparison operations are required, where N is the number of segments
72414 ** being merged (rounded up to the next power of 2).
72416 struct VdbeSorter {
72417 i64 iWriteOff; /* Current write offset within file pTemp1 */
72418 i64 iReadOff; /* Current read offset within file pTemp1 */
72419 int nInMemory; /* Current size of pRecord list as PMA */
72420 int nTree; /* Used size of aTree/aIter (power of 2) */
72421 int nPMA; /* Number of PMAs stored in pTemp1 */
72422 int mnPmaSize; /* Minimum PMA size, in bytes */
72423 int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
72424 VdbeSorterIter *aIter; /* Array of iterators to merge */
72425 int *aTree; /* Current state of incremental merge */
72426 sqlite3_file *pTemp1; /* PMA file 1 */
72427 SorterRecord *pRecord; /* Head of in-memory record list */
72428 UnpackedRecord *pUnpacked; /* Used to unpack keys */
72432 ** The following type is an iterator for a PMA. It caches the current key in
72433 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
72435 struct VdbeSorterIter {
72436 i64 iReadOff; /* Current read offset */
72437 i64 iEof; /* 1 byte past EOF for this iterator */
72438 int nAlloc; /* Bytes of space at aAlloc */
72439 int nKey; /* Number of bytes in key */
72440 sqlite3_file *pFile; /* File iterator is reading from */
72441 u8 *aAlloc; /* Allocated space */
72442 u8 *aKey; /* Pointer to current key */
72443 u8 *aBuffer; /* Current read buffer */
72444 int nBuffer; /* Size of read buffer in bytes */
72448 ** An instance of this structure is used to organize the stream of records
72449 ** being written to files by the merge-sort code into aligned, page-sized
72450 ** blocks. Doing all I/O in aligned page-sized blocks helps I/O to go
72451 ** faster on many operating systems.
72453 struct FileWriter {
72454 int eFWErr; /* Non-zero if in an error state */
72455 u8 *aBuffer; /* Pointer to write buffer */
72456 int nBuffer; /* Size of write buffer in bytes */
72457 int iBufStart; /* First byte of buffer to write */
72458 int iBufEnd; /* Last byte of buffer to write */
72459 i64 iWriteOff; /* Offset of start of buffer in file */
72460 sqlite3_file *pFile; /* File to write to */
72464 ** A structure to store a single record. All in-memory records are connected
72465 ** together into a linked list headed at VdbeSorter.pRecord using the
72466 ** SorterRecord.pNext pointer.
72468 struct SorterRecord {
72469 void *pVal;
72470 int nVal;
72471 SorterRecord *pNext;
72474 /* Minimum allowable value for the VdbeSorter.nWorking variable */
72475 #define SORTER_MIN_WORKING 10
72477 /* Maximum number of segments to merge in a single pass. */
72478 #define SORTER_MAX_MERGE_COUNT 16
72481 ** Free all memory belonging to the VdbeSorterIter object passed as the second
72482 ** argument. All structure fields are set to zero before returning.
72484 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
72485 sqlite3DbFree(db, pIter->aAlloc);
72486 sqlite3DbFree(db, pIter->aBuffer);
72487 memset(pIter, 0, sizeof(VdbeSorterIter));
72491 ** Read nByte bytes of data from the stream of data iterated by object p.
72492 ** If successful, set *ppOut to point to a buffer containing the data
72493 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
72494 ** error code.
72496 ** The buffer indicated by *ppOut may only be considered valid until the
72497 ** next call to this function.
72499 static int vdbeSorterIterRead(
72500 sqlite3 *db, /* Database handle (for malloc) */
72501 VdbeSorterIter *p, /* Iterator */
72502 int nByte, /* Bytes of data to read */
72503 u8 **ppOut /* OUT: Pointer to buffer containing data */
72505 int iBuf; /* Offset within buffer to read from */
72506 int nAvail; /* Bytes of data available in buffer */
72507 assert( p->aBuffer );
72509 /* If there is no more data to be read from the buffer, read the next
72510 ** p->nBuffer bytes of data from the file into it. Or, if there are less
72511 ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
72512 iBuf = p->iReadOff % p->nBuffer;
72513 if( iBuf==0 ){
72514 int nRead; /* Bytes to read from disk */
72515 int rc; /* sqlite3OsRead() return code */
72517 /* Determine how many bytes of data to read. */
72518 if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
72519 nRead = p->nBuffer;
72520 }else{
72521 nRead = (int)(p->iEof - p->iReadOff);
72523 assert( nRead>0 );
72525 /* Read data from the file. Return early if an error occurs. */
72526 rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
72527 assert( rc!=SQLITE_IOERR_SHORT_READ );
72528 if( rc!=SQLITE_OK ) return rc;
72530 nAvail = p->nBuffer - iBuf;
72532 if( nByte<=nAvail ){
72533 /* The requested data is available in the in-memory buffer. In this
72534 ** case there is no need to make a copy of the data, just return a
72535 ** pointer into the buffer to the caller. */
72536 *ppOut = &p->aBuffer[iBuf];
72537 p->iReadOff += nByte;
72538 }else{
72539 /* The requested data is not all available in the in-memory buffer.
72540 ** In this case, allocate space at p->aAlloc[] to copy the requested
72541 ** range into. Then return a copy of pointer p->aAlloc to the caller. */
72542 int nRem; /* Bytes remaining to copy */
72544 /* Extend the p->aAlloc[] allocation if required. */
72545 if( p->nAlloc<nByte ){
72546 int nNew = p->nAlloc*2;
72547 while( nByte>nNew ) nNew = nNew*2;
72548 p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
72549 if( !p->aAlloc ) return SQLITE_NOMEM;
72550 p->nAlloc = nNew;
72553 /* Copy as much data as is available in the buffer into the start of
72554 ** p->aAlloc[]. */
72555 memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
72556 p->iReadOff += nAvail;
72557 nRem = nByte - nAvail;
72559 /* The following loop copies up to p->nBuffer bytes per iteration into
72560 ** the p->aAlloc[] buffer. */
72561 while( nRem>0 ){
72562 int rc; /* vdbeSorterIterRead() return code */
72563 int nCopy; /* Number of bytes to copy */
72564 u8 *aNext; /* Pointer to buffer to copy data from */
72566 nCopy = nRem;
72567 if( nRem>p->nBuffer ) nCopy = p->nBuffer;
72568 rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
72569 if( rc!=SQLITE_OK ) return rc;
72570 assert( aNext!=p->aAlloc );
72571 memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
72572 nRem -= nCopy;
72575 *ppOut = p->aAlloc;
72578 return SQLITE_OK;
72582 ** Read a varint from the stream of data accessed by p. Set *pnOut to
72583 ** the value read.
72585 static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
72586 int iBuf;
72588 iBuf = p->iReadOff % p->nBuffer;
72589 if( iBuf && (p->nBuffer-iBuf)>=9 ){
72590 p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
72591 }else{
72592 u8 aVarint[16], *a;
72593 int i = 0, rc;
72595 rc = vdbeSorterIterRead(db, p, 1, &a);
72596 if( rc ) return rc;
72597 aVarint[(i++)&0xf] = a[0];
72598 }while( (a[0]&0x80)!=0 );
72599 sqlite3GetVarint(aVarint, pnOut);
72602 return SQLITE_OK;
72607 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
72608 ** no error occurs, or an SQLite error code if one does.
72610 static int vdbeSorterIterNext(
72611 sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
72612 VdbeSorterIter *pIter /* Iterator to advance */
72614 int rc; /* Return Code */
72615 u64 nRec = 0; /* Size of record in bytes */
72617 if( pIter->iReadOff>=pIter->iEof ){
72618 /* This is an EOF condition */
72619 vdbeSorterIterZero(db, pIter);
72620 return SQLITE_OK;
72623 rc = vdbeSorterIterVarint(db, pIter, &nRec);
72624 if( rc==SQLITE_OK ){
72625 pIter->nKey = (int)nRec;
72626 rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
72629 return rc;
72633 ** Initialize iterator pIter to scan through the PMA stored in file pFile
72634 ** starting at offset iStart and ending at offset iEof-1. This function
72635 ** leaves the iterator pointing to the first key in the PMA (or EOF if the
72636 ** PMA is empty).
72638 static int vdbeSorterIterInit(
72639 sqlite3 *db, /* Database handle */
72640 const VdbeSorter *pSorter, /* Sorter object */
72641 i64 iStart, /* Start offset in pFile */
72642 VdbeSorterIter *pIter, /* Iterator to populate */
72643 i64 *pnByte /* IN/OUT: Increment this value by PMA size */
72645 int rc = SQLITE_OK;
72646 int nBuf;
72648 nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72650 assert( pSorter->iWriteOff>iStart );
72651 assert( pIter->aAlloc==0 );
72652 assert( pIter->aBuffer==0 );
72653 pIter->pFile = pSorter->pTemp1;
72654 pIter->iReadOff = iStart;
72655 pIter->nAlloc = 128;
72656 pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
72657 pIter->nBuffer = nBuf;
72658 pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
72660 if( !pIter->aBuffer ){
72661 rc = SQLITE_NOMEM;
72662 }else{
72663 int iBuf;
72665 iBuf = iStart % nBuf;
72666 if( iBuf ){
72667 int nRead = nBuf - iBuf;
72668 if( (iStart + nRead) > pSorter->iWriteOff ){
72669 nRead = (int)(pSorter->iWriteOff - iStart);
72671 rc = sqlite3OsRead(
72672 pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
72674 assert( rc!=SQLITE_IOERR_SHORT_READ );
72677 if( rc==SQLITE_OK ){
72678 u64 nByte; /* Size of PMA in bytes */
72679 pIter->iEof = pSorter->iWriteOff;
72680 rc = vdbeSorterIterVarint(db, pIter, &nByte);
72681 pIter->iEof = pIter->iReadOff + nByte;
72682 *pnByte += nByte;
72686 if( rc==SQLITE_OK ){
72687 rc = vdbeSorterIterNext(db, pIter);
72689 return rc;
72694 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
72695 ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
72696 ** used by the comparison. If an error occurs, return an SQLite error code.
72697 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
72698 ** value, depending on whether key1 is smaller, equal to or larger than key2.
72700 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
72701 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
72702 ** is true and key1 contains even a single NULL value, it is considered to
72703 ** be less than key2. Even if key2 also contains NULL values.
72705 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
72706 ** has been allocated and contains an unpacked record that is used as key2.
72708 static void vdbeSorterCompare(
72709 const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
72710 int bOmitRowid, /* Ignore rowid field at end of keys */
72711 const void *pKey1, int nKey1, /* Left side of comparison */
72712 const void *pKey2, int nKey2, /* Right side of comparison */
72713 int *pRes /* OUT: Result of comparison */
72715 KeyInfo *pKeyInfo = pCsr->pKeyInfo;
72716 VdbeSorter *pSorter = pCsr->pSorter;
72717 UnpackedRecord *r2 = pSorter->pUnpacked;
72718 int i;
72720 if( pKey2 ){
72721 sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
72724 if( bOmitRowid ){
72725 r2->nField = pKeyInfo->nField;
72726 assert( r2->nField>0 );
72727 for(i=0; i<r2->nField; i++){
72728 if( r2->aMem[i].flags & MEM_Null ){
72729 *pRes = -1;
72730 return;
72733 r2->flags |= UNPACKED_PREFIX_MATCH;
72736 *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
72740 ** This function is called to compare two iterator keys when merging
72741 ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
72742 ** value to recalculate.
72744 static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
72745 VdbeSorter *pSorter = pCsr->pSorter;
72746 int i1;
72747 int i2;
72748 int iRes;
72749 VdbeSorterIter *p1;
72750 VdbeSorterIter *p2;
72752 assert( iOut<pSorter->nTree && iOut>0 );
72754 if( iOut>=(pSorter->nTree/2) ){
72755 i1 = (iOut - pSorter->nTree/2) * 2;
72756 i2 = i1 + 1;
72757 }else{
72758 i1 = pSorter->aTree[iOut*2];
72759 i2 = pSorter->aTree[iOut*2+1];
72762 p1 = &pSorter->aIter[i1];
72763 p2 = &pSorter->aIter[i2];
72765 if( p1->pFile==0 ){
72766 iRes = i2;
72767 }else if( p2->pFile==0 ){
72768 iRes = i1;
72769 }else{
72770 int res;
72771 assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
72772 vdbeSorterCompare(
72773 pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
72775 if( res<=0 ){
72776 iRes = i1;
72777 }else{
72778 iRes = i2;
72782 pSorter->aTree[iOut] = iRes;
72783 return SQLITE_OK;
72787 ** Initialize the temporary index cursor just opened as a sorter cursor.
72789 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
72790 int pgsz; /* Page size of main database */
72791 int mxCache; /* Cache size */
72792 VdbeSorter *pSorter; /* The new sorter */
72793 char *d; /* Dummy */
72795 assert( pCsr->pKeyInfo && pCsr->pBt==0 );
72796 pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
72797 if( pSorter==0 ){
72798 return SQLITE_NOMEM;
72801 pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
72802 if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
72803 assert( pSorter->pUnpacked==(UnpackedRecord *)d );
72805 if( !sqlite3TempInMemory(db) ){
72806 pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72807 pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
72808 mxCache = db->aDb[0].pSchema->cache_size;
72809 if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
72810 pSorter->mxPmaSize = mxCache * pgsz;
72813 return SQLITE_OK;
72817 ** Free the list of sorted records starting at pRecord.
72819 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
72820 SorterRecord *p;
72821 SorterRecord *pNext;
72822 for(p=pRecord; p; p=pNext){
72823 pNext = p->pNext;
72824 sqlite3DbFree(db, p);
72829 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
72831 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
72832 VdbeSorter *pSorter = pCsr->pSorter;
72833 if( pSorter ){
72834 if( pSorter->aIter ){
72835 int i;
72836 for(i=0; i<pSorter->nTree; i++){
72837 vdbeSorterIterZero(db, &pSorter->aIter[i]);
72839 sqlite3DbFree(db, pSorter->aIter);
72841 if( pSorter->pTemp1 ){
72842 sqlite3OsCloseFree(pSorter->pTemp1);
72844 vdbeSorterRecordFree(db, pSorter->pRecord);
72845 sqlite3DbFree(db, pSorter->pUnpacked);
72846 sqlite3DbFree(db, pSorter);
72847 pCsr->pSorter = 0;
72852 ** Allocate space for a file-handle and open a temporary file. If successful,
72853 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
72854 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
72856 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
72857 int dummy;
72858 return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
72859 SQLITE_OPEN_TEMP_JOURNAL |
72860 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
72861 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
72866 ** Merge the two sorted lists p1 and p2 into a single list.
72867 ** Set *ppOut to the head of the new list.
72869 static void vdbeSorterMerge(
72870 const VdbeCursor *pCsr, /* For pKeyInfo */
72871 SorterRecord *p1, /* First list to merge */
72872 SorterRecord *p2, /* Second list to merge */
72873 SorterRecord **ppOut /* OUT: Head of merged list */
72875 SorterRecord *pFinal = 0;
72876 SorterRecord **pp = &pFinal;
72877 void *pVal2 = p2 ? p2->pVal : 0;
72879 while( p1 && p2 ){
72880 int res;
72881 vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
72882 if( res<=0 ){
72883 *pp = p1;
72884 pp = &p1->pNext;
72885 p1 = p1->pNext;
72886 pVal2 = 0;
72887 }else{
72888 *pp = p2;
72889 pp = &p2->pNext;
72890 p2 = p2->pNext;
72891 if( p2==0 ) break;
72892 pVal2 = p2->pVal;
72895 *pp = p1 ? p1 : p2;
72896 *ppOut = pFinal;
72900 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
72901 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
72902 ** occurs.
72904 static int vdbeSorterSort(const VdbeCursor *pCsr){
72905 int i;
72906 SorterRecord **aSlot;
72907 SorterRecord *p;
72908 VdbeSorter *pSorter = pCsr->pSorter;
72910 aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
72911 if( !aSlot ){
72912 return SQLITE_NOMEM;
72915 p = pSorter->pRecord;
72916 while( p ){
72917 SorterRecord *pNext = p->pNext;
72918 p->pNext = 0;
72919 for(i=0; aSlot[i]; i++){
72920 vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72921 aSlot[i] = 0;
72923 aSlot[i] = p;
72924 p = pNext;
72927 p = 0;
72928 for(i=0; i<64; i++){
72929 vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72931 pSorter->pRecord = p;
72933 sqlite3_free(aSlot);
72934 return SQLITE_OK;
72938 ** Initialize a file-writer object.
72940 static void fileWriterInit(
72941 sqlite3 *db, /* Database (for malloc) */
72942 sqlite3_file *pFile, /* File to write to */
72943 FileWriter *p, /* Object to populate */
72944 i64 iStart /* Offset of pFile to begin writing at */
72946 int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72948 memset(p, 0, sizeof(FileWriter));
72949 p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
72950 if( !p->aBuffer ){
72951 p->eFWErr = SQLITE_NOMEM;
72952 }else{
72953 p->iBufEnd = p->iBufStart = (iStart % nBuf);
72954 p->iWriteOff = iStart - p->iBufStart;
72955 p->nBuffer = nBuf;
72956 p->pFile = pFile;
72961 ** Write nData bytes of data to the file-write object. Return SQLITE_OK
72962 ** if successful, or an SQLite error code if an error occurs.
72964 static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
72965 int nRem = nData;
72966 while( nRem>0 && p->eFWErr==0 ){
72967 int nCopy = nRem;
72968 if( nCopy>(p->nBuffer - p->iBufEnd) ){
72969 nCopy = p->nBuffer - p->iBufEnd;
72972 memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
72973 p->iBufEnd += nCopy;
72974 if( p->iBufEnd==p->nBuffer ){
72975 p->eFWErr = sqlite3OsWrite(p->pFile,
72976 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
72977 p->iWriteOff + p->iBufStart
72979 p->iBufStart = p->iBufEnd = 0;
72980 p->iWriteOff += p->nBuffer;
72982 assert( p->iBufEnd<p->nBuffer );
72984 nRem -= nCopy;
72989 ** Flush any buffered data to disk and clean up the file-writer object.
72990 ** The results of using the file-writer after this call are undefined.
72991 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
72992 ** required. Otherwise, return an SQLite error code.
72994 ** Before returning, set *piEof to the offset immediately following the
72995 ** last byte written to the file.
72997 static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
72998 int rc;
72999 if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
73000 p->eFWErr = sqlite3OsWrite(p->pFile,
73001 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
73002 p->iWriteOff + p->iBufStart
73005 *piEof = (p->iWriteOff + p->iBufEnd);
73006 sqlite3DbFree(db, p->aBuffer);
73007 rc = p->eFWErr;
73008 memset(p, 0, sizeof(FileWriter));
73009 return rc;
73013 ** Write value iVal encoded as a varint to the file-write object. Return
73014 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
73016 static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
73017 int nByte;
73018 u8 aByte[10];
73019 nByte = sqlite3PutVarint(aByte, iVal);
73020 fileWriterWrite(p, aByte, nByte);
73024 ** Write the current contents of the in-memory linked-list to a PMA. Return
73025 ** SQLITE_OK if successful, or an SQLite error code otherwise.
73027 ** The format of a PMA is:
73029 ** * A varint. This varint contains the total number of bytes of content
73030 ** in the PMA (not including the varint itself).
73032 ** * One or more records packed end-to-end in order of ascending keys.
73033 ** Each record consists of a varint followed by a blob of data (the
73034 ** key). The varint is the number of bytes in the blob of data.
73036 static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
73037 int rc = SQLITE_OK; /* Return code */
73038 VdbeSorter *pSorter = pCsr->pSorter;
73039 FileWriter writer;
73041 memset(&writer, 0, sizeof(FileWriter));
73043 if( pSorter->nInMemory==0 ){
73044 assert( pSorter->pRecord==0 );
73045 return rc;
73048 rc = vdbeSorterSort(pCsr);
73050 /* If the first temporary PMA file has not been opened, open it now. */
73051 if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
73052 rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
73053 assert( rc!=SQLITE_OK || pSorter->pTemp1 );
73054 assert( pSorter->iWriteOff==0 );
73055 assert( pSorter->nPMA==0 );
73058 if( rc==SQLITE_OK ){
73059 SorterRecord *p;
73060 SorterRecord *pNext = 0;
73062 fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
73063 pSorter->nPMA++;
73064 fileWriterWriteVarint(&writer, pSorter->nInMemory);
73065 for(p=pSorter->pRecord; p; p=pNext){
73066 pNext = p->pNext;
73067 fileWriterWriteVarint(&writer, p->nVal);
73068 fileWriterWrite(&writer, p->pVal, p->nVal);
73069 sqlite3DbFree(db, p);
73071 pSorter->pRecord = p;
73072 rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
73075 return rc;
73079 ** Add a record to the sorter.
73081 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
73082 sqlite3 *db, /* Database handle */
73083 const VdbeCursor *pCsr, /* Sorter cursor */
73084 Mem *pVal /* Memory cell containing record */
73086 VdbeSorter *pSorter = pCsr->pSorter;
73087 int rc = SQLITE_OK; /* Return Code */
73088 SorterRecord *pNew; /* New list element */
73090 assert( pSorter );
73091 pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
73093 pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
73094 if( pNew==0 ){
73095 rc = SQLITE_NOMEM;
73096 }else{
73097 pNew->pVal = (void *)&pNew[1];
73098 memcpy(pNew->pVal, pVal->z, pVal->n);
73099 pNew->nVal = pVal->n;
73100 pNew->pNext = pSorter->pRecord;
73101 pSorter->pRecord = pNew;
73104 /* See if the contents of the sorter should now be written out. They
73105 ** are written out when either of the following are true:
73107 ** * The total memory allocated for the in-memory list is greater
73108 ** than (page-size * cache-size), or
73110 ** * The total memory allocated for the in-memory list is greater
73111 ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
73113 if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
73114 (pSorter->nInMemory>pSorter->mxPmaSize)
73115 || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
73117 #ifdef SQLITE_DEBUG
73118 i64 nExpect = pSorter->iWriteOff
73119 + sqlite3VarintLen(pSorter->nInMemory)
73120 + pSorter->nInMemory;
73121 #endif
73122 rc = vdbeSorterListToPMA(db, pCsr);
73123 pSorter->nInMemory = 0;
73124 assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
73127 return rc;
73131 ** Helper function for sqlite3VdbeSorterRewind().
73133 static int vdbeSorterInitMerge(
73134 sqlite3 *db, /* Database handle */
73135 const VdbeCursor *pCsr, /* Cursor handle for this sorter */
73136 i64 *pnByte /* Sum of bytes in all opened PMAs */
73138 VdbeSorter *pSorter = pCsr->pSorter;
73139 int rc = SQLITE_OK; /* Return code */
73140 int i; /* Used to iterator through aIter[] */
73141 i64 nByte = 0; /* Total bytes in all opened PMAs */
73143 /* Initialize the iterators. */
73144 for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
73145 VdbeSorterIter *pIter = &pSorter->aIter[i];
73146 rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
73147 pSorter->iReadOff = pIter->iEof;
73148 assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
73149 if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
73152 /* Initialize the aTree[] array. */
73153 for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
73154 rc = vdbeSorterDoCompare(pCsr, i);
73157 *pnByte = nByte;
73158 return rc;
73162 ** Once the sorter has been populated, this function is called to prepare
73163 ** for iterating through its contents in sorted order.
73165 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
73166 VdbeSorter *pSorter = pCsr->pSorter;
73167 int rc; /* Return code */
73168 sqlite3_file *pTemp2 = 0; /* Second temp file to use */
73169 i64 iWrite2 = 0; /* Write offset for pTemp2 */
73170 int nIter; /* Number of iterators used */
73171 int nByte; /* Bytes of space required for aIter/aTree */
73172 int N = 2; /* Power of 2 >= nIter */
73174 assert( pSorter );
73176 /* If no data has been written to disk, then do not do so now. Instead,
73177 ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
73178 ** from the in-memory list. */
73179 if( pSorter->nPMA==0 ){
73180 *pbEof = !pSorter->pRecord;
73181 assert( pSorter->aTree==0 );
73182 return vdbeSorterSort(pCsr);
73185 /* Write the current in-memory list to a PMA. */
73186 rc = vdbeSorterListToPMA(db, pCsr);
73187 if( rc!=SQLITE_OK ) return rc;
73189 /* Allocate space for aIter[] and aTree[]. */
73190 nIter = pSorter->nPMA;
73191 if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
73192 assert( nIter>0 );
73193 while( N<nIter ) N += N;
73194 nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
73195 pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
73196 if( !pSorter->aIter ) return SQLITE_NOMEM;
73197 pSorter->aTree = (int *)&pSorter->aIter[N];
73198 pSorter->nTree = N;
73200 do {
73201 int iNew; /* Index of new, merged, PMA */
73203 for(iNew=0;
73204 rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
73205 iNew++
73207 int rc2; /* Return code from fileWriterFinish() */
73208 FileWriter writer; /* Object used to write to disk */
73209 i64 nWrite; /* Number of bytes in new PMA */
73211 memset(&writer, 0, sizeof(FileWriter));
73213 /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
73214 ** initialize an iterator for each of them and break out of the loop.
73215 ** These iterators will be incrementally merged as the VDBE layer calls
73216 ** sqlite3VdbeSorterNext().
73218 ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
73219 ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
73220 ** are merged into a single PMA that is written to file pTemp2.
73222 rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
73223 assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
73224 if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
73225 break;
73228 /* Open the second temp file, if it is not already open. */
73229 if( pTemp2==0 ){
73230 assert( iWrite2==0 );
73231 rc = vdbeSorterOpenTempFile(db, &pTemp2);
73234 if( rc==SQLITE_OK ){
73235 int bEof = 0;
73236 fileWriterInit(db, pTemp2, &writer, iWrite2);
73237 fileWriterWriteVarint(&writer, nWrite);
73238 while( rc==SQLITE_OK && bEof==0 ){
73239 VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
73240 assert( pIter->pFile );
73242 fileWriterWriteVarint(&writer, pIter->nKey);
73243 fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
73244 rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
73246 rc2 = fileWriterFinish(db, &writer, &iWrite2);
73247 if( rc==SQLITE_OK ) rc = rc2;
73251 if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
73252 break;
73253 }else{
73254 sqlite3_file *pTmp = pSorter->pTemp1;
73255 pSorter->nPMA = iNew;
73256 pSorter->pTemp1 = pTemp2;
73257 pTemp2 = pTmp;
73258 pSorter->iWriteOff = iWrite2;
73259 pSorter->iReadOff = 0;
73260 iWrite2 = 0;
73262 }while( rc==SQLITE_OK );
73264 if( pTemp2 ){
73265 sqlite3OsCloseFree(pTemp2);
73267 *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
73268 return rc;
73272 ** Advance to the next element in the sorter.
73274 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
73275 VdbeSorter *pSorter = pCsr->pSorter;
73276 int rc; /* Return code */
73278 if( pSorter->aTree ){
73279 int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
73280 int i; /* Index of aTree[] to recalculate */
73282 rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
73283 for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
73284 rc = vdbeSorterDoCompare(pCsr, i);
73287 *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
73288 }else{
73289 SorterRecord *pFree = pSorter->pRecord;
73290 pSorter->pRecord = pFree->pNext;
73291 pFree->pNext = 0;
73292 vdbeSorterRecordFree(db, pFree);
73293 *pbEof = !pSorter->pRecord;
73294 rc = SQLITE_OK;
73296 return rc;
73300 ** Return a pointer to a buffer owned by the sorter that contains the
73301 ** current key.
73303 static void *vdbeSorterRowkey(
73304 const VdbeSorter *pSorter, /* Sorter object */
73305 int *pnKey /* OUT: Size of current key in bytes */
73307 void *pKey;
73308 if( pSorter->aTree ){
73309 VdbeSorterIter *pIter;
73310 pIter = &pSorter->aIter[ pSorter->aTree[1] ];
73311 *pnKey = pIter->nKey;
73312 pKey = pIter->aKey;
73313 }else{
73314 *pnKey = pSorter->pRecord->nVal;
73315 pKey = pSorter->pRecord->pVal;
73317 return pKey;
73321 ** Copy the current sorter key into the memory cell pOut.
73323 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
73324 VdbeSorter *pSorter = pCsr->pSorter;
73325 void *pKey; int nKey; /* Sorter key to copy into pOut */
73327 pKey = vdbeSorterRowkey(pSorter, &nKey);
73328 if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
73329 return SQLITE_NOMEM;
73331 pOut->n = nKey;
73332 MemSetTypeFlag(pOut, MEM_Blob);
73333 memcpy(pOut->z, pKey, nKey);
73335 return SQLITE_OK;
73339 ** Compare the key in memory cell pVal with the key that the sorter cursor
73340 ** passed as the first argument currently points to. For the purposes of
73341 ** the comparison, ignore the rowid field at the end of each record.
73343 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
73344 ** Otherwise, set *pRes to a negative, zero or positive value if the
73345 ** key in pVal is smaller than, equal to or larger than the current sorter
73346 ** key.
73348 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
73349 const VdbeCursor *pCsr, /* Sorter cursor */
73350 Mem *pVal, /* Value to compare to current sorter key */
73351 int *pRes /* OUT: Result of comparison */
73353 VdbeSorter *pSorter = pCsr->pSorter;
73354 void *pKey; int nKey; /* Sorter key to compare pVal with */
73356 pKey = vdbeSorterRowkey(pSorter, &nKey);
73357 vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
73358 return SQLITE_OK;
73361 /************** End of vdbesort.c ********************************************/
73362 /************** Begin file journal.c *****************************************/
73364 ** 2007 August 22
73366 ** The author disclaims copyright to this source code. In place of
73367 ** a legal notice, here is a blessing:
73369 ** May you do good and not evil.
73370 ** May you find forgiveness for yourself and forgive others.
73371 ** May you share freely, never taking more than you give.
73373 *************************************************************************
73375 ** This file implements a special kind of sqlite3_file object used
73376 ** by SQLite to create journal files if the atomic-write optimization
73377 ** is enabled.
73379 ** The distinctive characteristic of this sqlite3_file is that the
73380 ** actual on disk file is created lazily. When the file is created,
73381 ** the caller specifies a buffer size for an in-memory buffer to
73382 ** be used to service read() and write() requests. The actual file
73383 ** on disk is not created or populated until either:
73385 ** 1) The in-memory representation grows too large for the allocated
73386 ** buffer, or
73387 ** 2) The sqlite3JournalCreate() function is called.
73389 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
73393 ** A JournalFile object is a subclass of sqlite3_file used by
73394 ** as an open file handle for journal files.
73396 struct JournalFile {
73397 sqlite3_io_methods *pMethod; /* I/O methods on journal files */
73398 int nBuf; /* Size of zBuf[] in bytes */
73399 char *zBuf; /* Space to buffer journal writes */
73400 int iSize; /* Amount of zBuf[] currently used */
73401 int flags; /* xOpen flags */
73402 sqlite3_vfs *pVfs; /* The "real" underlying VFS */
73403 sqlite3_file *pReal; /* The "real" underlying file descriptor */
73404 const char *zJournal; /* Name of the journal file */
73406 typedef struct JournalFile JournalFile;
73409 ** If it does not already exists, create and populate the on-disk file
73410 ** for JournalFile p.
73412 static int createFile(JournalFile *p){
73413 int rc = SQLITE_OK;
73414 if( !p->pReal ){
73415 sqlite3_file *pReal = (sqlite3_file *)&p[1];
73416 rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
73417 if( rc==SQLITE_OK ){
73418 p->pReal = pReal;
73419 if( p->iSize>0 ){
73420 assert(p->iSize<=p->nBuf);
73421 rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
73423 if( rc!=SQLITE_OK ){
73424 /* If an error occurred while writing to the file, close it before
73425 ** returning. This way, SQLite uses the in-memory journal data to
73426 ** roll back changes made to the internal page-cache before this
73427 ** function was called. */
73428 sqlite3OsClose(pReal);
73429 p->pReal = 0;
73433 return rc;
73437 ** Close the file.
73439 static int jrnlClose(sqlite3_file *pJfd){
73440 JournalFile *p = (JournalFile *)pJfd;
73441 if( p->pReal ){
73442 sqlite3OsClose(p->pReal);
73444 sqlite3_free(p->zBuf);
73445 return SQLITE_OK;
73449 ** Read data from the file.
73451 static int jrnlRead(
73452 sqlite3_file *pJfd, /* The journal file from which to read */
73453 void *zBuf, /* Put the results here */
73454 int iAmt, /* Number of bytes to read */
73455 sqlite_int64 iOfst /* Begin reading at this offset */
73457 int rc = SQLITE_OK;
73458 JournalFile *p = (JournalFile *)pJfd;
73459 if( p->pReal ){
73460 rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
73461 }else if( (iAmt+iOfst)>p->iSize ){
73462 rc = SQLITE_IOERR_SHORT_READ;
73463 }else{
73464 memcpy(zBuf, &p->zBuf[iOfst], iAmt);
73466 return rc;
73470 ** Write data to the file.
73472 static int jrnlWrite(
73473 sqlite3_file *pJfd, /* The journal file into which to write */
73474 const void *zBuf, /* Take data to be written from here */
73475 int iAmt, /* Number of bytes to write */
73476 sqlite_int64 iOfst /* Begin writing at this offset into the file */
73478 int rc = SQLITE_OK;
73479 JournalFile *p = (JournalFile *)pJfd;
73480 if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
73481 rc = createFile(p);
73483 if( rc==SQLITE_OK ){
73484 if( p->pReal ){
73485 rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
73486 }else{
73487 memcpy(&p->zBuf[iOfst], zBuf, iAmt);
73488 if( p->iSize<(iOfst+iAmt) ){
73489 p->iSize = (iOfst+iAmt);
73493 return rc;
73497 ** Truncate the file.
73499 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
73500 int rc = SQLITE_OK;
73501 JournalFile *p = (JournalFile *)pJfd;
73502 if( p->pReal ){
73503 rc = sqlite3OsTruncate(p->pReal, size);
73504 }else if( size<p->iSize ){
73505 p->iSize = size;
73507 return rc;
73511 ** Sync the file.
73513 static int jrnlSync(sqlite3_file *pJfd, int flags){
73514 int rc;
73515 JournalFile *p = (JournalFile *)pJfd;
73516 if( p->pReal ){
73517 rc = sqlite3OsSync(p->pReal, flags);
73518 }else{
73519 rc = SQLITE_OK;
73521 return rc;
73525 ** Query the size of the file in bytes.
73527 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
73528 int rc = SQLITE_OK;
73529 JournalFile *p = (JournalFile *)pJfd;
73530 if( p->pReal ){
73531 rc = sqlite3OsFileSize(p->pReal, pSize);
73532 }else{
73533 *pSize = (sqlite_int64) p->iSize;
73535 return rc;
73539 ** Table of methods for JournalFile sqlite3_file object.
73541 static struct sqlite3_io_methods JournalFileMethods = {
73542 1, /* iVersion */
73543 jrnlClose, /* xClose */
73544 jrnlRead, /* xRead */
73545 jrnlWrite, /* xWrite */
73546 jrnlTruncate, /* xTruncate */
73547 jrnlSync, /* xSync */
73548 jrnlFileSize, /* xFileSize */
73549 0, /* xLock */
73550 0, /* xUnlock */
73551 0, /* xCheckReservedLock */
73552 0, /* xFileControl */
73553 0, /* xSectorSize */
73554 0, /* xDeviceCharacteristics */
73555 0, /* xShmMap */
73556 0, /* xShmLock */
73557 0, /* xShmBarrier */
73558 0 /* xShmUnmap */
73562 ** Open a journal file.
73564 SQLITE_PRIVATE int sqlite3JournalOpen(
73565 sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
73566 const char *zName, /* Name of the journal file */
73567 sqlite3_file *pJfd, /* Preallocated, blank file handle */
73568 int flags, /* Opening flags */
73569 int nBuf /* Bytes buffered before opening the file */
73571 JournalFile *p = (JournalFile *)pJfd;
73572 memset(p, 0, sqlite3JournalSize(pVfs));
73573 if( nBuf>0 ){
73574 p->zBuf = sqlite3MallocZero(nBuf);
73575 if( !p->zBuf ){
73576 return SQLITE_NOMEM;
73578 }else{
73579 return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
73581 p->pMethod = &JournalFileMethods;
73582 p->nBuf = nBuf;
73583 p->flags = flags;
73584 p->zJournal = zName;
73585 p->pVfs = pVfs;
73586 return SQLITE_OK;
73590 ** If the argument p points to a JournalFile structure, and the underlying
73591 ** file has not yet been created, create it now.
73593 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
73594 if( p->pMethods!=&JournalFileMethods ){
73595 return SQLITE_OK;
73597 return createFile((JournalFile *)p);
73601 ** The file-handle passed as the only argument is guaranteed to be an open
73602 ** file. It may or may not be of class JournalFile. If the file is a
73603 ** JournalFile, and the underlying file on disk has not yet been opened,
73604 ** return 0. Otherwise, return 1.
73606 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
73607 return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
73611 ** Return the number of bytes required to store a JournalFile that uses vfs
73612 ** pVfs to create the underlying on-disk files.
73614 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
73615 return (pVfs->szOsFile+sizeof(JournalFile));
73617 #endif
73619 /************** End of journal.c *********************************************/
73620 /************** Begin file memjournal.c **************************************/
73622 ** 2008 October 7
73624 ** The author disclaims copyright to this source code. In place of
73625 ** a legal notice, here is a blessing:
73627 ** May you do good and not evil.
73628 ** May you find forgiveness for yourself and forgive others.
73629 ** May you share freely, never taking more than you give.
73631 *************************************************************************
73633 ** This file contains code use to implement an in-memory rollback journal.
73634 ** The in-memory rollback journal is used to journal transactions for
73635 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
73638 /* Forward references to internal structures */
73639 typedef struct MemJournal MemJournal;
73640 typedef struct FilePoint FilePoint;
73641 typedef struct FileChunk FileChunk;
73643 /* Space to hold the rollback journal is allocated in increments of
73644 ** this many bytes.
73646 ** The size chosen is a little less than a power of two. That way,
73647 ** the FileChunk object will have a size that almost exactly fills
73648 ** a power-of-two allocation. This mimimizes wasted space in power-of-two
73649 ** memory allocators.
73651 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
73654 ** The rollback journal is composed of a linked list of these structures.
73656 struct FileChunk {
73657 FileChunk *pNext; /* Next chunk in the journal */
73658 u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
73662 ** An instance of this object serves as a cursor into the rollback journal.
73663 ** The cursor can be either for reading or writing.
73665 struct FilePoint {
73666 sqlite3_int64 iOffset; /* Offset from the beginning of the file */
73667 FileChunk *pChunk; /* Specific chunk into which cursor points */
73671 ** This subclass is a subclass of sqlite3_file. Each open memory-journal
73672 ** is an instance of this class.
73674 struct MemJournal {
73675 sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
73676 FileChunk *pFirst; /* Head of in-memory chunk-list */
73677 FilePoint endpoint; /* Pointer to the end of the file */
73678 FilePoint readpoint; /* Pointer to the end of the last xRead() */
73682 ** Read data from the in-memory journal file. This is the implementation
73683 ** of the sqlite3_vfs.xRead method.
73685 static int memjrnlRead(
73686 sqlite3_file *pJfd, /* The journal file from which to read */
73687 void *zBuf, /* Put the results here */
73688 int iAmt, /* Number of bytes to read */
73689 sqlite_int64 iOfst /* Begin reading at this offset */
73691 MemJournal *p = (MemJournal *)pJfd;
73692 u8 *zOut = zBuf;
73693 int nRead = iAmt;
73694 int iChunkOffset;
73695 FileChunk *pChunk;
73697 /* SQLite never tries to read past the end of a rollback journal file */
73698 assert( iOfst+iAmt<=p->endpoint.iOffset );
73700 if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
73701 sqlite3_int64 iOff = 0;
73702 for(pChunk=p->pFirst;
73703 ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
73704 pChunk=pChunk->pNext
73706 iOff += JOURNAL_CHUNKSIZE;
73708 }else{
73709 pChunk = p->readpoint.pChunk;
73712 iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
73713 do {
73714 int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
73715 int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
73716 memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
73717 zOut += nCopy;
73718 nRead -= iSpace;
73719 iChunkOffset = 0;
73720 } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
73721 p->readpoint.iOffset = iOfst+iAmt;
73722 p->readpoint.pChunk = pChunk;
73724 return SQLITE_OK;
73728 ** Write data to the file.
73730 static int memjrnlWrite(
73731 sqlite3_file *pJfd, /* The journal file into which to write */
73732 const void *zBuf, /* Take data to be written from here */
73733 int iAmt, /* Number of bytes to write */
73734 sqlite_int64 iOfst /* Begin writing at this offset into the file */
73736 MemJournal *p = (MemJournal *)pJfd;
73737 int nWrite = iAmt;
73738 u8 *zWrite = (u8 *)zBuf;
73740 /* An in-memory journal file should only ever be appended to. Random
73741 ** access writes are not required by sqlite.
73743 assert( iOfst==p->endpoint.iOffset );
73744 UNUSED_PARAMETER(iOfst);
73746 while( nWrite>0 ){
73747 FileChunk *pChunk = p->endpoint.pChunk;
73748 int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
73749 int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
73751 if( iChunkOffset==0 ){
73752 /* New chunk is required to extend the file. */
73753 FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
73754 if( !pNew ){
73755 return SQLITE_IOERR_NOMEM;
73757 pNew->pNext = 0;
73758 if( pChunk ){
73759 assert( p->pFirst );
73760 pChunk->pNext = pNew;
73761 }else{
73762 assert( !p->pFirst );
73763 p->pFirst = pNew;
73765 p->endpoint.pChunk = pNew;
73768 memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
73769 zWrite += iSpace;
73770 nWrite -= iSpace;
73771 p->endpoint.iOffset += iSpace;
73774 return SQLITE_OK;
73778 ** Truncate the file.
73780 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
73781 MemJournal *p = (MemJournal *)pJfd;
73782 FileChunk *pChunk;
73783 assert(size==0);
73784 UNUSED_PARAMETER(size);
73785 pChunk = p->pFirst;
73786 while( pChunk ){
73787 FileChunk *pTmp = pChunk;
73788 pChunk = pChunk->pNext;
73789 sqlite3_free(pTmp);
73791 sqlite3MemJournalOpen(pJfd);
73792 return SQLITE_OK;
73796 ** Close the file.
73798 static int memjrnlClose(sqlite3_file *pJfd){
73799 memjrnlTruncate(pJfd, 0);
73800 return SQLITE_OK;
73805 ** Sync the file.
73807 ** Syncing an in-memory journal is a no-op. And, in fact, this routine
73808 ** is never called in a working implementation. This implementation
73809 ** exists purely as a contingency, in case some malfunction in some other
73810 ** part of SQLite causes Sync to be called by mistake.
73812 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
73813 UNUSED_PARAMETER2(NotUsed, NotUsed2);
73814 return SQLITE_OK;
73818 ** Query the size of the file in bytes.
73820 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
73821 MemJournal *p = (MemJournal *)pJfd;
73822 *pSize = (sqlite_int64) p->endpoint.iOffset;
73823 return SQLITE_OK;
73827 ** Table of methods for MemJournal sqlite3_file object.
73829 static const struct sqlite3_io_methods MemJournalMethods = {
73830 1, /* iVersion */
73831 memjrnlClose, /* xClose */
73832 memjrnlRead, /* xRead */
73833 memjrnlWrite, /* xWrite */
73834 memjrnlTruncate, /* xTruncate */
73835 memjrnlSync, /* xSync */
73836 memjrnlFileSize, /* xFileSize */
73837 0, /* xLock */
73838 0, /* xUnlock */
73839 0, /* xCheckReservedLock */
73840 0, /* xFileControl */
73841 0, /* xSectorSize */
73842 0, /* xDeviceCharacteristics */
73843 0, /* xShmMap */
73844 0, /* xShmLock */
73845 0, /* xShmBarrier */
73846 0, /* xShmUnmap */
73847 0, /* xFetch */
73848 0 /* xUnfetch */
73852 ** Open a journal file.
73854 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
73855 MemJournal *p = (MemJournal *)pJfd;
73856 assert( EIGHT_BYTE_ALIGNMENT(p) );
73857 memset(p, 0, sqlite3MemJournalSize());
73858 p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
73862 ** Return true if the file-handle passed as an argument is
73863 ** an in-memory journal
73865 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
73866 return pJfd->pMethods==&MemJournalMethods;
73870 ** Return the number of bytes required to store a MemJournal file descriptor.
73872 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
73873 return sizeof(MemJournal);
73876 /************** End of memjournal.c ******************************************/
73877 /************** Begin file walker.c ******************************************/
73879 ** 2008 August 16
73881 ** The author disclaims copyright to this source code. In place of
73882 ** a legal notice, here is a blessing:
73884 ** May you do good and not evil.
73885 ** May you find forgiveness for yourself and forgive others.
73886 ** May you share freely, never taking more than you give.
73888 *************************************************************************
73889 ** This file contains routines used for walking the parser tree for
73890 ** an SQL statement.
73892 /* #include <stdlib.h> */
73893 /* #include <string.h> */
73897 ** Walk an expression tree. Invoke the callback once for each node
73898 ** of the expression, while decending. (In other words, the callback
73899 ** is invoked before visiting children.)
73901 ** The return value from the callback should be one of the WRC_*
73902 ** constants to specify how to proceed with the walk.
73904 ** WRC_Continue Continue descending down the tree.
73906 ** WRC_Prune Do not descend into child nodes. But allow
73907 ** the walk to continue with sibling nodes.
73909 ** WRC_Abort Do no more callbacks. Unwind the stack and
73910 ** return the top-level walk call.
73912 ** The return value from this routine is WRC_Abort to abandon the tree walk
73913 ** and WRC_Continue to continue.
73915 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
73916 int rc;
73917 if( pExpr==0 ) return WRC_Continue;
73918 testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
73919 testcase( ExprHasProperty(pExpr, EP_Reduced) );
73920 rc = pWalker->xExprCallback(pWalker, pExpr);
73921 if( rc==WRC_Continue
73922 && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
73923 if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
73924 if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
73925 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73926 if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
73927 }else{
73928 if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
73931 return rc & WRC_Abort;
73935 ** Call sqlite3WalkExpr() for every expression in list p or until
73936 ** an abort request is seen.
73938 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
73939 int i;
73940 struct ExprList_item *pItem;
73941 if( p ){
73942 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
73943 if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
73946 return WRC_Continue;
73950 ** Walk all expressions associated with SELECT statement p. Do
73951 ** not invoke the SELECT callback on p, but do (of course) invoke
73952 ** any expr callbacks and SELECT callbacks that come from subqueries.
73953 ** Return WRC_Abort or WRC_Continue.
73955 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
73956 if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
73957 if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
73958 if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
73959 if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
73960 if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
73961 if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
73962 if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
73963 return WRC_Continue;
73967 ** Walk the parse trees associated with all subqueries in the
73968 ** FROM clause of SELECT statement p. Do not invoke the select
73969 ** callback on p, but do invoke it on each FROM clause subquery
73970 ** and on any subqueries further down in the tree. Return
73971 ** WRC_Abort or WRC_Continue;
73973 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
73974 SrcList *pSrc;
73975 int i;
73976 struct SrcList_item *pItem;
73978 pSrc = p->pSrc;
73979 if( ALWAYS(pSrc) ){
73980 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
73981 if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
73982 return WRC_Abort;
73986 return WRC_Continue;
73990 ** Call sqlite3WalkExpr() for every expression in Select statement p.
73991 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
73992 ** on the compound select chain, p->pPrior. Invoke the xSelectCallback()
73993 ** either before or after the walk of expressions and FROM clause, depending
73994 ** on whether pWalker->bSelectDepthFirst is false or true, respectively.
73996 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
73997 ** there is an abort request.
73999 ** If the Walker does not have an xSelectCallback() then this routine
74000 ** is a no-op returning WRC_Continue.
74002 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
74003 int rc;
74004 if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
74005 rc = WRC_Continue;
74006 pWalker->walkerDepth++;
74007 while( p ){
74008 if( !pWalker->bSelectDepthFirst ){
74009 rc = pWalker->xSelectCallback(pWalker, p);
74010 if( rc ) break;
74012 if( sqlite3WalkSelectExpr(pWalker, p)
74013 || sqlite3WalkSelectFrom(pWalker, p)
74015 pWalker->walkerDepth--;
74016 return WRC_Abort;
74018 if( pWalker->bSelectDepthFirst ){
74019 rc = pWalker->xSelectCallback(pWalker, p);
74020 /* Depth-first search is currently only used for
74021 ** selectAddSubqueryTypeInfo() and that routine always returns
74022 ** WRC_Continue (0). So the following branch is never taken. */
74023 if( NEVER(rc) ) break;
74025 p = p->pPrior;
74027 pWalker->walkerDepth--;
74028 return rc & WRC_Abort;
74031 /************** End of walker.c **********************************************/
74032 /************** Begin file resolve.c *****************************************/
74034 ** 2008 August 18
74036 ** The author disclaims copyright to this source code. In place of
74037 ** a legal notice, here is a blessing:
74039 ** May you do good and not evil.
74040 ** May you find forgiveness for yourself and forgive others.
74041 ** May you share freely, never taking more than you give.
74043 *************************************************************************
74045 ** This file contains routines used for walking the parser tree and
74046 ** resolve all identifiers by associating them with a particular
74047 ** table and column.
74049 /* #include <stdlib.h> */
74050 /* #include <string.h> */
74053 ** Walk the expression tree pExpr and increase the aggregate function
74054 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
74055 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
74056 ** outer query into an inner subquery.
74058 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
74059 ** is a helper function - a callback for the tree walker.
74061 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
74062 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
74063 return WRC_Continue;
74065 static void incrAggFunctionDepth(Expr *pExpr, int N){
74066 if( N>0 ){
74067 Walker w;
74068 memset(&w, 0, sizeof(w));
74069 w.xExprCallback = incrAggDepth;
74070 w.u.i = N;
74071 sqlite3WalkExpr(&w, pExpr);
74076 ** Turn the pExpr expression into an alias for the iCol-th column of the
74077 ** result set in pEList.
74079 ** If the result set column is a simple column reference, then this routine
74080 ** makes an exact copy. But for any other kind of expression, this
74081 ** routine make a copy of the result set column as the argument to the
74082 ** TK_AS operator. The TK_AS operator causes the expression to be
74083 ** evaluated just once and then reused for each alias.
74085 ** The reason for suppressing the TK_AS term when the expression is a simple
74086 ** column reference is so that the column reference will be recognized as
74087 ** usable by indices within the WHERE clause processing logic.
74089 ** The TK_AS operator is inhibited if zType[0]=='G'. This means
74090 ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
74092 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
74094 ** Is equivalent to:
74096 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
74098 ** The result of random()%5 in the GROUP BY clause is probably different
74099 ** from the result in the result-set. On the other hand Standard SQL does
74100 ** not allow the GROUP BY clause to contain references to result-set columns.
74101 ** So this should never come up in well-formed queries.
74103 ** If the reference is followed by a COLLATE operator, then make sure
74104 ** the COLLATE operator is preserved. For example:
74106 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
74108 ** Should be transformed into:
74110 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
74112 ** The nSubquery parameter specifies how many levels of subquery the
74113 ** alias is removed from the original expression. The usually value is
74114 ** zero but it might be more if the alias is contained within a subquery
74115 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
74116 ** structures must be increased by the nSubquery amount.
74118 static void resolveAlias(
74119 Parse *pParse, /* Parsing context */
74120 ExprList *pEList, /* A result set */
74121 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
74122 Expr *pExpr, /* Transform this into an alias to the result set */
74123 const char *zType, /* "GROUP" or "ORDER" or "" */
74124 int nSubquery /* Number of subqueries that the label is moving */
74126 Expr *pOrig; /* The iCol-th column of the result set */
74127 Expr *pDup; /* Copy of pOrig */
74128 sqlite3 *db; /* The database connection */
74130 assert( iCol>=0 && iCol<pEList->nExpr );
74131 pOrig = pEList->a[iCol].pExpr;
74132 assert( pOrig!=0 );
74133 assert( pOrig->flags & EP_Resolved );
74134 db = pParse->db;
74135 pDup = sqlite3ExprDup(db, pOrig, 0);
74136 if( pDup==0 ) return;
74137 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
74138 incrAggFunctionDepth(pDup, nSubquery);
74139 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
74140 if( pDup==0 ) return;
74141 if( pEList->a[iCol].iAlias==0 ){
74142 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
74144 pDup->iTable = pEList->a[iCol].iAlias;
74146 if( pExpr->op==TK_COLLATE ){
74147 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
74150 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
74151 ** prevents ExprDelete() from deleting the Expr structure itself,
74152 ** allowing it to be repopulated by the memcpy() on the following line.
74153 ** The pExpr->u.zToken might point into memory that will be freed by the
74154 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
74155 ** make a copy of the token before doing the sqlite3DbFree().
74157 ExprSetProperty(pExpr, EP_Static);
74158 sqlite3ExprDelete(db, pExpr);
74159 memcpy(pExpr, pDup, sizeof(*pExpr));
74160 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
74161 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
74162 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
74163 pExpr->flags2 |= EP2_MallocedToken;
74165 sqlite3DbFree(db, pDup);
74170 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
74172 ** Return FALSE if the USING clause is NULL or if it does not contain
74173 ** zCol.
74175 static int nameInUsingClause(IdList *pUsing, const char *zCol){
74176 if( pUsing ){
74177 int k;
74178 for(k=0; k<pUsing->nId; k++){
74179 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
74182 return 0;
74186 ** Subqueries stores the original database, table and column names for their
74187 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
74188 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
74189 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
74190 ** match anything.
74192 SQLITE_PRIVATE int sqlite3MatchSpanName(
74193 const char *zSpan,
74194 const char *zCol,
74195 const char *zTab,
74196 const char *zDb
74198 int n;
74199 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
74200 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
74201 return 0;
74203 zSpan += n+1;
74204 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
74205 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
74206 return 0;
74208 zSpan += n+1;
74209 if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
74210 return 0;
74212 return 1;
74216 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
74217 ** that name in the set of source tables in pSrcList and make the pExpr
74218 ** expression node refer back to that source column. The following changes
74219 ** are made to pExpr:
74221 ** pExpr->iDb Set the index in db->aDb[] of the database X
74222 ** (even if X is implied).
74223 ** pExpr->iTable Set to the cursor number for the table obtained
74224 ** from pSrcList.
74225 ** pExpr->pTab Points to the Table structure of X.Y (even if
74226 ** X and/or Y are implied.)
74227 ** pExpr->iColumn Set to the column number within the table.
74228 ** pExpr->op Set to TK_COLUMN.
74229 ** pExpr->pLeft Any expression this points to is deleted
74230 ** pExpr->pRight Any expression this points to is deleted.
74232 ** The zDb variable is the name of the database (the "X"). This value may be
74233 ** NULL meaning that name is of the form Y.Z or Z. Any available database
74234 ** can be used. The zTable variable is the name of the table (the "Y"). This
74235 ** value can be NULL if zDb is also NULL. If zTable is NULL it
74236 ** means that the form of the name is Z and that columns from any table
74237 ** can be used.
74239 ** If the name cannot be resolved unambiguously, leave an error message
74240 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
74242 static int lookupName(
74243 Parse *pParse, /* The parsing context */
74244 const char *zDb, /* Name of the database containing table, or NULL */
74245 const char *zTab, /* Name of table containing column, or NULL */
74246 const char *zCol, /* Name of the column. */
74247 NameContext *pNC, /* The name context used to resolve the name */
74248 Expr *pExpr /* Make this EXPR node point to the selected column */
74250 int i, j; /* Loop counters */
74251 int cnt = 0; /* Number of matching column names */
74252 int cntTab = 0; /* Number of matching table names */
74253 int nSubquery = 0; /* How many levels of subquery */
74254 sqlite3 *db = pParse->db; /* The database connection */
74255 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
74256 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
74257 NameContext *pTopNC = pNC; /* First namecontext in the list */
74258 Schema *pSchema = 0; /* Schema of the expression */
74259 int isTrigger = 0;
74261 assert( pNC ); /* the name context cannot be NULL. */
74262 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
74263 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74265 /* Initialize the node to no-match */
74266 pExpr->iTable = -1;
74267 pExpr->pTab = 0;
74268 ExprSetIrreducible(pExpr);
74270 /* Translate the schema name in zDb into a pointer to the corresponding
74271 ** schema. If not found, pSchema will remain NULL and nothing will match
74272 ** resulting in an appropriate error message toward the end of this routine
74274 if( zDb ){
74275 testcase( pNC->ncFlags & NC_PartIdx );
74276 testcase( pNC->ncFlags & NC_IsCheck );
74277 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
74278 /* Silently ignore database qualifiers inside CHECK constraints and partial
74279 ** indices. Do not raise errors because that might break legacy and
74280 ** because it does not hurt anything to just ignore the database name. */
74281 zDb = 0;
74282 }else{
74283 for(i=0; i<db->nDb; i++){
74284 assert( db->aDb[i].zName );
74285 if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
74286 pSchema = db->aDb[i].pSchema;
74287 break;
74293 /* Start at the inner-most context and move outward until a match is found */
74294 while( pNC && cnt==0 ){
74295 ExprList *pEList;
74296 SrcList *pSrcList = pNC->pSrcList;
74298 if( pSrcList ){
74299 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
74300 Table *pTab;
74301 Column *pCol;
74303 pTab = pItem->pTab;
74304 assert( pTab!=0 && pTab->zName!=0 );
74305 assert( pTab->nCol>0 );
74306 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
74307 int hit = 0;
74308 pEList = pItem->pSelect->pEList;
74309 for(j=0; j<pEList->nExpr; j++){
74310 if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
74311 cnt++;
74312 cntTab = 2;
74313 pMatch = pItem;
74314 pExpr->iColumn = j;
74315 hit = 1;
74318 if( hit || zTab==0 ) continue;
74320 if( zDb && pTab->pSchema!=pSchema ){
74321 continue;
74323 if( zTab ){
74324 const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
74325 assert( zTabName!=0 );
74326 if( sqlite3StrICmp(zTabName, zTab)!=0 ){
74327 continue;
74330 if( 0==(cntTab++) ){
74331 pMatch = pItem;
74333 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
74334 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
74335 /* If there has been exactly one prior match and this match
74336 ** is for the right-hand table of a NATURAL JOIN or is in a
74337 ** USING clause, then skip this match.
74339 if( cnt==1 ){
74340 if( pItem->jointype & JT_NATURAL ) continue;
74341 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
74343 cnt++;
74344 pMatch = pItem;
74345 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
74346 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
74347 break;
74351 if( pMatch ){
74352 pExpr->iTable = pMatch->iCursor;
74353 pExpr->pTab = pMatch->pTab;
74354 pSchema = pExpr->pTab->pSchema;
74356 } /* if( pSrcList ) */
74358 #ifndef SQLITE_OMIT_TRIGGER
74359 /* If we have not already resolved the name, then maybe
74360 ** it is a new.* or old.* trigger argument reference
74362 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
74363 int op = pParse->eTriggerOp;
74364 Table *pTab = 0;
74365 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
74366 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
74367 pExpr->iTable = 1;
74368 pTab = pParse->pTriggerTab;
74369 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
74370 pExpr->iTable = 0;
74371 pTab = pParse->pTriggerTab;
74374 if( pTab ){
74375 int iCol;
74376 pSchema = pTab->pSchema;
74377 cntTab++;
74378 for(iCol=0; iCol<pTab->nCol; iCol++){
74379 Column *pCol = &pTab->aCol[iCol];
74380 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
74381 if( iCol==pTab->iPKey ){
74382 iCol = -1;
74384 break;
74387 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
74388 iCol = -1; /* IMP: R-44911-55124 */
74390 if( iCol<pTab->nCol ){
74391 cnt++;
74392 if( iCol<0 ){
74393 pExpr->affinity = SQLITE_AFF_INTEGER;
74394 }else if( pExpr->iTable==0 ){
74395 testcase( iCol==31 );
74396 testcase( iCol==32 );
74397 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
74398 }else{
74399 testcase( iCol==31 );
74400 testcase( iCol==32 );
74401 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
74403 pExpr->iColumn = (i16)iCol;
74404 pExpr->pTab = pTab;
74405 isTrigger = 1;
74409 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
74412 ** Perhaps the name is a reference to the ROWID
74414 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
74415 cnt = 1;
74416 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
74417 pExpr->affinity = SQLITE_AFF_INTEGER;
74421 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
74422 ** might refer to an result-set alias. This happens, for example, when
74423 ** we are resolving names in the WHERE clause of the following command:
74425 ** SELECT a+b AS x FROM table WHERE x<10;
74427 ** In cases like this, replace pExpr with a copy of the expression that
74428 ** forms the result set entry ("a+b" in the example) and return immediately.
74429 ** Note that the expression in the result set should have already been
74430 ** resolved by the time the WHERE clause is resolved.
74432 ** The ability to use an output result-set column in the WHERE, GROUP BY,
74433 ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
74434 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
74435 ** is supported for backwards compatibility only. TO DO: Issue a warning
74436 ** on sqlite3_log() whenever the capability is used.
74438 if( (pEList = pNC->pEList)!=0
74439 && zTab==0
74440 && cnt==0
74442 for(j=0; j<pEList->nExpr; j++){
74443 char *zAs = pEList->a[j].zName;
74444 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
74445 Expr *pOrig;
74446 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
74447 assert( pExpr->x.pList==0 );
74448 assert( pExpr->x.pSelect==0 );
74449 pOrig = pEList->a[j].pExpr;
74450 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
74451 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
74452 return WRC_Abort;
74454 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
74455 cnt = 1;
74456 pMatch = 0;
74457 assert( zTab==0 && zDb==0 );
74458 goto lookupname_end;
74463 /* Advance to the next name context. The loop will exit when either
74464 ** we have a match (cnt>0) or when we run out of name contexts.
74466 if( cnt==0 ){
74467 pNC = pNC->pNext;
74468 nSubquery++;
74473 ** If X and Y are NULL (in other words if only the column name Z is
74474 ** supplied) and the value of Z is enclosed in double-quotes, then
74475 ** Z is a string literal if it doesn't match any column names. In that
74476 ** case, we need to return right away and not make any changes to
74477 ** pExpr.
74479 ** Because no reference was made to outer contexts, the pNC->nRef
74480 ** fields are not changed in any context.
74482 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
74483 pExpr->op = TK_STRING;
74484 pExpr->pTab = 0;
74485 return WRC_Prune;
74489 ** cnt==0 means there was not match. cnt>1 means there were two or
74490 ** more matches. Either way, we have an error.
74492 if( cnt!=1 ){
74493 const char *zErr;
74494 zErr = cnt==0 ? "no such column" : "ambiguous column name";
74495 if( zDb ){
74496 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
74497 }else if( zTab ){
74498 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
74499 }else{
74500 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
74502 pParse->checkSchema = 1;
74503 pTopNC->nErr++;
74506 /* If a column from a table in pSrcList is referenced, then record
74507 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
74508 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
74509 ** column number is greater than the number of bits in the bitmask
74510 ** then set the high-order bit of the bitmask.
74512 if( pExpr->iColumn>=0 && pMatch!=0 ){
74513 int n = pExpr->iColumn;
74514 testcase( n==BMS-1 );
74515 if( n>=BMS ){
74516 n = BMS-1;
74518 assert( pMatch->iCursor==pExpr->iTable );
74519 pMatch->colUsed |= ((Bitmask)1)<<n;
74522 /* Clean up and return
74524 sqlite3ExprDelete(db, pExpr->pLeft);
74525 pExpr->pLeft = 0;
74526 sqlite3ExprDelete(db, pExpr->pRight);
74527 pExpr->pRight = 0;
74528 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
74529 lookupname_end:
74530 if( cnt==1 ){
74531 assert( pNC!=0 );
74532 if( pExpr->op!=TK_AS ){
74533 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
74535 /* Increment the nRef value on all name contexts from TopNC up to
74536 ** the point where the name matched. */
74537 for(;;){
74538 assert( pTopNC!=0 );
74539 pTopNC->nRef++;
74540 if( pTopNC==pNC ) break;
74541 pTopNC = pTopNC->pNext;
74543 return WRC_Prune;
74544 } else {
74545 return WRC_Abort;
74550 ** Allocate and return a pointer to an expression to load the column iCol
74551 ** from datasource iSrc in SrcList pSrc.
74553 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
74554 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
74555 if( p ){
74556 struct SrcList_item *pItem = &pSrc->a[iSrc];
74557 p->pTab = pItem->pTab;
74558 p->iTable = pItem->iCursor;
74559 if( p->pTab->iPKey==iCol ){
74560 p->iColumn = -1;
74561 }else{
74562 p->iColumn = (ynVar)iCol;
74563 testcase( iCol==BMS );
74564 testcase( iCol==BMS-1 );
74565 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
74567 ExprSetProperty(p, EP_Resolved);
74569 return p;
74573 ** Report an error that an expression is not valid for a partial index WHERE
74574 ** clause.
74576 static void notValidPartIdxWhere(
74577 Parse *pParse, /* Leave error message here */
74578 NameContext *pNC, /* The name context */
74579 const char *zMsg /* Type of error */
74581 if( (pNC->ncFlags & NC_PartIdx)!=0 ){
74582 sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
74583 zMsg);
74587 #ifndef SQLITE_OMIT_CHECK
74589 ** Report an error that an expression is not valid for a CHECK constraint.
74591 static void notValidCheckConstraint(
74592 Parse *pParse, /* Leave error message here */
74593 NameContext *pNC, /* The name context */
74594 const char *zMsg /* Type of error */
74596 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
74597 sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
74600 #else
74601 # define notValidCheckConstraint(P,N,M)
74602 #endif
74606 ** This routine is callback for sqlite3WalkExpr().
74608 ** Resolve symbolic names into TK_COLUMN operators for the current
74609 ** node in the expression tree. Return 0 to continue the search down
74610 ** the tree or 2 to abort the tree walk.
74612 ** This routine also does error checking and name resolution for
74613 ** function names. The operator for aggregate functions is changed
74614 ** to TK_AGG_FUNCTION.
74616 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
74617 NameContext *pNC;
74618 Parse *pParse;
74620 pNC = pWalker->u.pNC;
74621 assert( pNC!=0 );
74622 pParse = pNC->pParse;
74623 assert( pParse==pWalker->pParse );
74625 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
74626 ExprSetProperty(pExpr, EP_Resolved);
74627 #ifndef NDEBUG
74628 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
74629 SrcList *pSrcList = pNC->pSrcList;
74630 int i;
74631 for(i=0; i<pNC->pSrcList->nSrc; i++){
74632 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
74635 #endif
74636 switch( pExpr->op ){
74638 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
74639 /* The special operator TK_ROW means use the rowid for the first
74640 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
74641 ** clause processing on UPDATE and DELETE statements.
74643 case TK_ROW: {
74644 SrcList *pSrcList = pNC->pSrcList;
74645 struct SrcList_item *pItem;
74646 assert( pSrcList && pSrcList->nSrc==1 );
74647 pItem = pSrcList->a;
74648 pExpr->op = TK_COLUMN;
74649 pExpr->pTab = pItem->pTab;
74650 pExpr->iTable = pItem->iCursor;
74651 pExpr->iColumn = -1;
74652 pExpr->affinity = SQLITE_AFF_INTEGER;
74653 break;
74655 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
74657 /* A lone identifier is the name of a column.
74659 case TK_ID: {
74660 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
74663 /* A table name and column name: ID.ID
74664 ** Or a database, table and column: ID.ID.ID
74666 case TK_DOT: {
74667 const char *zColumn;
74668 const char *zTable;
74669 const char *zDb;
74670 Expr *pRight;
74672 /* if( pSrcList==0 ) break; */
74673 pRight = pExpr->pRight;
74674 if( pRight->op==TK_ID ){
74675 zDb = 0;
74676 zTable = pExpr->pLeft->u.zToken;
74677 zColumn = pRight->u.zToken;
74678 }else{
74679 assert( pRight->op==TK_DOT );
74680 zDb = pExpr->pLeft->u.zToken;
74681 zTable = pRight->pLeft->u.zToken;
74682 zColumn = pRight->pRight->u.zToken;
74684 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
74687 /* Resolve function names
74689 case TK_CONST_FUNC:
74690 case TK_FUNCTION: {
74691 ExprList *pList = pExpr->x.pList; /* The argument list */
74692 int n = pList ? pList->nExpr : 0; /* Number of arguments */
74693 int no_such_func = 0; /* True if no such function exists */
74694 int wrong_num_args = 0; /* True if wrong number of arguments */
74695 int is_agg = 0; /* True if is an aggregate function */
74696 int auth; /* Authorization to use the function */
74697 int nId; /* Number of characters in function name */
74698 const char *zId; /* The function name. */
74699 FuncDef *pDef; /* Information about the function */
74700 u8 enc = ENC(pParse->db); /* The database encoding */
74702 testcase( pExpr->op==TK_CONST_FUNC );
74703 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74704 notValidPartIdxWhere(pParse, pNC, "functions");
74705 zId = pExpr->u.zToken;
74706 nId = sqlite3Strlen30(zId);
74707 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
74708 if( pDef==0 ){
74709 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
74710 if( pDef==0 ){
74711 no_such_func = 1;
74712 }else{
74713 wrong_num_args = 1;
74715 }else{
74716 is_agg = pDef->xFunc==0;
74718 #ifndef SQLITE_OMIT_AUTHORIZATION
74719 if( pDef ){
74720 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
74721 if( auth!=SQLITE_OK ){
74722 if( auth==SQLITE_DENY ){
74723 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
74724 pDef->zName);
74725 pNC->nErr++;
74727 pExpr->op = TK_NULL;
74728 return WRC_Prune;
74731 #endif
74732 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
74733 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
74734 pNC->nErr++;
74735 is_agg = 0;
74736 }else if( no_such_func && pParse->db->init.busy==0 ){
74737 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
74738 pNC->nErr++;
74739 }else if( wrong_num_args ){
74740 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
74741 nId, zId);
74742 pNC->nErr++;
74744 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
74745 sqlite3WalkExprList(pWalker, pList);
74746 if( is_agg ){
74747 NameContext *pNC2 = pNC;
74748 pExpr->op = TK_AGG_FUNCTION;
74749 pExpr->op2 = 0;
74750 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
74751 pExpr->op2++;
74752 pNC2 = pNC2->pNext;
74754 if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
74755 pNC->ncFlags |= NC_AllowAgg;
74757 /* FIX ME: Compute pExpr->affinity based on the expected return
74758 ** type of the function
74760 return WRC_Prune;
74762 #ifndef SQLITE_OMIT_SUBQUERY
74763 case TK_SELECT:
74764 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
74765 #endif
74766 case TK_IN: {
74767 testcase( pExpr->op==TK_IN );
74768 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74769 int nRef = pNC->nRef;
74770 notValidCheckConstraint(pParse, pNC, "subqueries");
74771 notValidPartIdxWhere(pParse, pNC, "subqueries");
74772 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
74773 assert( pNC->nRef>=nRef );
74774 if( nRef!=pNC->nRef ){
74775 ExprSetProperty(pExpr, EP_VarSelect);
74778 break;
74780 case TK_VARIABLE: {
74781 notValidCheckConstraint(pParse, pNC, "parameters");
74782 notValidPartIdxWhere(pParse, pNC, "parameters");
74783 break;
74786 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
74790 ** pEList is a list of expressions which are really the result set of the
74791 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
74792 ** This routine checks to see if pE is a simple identifier which corresponds
74793 ** to the AS-name of one of the terms of the expression list. If it is,
74794 ** this routine return an integer between 1 and N where N is the number of
74795 ** elements in pEList, corresponding to the matching entry. If there is
74796 ** no match, or if pE is not a simple identifier, then this routine
74797 ** return 0.
74799 ** pEList has been resolved. pE has not.
74801 static int resolveAsName(
74802 Parse *pParse, /* Parsing context for error messages */
74803 ExprList *pEList, /* List of expressions to scan */
74804 Expr *pE /* Expression we are trying to match */
74806 int i; /* Loop counter */
74808 UNUSED_PARAMETER(pParse);
74810 if( pE->op==TK_ID ){
74811 char *zCol = pE->u.zToken;
74812 for(i=0; i<pEList->nExpr; i++){
74813 char *zAs = pEList->a[i].zName;
74814 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
74815 return i+1;
74819 return 0;
74823 ** pE is a pointer to an expression which is a single term in the
74824 ** ORDER BY of a compound SELECT. The expression has not been
74825 ** name resolved.
74827 ** At the point this routine is called, we already know that the
74828 ** ORDER BY term is not an integer index into the result set. That
74829 ** case is handled by the calling routine.
74831 ** Attempt to match pE against result set columns in the left-most
74832 ** SELECT statement. Return the index i of the matching column,
74833 ** as an indication to the caller that it should sort by the i-th column.
74834 ** The left-most column is 1. In other words, the value returned is the
74835 ** same integer value that would be used in the SQL statement to indicate
74836 ** the column.
74838 ** If there is no match, return 0. Return -1 if an error occurs.
74840 static int resolveOrderByTermToExprList(
74841 Parse *pParse, /* Parsing context for error messages */
74842 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
74843 Expr *pE /* The specific ORDER BY term */
74845 int i; /* Loop counter */
74846 ExprList *pEList; /* The columns of the result set */
74847 NameContext nc; /* Name context for resolving pE */
74848 sqlite3 *db; /* Database connection */
74849 int rc; /* Return code from subprocedures */
74850 u8 savedSuppErr; /* Saved value of db->suppressErr */
74852 assert( sqlite3ExprIsInteger(pE, &i)==0 );
74853 pEList = pSelect->pEList;
74855 /* Resolve all names in the ORDER BY term expression
74857 memset(&nc, 0, sizeof(nc));
74858 nc.pParse = pParse;
74859 nc.pSrcList = pSelect->pSrc;
74860 nc.pEList = pEList;
74861 nc.ncFlags = NC_AllowAgg;
74862 nc.nErr = 0;
74863 db = pParse->db;
74864 savedSuppErr = db->suppressErr;
74865 db->suppressErr = 1;
74866 rc = sqlite3ResolveExprNames(&nc, pE);
74867 db->suppressErr = savedSuppErr;
74868 if( rc ) return 0;
74870 /* Try to match the ORDER BY expression against an expression
74871 ** in the result set. Return an 1-based index of the matching
74872 ** result-set entry.
74874 for(i=0; i<pEList->nExpr; i++){
74875 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
74876 return i+1;
74880 /* If no match, return 0. */
74881 return 0;
74885 ** Generate an ORDER BY or GROUP BY term out-of-range error.
74887 static void resolveOutOfRangeError(
74888 Parse *pParse, /* The error context into which to write the error */
74889 const char *zType, /* "ORDER" or "GROUP" */
74890 int i, /* The index (1-based) of the term out of range */
74891 int mx /* Largest permissible value of i */
74893 sqlite3ErrorMsg(pParse,
74894 "%r %s BY term out of range - should be "
74895 "between 1 and %d", i, zType, mx);
74899 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
74900 ** each term of the ORDER BY clause is a constant integer between 1
74901 ** and N where N is the number of columns in the compound SELECT.
74903 ** ORDER BY terms that are already an integer between 1 and N are
74904 ** unmodified. ORDER BY terms that are integers outside the range of
74905 ** 1 through N generate an error. ORDER BY terms that are expressions
74906 ** are matched against result set expressions of compound SELECT
74907 ** beginning with the left-most SELECT and working toward the right.
74908 ** At the first match, the ORDER BY expression is transformed into
74909 ** the integer column number.
74911 ** Return the number of errors seen.
74913 static int resolveCompoundOrderBy(
74914 Parse *pParse, /* Parsing context. Leave error messages here */
74915 Select *pSelect /* The SELECT statement containing the ORDER BY */
74917 int i;
74918 ExprList *pOrderBy;
74919 ExprList *pEList;
74920 sqlite3 *db;
74921 int moreToDo = 1;
74923 pOrderBy = pSelect->pOrderBy;
74924 if( pOrderBy==0 ) return 0;
74925 db = pParse->db;
74926 #if SQLITE_MAX_COLUMN
74927 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74928 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
74929 return 1;
74931 #endif
74932 for(i=0; i<pOrderBy->nExpr; i++){
74933 pOrderBy->a[i].done = 0;
74935 pSelect->pNext = 0;
74936 while( pSelect->pPrior ){
74937 pSelect->pPrior->pNext = pSelect;
74938 pSelect = pSelect->pPrior;
74940 while( pSelect && moreToDo ){
74941 struct ExprList_item *pItem;
74942 moreToDo = 0;
74943 pEList = pSelect->pEList;
74944 assert( pEList!=0 );
74945 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74946 int iCol = -1;
74947 Expr *pE, *pDup;
74948 if( pItem->done ) continue;
74949 pE = sqlite3ExprSkipCollate(pItem->pExpr);
74950 if( sqlite3ExprIsInteger(pE, &iCol) ){
74951 if( iCol<=0 || iCol>pEList->nExpr ){
74952 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
74953 return 1;
74955 }else{
74956 iCol = resolveAsName(pParse, pEList, pE);
74957 if( iCol==0 ){
74958 pDup = sqlite3ExprDup(db, pE, 0);
74959 if( !db->mallocFailed ){
74960 assert(pDup);
74961 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
74963 sqlite3ExprDelete(db, pDup);
74966 if( iCol>0 ){
74967 /* Convert the ORDER BY term into an integer column number iCol,
74968 ** taking care to preserve the COLLATE clause if it exists */
74969 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
74970 if( pNew==0 ) return 1;
74971 pNew->flags |= EP_IntValue;
74972 pNew->u.iValue = iCol;
74973 if( pItem->pExpr==pE ){
74974 pItem->pExpr = pNew;
74975 }else{
74976 assert( pItem->pExpr->op==TK_COLLATE );
74977 assert( pItem->pExpr->pLeft==pE );
74978 pItem->pExpr->pLeft = pNew;
74980 sqlite3ExprDelete(db, pE);
74981 pItem->iOrderByCol = (u16)iCol;
74982 pItem->done = 1;
74983 }else{
74984 moreToDo = 1;
74987 pSelect = pSelect->pNext;
74989 for(i=0; i<pOrderBy->nExpr; i++){
74990 if( pOrderBy->a[i].done==0 ){
74991 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
74992 "column in the result set", i+1);
74993 return 1;
74996 return 0;
75000 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
75001 ** the SELECT statement pSelect. If any term is reference to a
75002 ** result set expression (as determined by the ExprList.a.iOrderByCol field)
75003 ** then convert that term into a copy of the corresponding result set
75004 ** column.
75006 ** If any errors are detected, add an error message to pParse and
75007 ** return non-zero. Return zero if no errors are seen.
75009 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
75010 Parse *pParse, /* Parsing context. Leave error messages here */
75011 Select *pSelect, /* The SELECT statement containing the clause */
75012 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
75013 const char *zType /* "ORDER" or "GROUP" */
75015 int i;
75016 sqlite3 *db = pParse->db;
75017 ExprList *pEList;
75018 struct ExprList_item *pItem;
75020 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
75021 #if SQLITE_MAX_COLUMN
75022 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
75023 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
75024 return 1;
75026 #endif
75027 pEList = pSelect->pEList;
75028 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
75029 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
75030 if( pItem->iOrderByCol ){
75031 if( pItem->iOrderByCol>pEList->nExpr ){
75032 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
75033 return 1;
75035 resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
75038 return 0;
75042 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
75043 ** The Name context of the SELECT statement is pNC. zType is either
75044 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
75046 ** This routine resolves each term of the clause into an expression.
75047 ** If the order-by term is an integer I between 1 and N (where N is the
75048 ** number of columns in the result set of the SELECT) then the expression
75049 ** in the resolution is a copy of the I-th result-set expression. If
75050 ** the order-by term is an identifier that corresponds to the AS-name of
75051 ** a result-set expression, then the term resolves to a copy of the
75052 ** result-set expression. Otherwise, the expression is resolved in
75053 ** the usual way - using sqlite3ResolveExprNames().
75055 ** This routine returns the number of errors. If errors occur, then
75056 ** an appropriate error message might be left in pParse. (OOM errors
75057 ** excepted.)
75059 static int resolveOrderGroupBy(
75060 NameContext *pNC, /* The name context of the SELECT statement */
75061 Select *pSelect, /* The SELECT statement holding pOrderBy */
75062 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
75063 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
75065 int i, j; /* Loop counters */
75066 int iCol; /* Column number */
75067 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
75068 Parse *pParse; /* Parsing context */
75069 int nResult; /* Number of terms in the result set */
75071 if( pOrderBy==0 ) return 0;
75072 nResult = pSelect->pEList->nExpr;
75073 pParse = pNC->pParse;
75074 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
75075 Expr *pE = pItem->pExpr;
75076 Expr *pE2 = sqlite3ExprSkipCollate(pE);
75077 if( zType[0]!='G' ){
75078 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
75079 if( iCol>0 ){
75080 /* If an AS-name match is found, mark this ORDER BY column as being
75081 ** a copy of the iCol-th result-set column. The subsequent call to
75082 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
75083 ** copy of the iCol-th result-set expression. */
75084 pItem->iOrderByCol = (u16)iCol;
75085 continue;
75088 if( sqlite3ExprIsInteger(pE2, &iCol) ){
75089 /* The ORDER BY term is an integer constant. Again, set the column
75090 ** number so that sqlite3ResolveOrderGroupBy() will convert the
75091 ** order-by term to a copy of the result-set expression */
75092 if( iCol<1 || iCol>0xffff ){
75093 resolveOutOfRangeError(pParse, zType, i+1, nResult);
75094 return 1;
75096 pItem->iOrderByCol = (u16)iCol;
75097 continue;
75100 /* Otherwise, treat the ORDER BY term as an ordinary expression */
75101 pItem->iOrderByCol = 0;
75102 if( sqlite3ResolveExprNames(pNC, pE) ){
75103 return 1;
75105 for(j=0; j<pSelect->pEList->nExpr; j++){
75106 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
75107 pItem->iOrderByCol = j+1;
75111 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
75115 ** Resolve names in the SELECT statement p and all of its descendents.
75117 static int resolveSelectStep(Walker *pWalker, Select *p){
75118 NameContext *pOuterNC; /* Context that contains this SELECT */
75119 NameContext sNC; /* Name context of this SELECT */
75120 int isCompound; /* True if p is a compound select */
75121 int nCompound; /* Number of compound terms processed so far */
75122 Parse *pParse; /* Parsing context */
75123 ExprList *pEList; /* Result set expression list */
75124 int i; /* Loop counter */
75125 ExprList *pGroupBy; /* The GROUP BY clause */
75126 Select *pLeftmost; /* Left-most of SELECT of a compound */
75127 sqlite3 *db; /* Database connection */
75130 assert( p!=0 );
75131 if( p->selFlags & SF_Resolved ){
75132 return WRC_Prune;
75134 pOuterNC = pWalker->u.pNC;
75135 pParse = pWalker->pParse;
75136 db = pParse->db;
75138 /* Normally sqlite3SelectExpand() will be called first and will have
75139 ** already expanded this SELECT. However, if this is a subquery within
75140 ** an expression, sqlite3ResolveExprNames() will be called without a
75141 ** prior call to sqlite3SelectExpand(). When that happens, let
75142 ** sqlite3SelectPrep() do all of the processing for this SELECT.
75143 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
75144 ** this routine in the correct order.
75146 if( (p->selFlags & SF_Expanded)==0 ){
75147 sqlite3SelectPrep(pParse, p, pOuterNC);
75148 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
75151 isCompound = p->pPrior!=0;
75152 nCompound = 0;
75153 pLeftmost = p;
75154 while( p ){
75155 assert( (p->selFlags & SF_Expanded)!=0 );
75156 assert( (p->selFlags & SF_Resolved)==0 );
75157 p->selFlags |= SF_Resolved;
75159 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
75160 ** are not allowed to refer to any names, so pass an empty NameContext.
75162 memset(&sNC, 0, sizeof(sNC));
75163 sNC.pParse = pParse;
75164 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
75165 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
75166 return WRC_Abort;
75169 /* Recursively resolve names in all subqueries
75171 for(i=0; i<p->pSrc->nSrc; i++){
75172 struct SrcList_item *pItem = &p->pSrc->a[i];
75173 if( pItem->pSelect ){
75174 NameContext *pNC; /* Used to iterate name contexts */
75175 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
75176 const char *zSavedContext = pParse->zAuthContext;
75178 /* Count the total number of references to pOuterNC and all of its
75179 ** parent contexts. After resolving references to expressions in
75180 ** pItem->pSelect, check if this value has changed. If so, then
75181 ** SELECT statement pItem->pSelect must be correlated. Set the
75182 ** pItem->isCorrelated flag if this is the case. */
75183 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
75185 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
75186 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
75187 pParse->zAuthContext = zSavedContext;
75188 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
75190 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
75191 assert( pItem->isCorrelated==0 && nRef<=0 );
75192 pItem->isCorrelated = (nRef!=0);
75196 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
75197 ** resolve the result-set expression list.
75199 sNC.ncFlags = NC_AllowAgg;
75200 sNC.pSrcList = p->pSrc;
75201 sNC.pNext = pOuterNC;
75203 /* Resolve names in the result set. */
75204 pEList = p->pEList;
75205 assert( pEList!=0 );
75206 for(i=0; i<pEList->nExpr; i++){
75207 Expr *pX = pEList->a[i].pExpr;
75208 if( sqlite3ResolveExprNames(&sNC, pX) ){
75209 return WRC_Abort;
75213 /* If there are no aggregate functions in the result-set, and no GROUP BY
75214 ** expression, do not allow aggregates in any of the other expressions.
75216 assert( (p->selFlags & SF_Aggregate)==0 );
75217 pGroupBy = p->pGroupBy;
75218 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
75219 p->selFlags |= SF_Aggregate;
75220 }else{
75221 sNC.ncFlags &= ~NC_AllowAgg;
75224 /* If a HAVING clause is present, then there must be a GROUP BY clause.
75226 if( p->pHaving && !pGroupBy ){
75227 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
75228 return WRC_Abort;
75231 /* Add the output column list to the name-context before parsing the
75232 ** other expressions in the SELECT statement. This is so that
75233 ** expressions in the WHERE clause (etc.) can refer to expressions by
75234 ** aliases in the result set.
75236 ** Minor point: If this is the case, then the expression will be
75237 ** re-evaluated for each reference to it.
75239 sNC.pEList = p->pEList;
75240 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
75241 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
75243 /* The ORDER BY and GROUP BY clauses may not refer to terms in
75244 ** outer queries
75246 sNC.pNext = 0;
75247 sNC.ncFlags |= NC_AllowAgg;
75249 /* Process the ORDER BY clause for singleton SELECT statements.
75250 ** The ORDER BY clause for compounds SELECT statements is handled
75251 ** below, after all of the result-sets for all of the elements of
75252 ** the compound have been resolved.
75254 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
75255 return WRC_Abort;
75257 if( db->mallocFailed ){
75258 return WRC_Abort;
75261 /* Resolve the GROUP BY clause. At the same time, make sure
75262 ** the GROUP BY clause does not contain aggregate functions.
75264 if( pGroupBy ){
75265 struct ExprList_item *pItem;
75267 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
75268 return WRC_Abort;
75270 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
75271 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
75272 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
75273 "the GROUP BY clause");
75274 return WRC_Abort;
75279 /* Advance to the next term of the compound
75281 p = p->pPrior;
75282 nCompound++;
75285 /* Resolve the ORDER BY on a compound SELECT after all terms of
75286 ** the compound have been resolved.
75288 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
75289 return WRC_Abort;
75292 return WRC_Prune;
75296 ** This routine walks an expression tree and resolves references to
75297 ** table columns and result-set columns. At the same time, do error
75298 ** checking on function usage and set a flag if any aggregate functions
75299 ** are seen.
75301 ** To resolve table columns references we look for nodes (or subtrees) of the
75302 ** form X.Y.Z or Y.Z or just Z where
75304 ** X: The name of a database. Ex: "main" or "temp" or
75305 ** the symbolic name assigned to an ATTACH-ed database.
75307 ** Y: The name of a table in a FROM clause. Or in a trigger
75308 ** one of the special names "old" or "new".
75310 ** Z: The name of a column in table Y.
75312 ** The node at the root of the subtree is modified as follows:
75314 ** Expr.op Changed to TK_COLUMN
75315 ** Expr.pTab Points to the Table object for X.Y
75316 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
75317 ** Expr.iTable The VDBE cursor number for X.Y
75320 ** To resolve result-set references, look for expression nodes of the
75321 ** form Z (with no X and Y prefix) where the Z matches the right-hand
75322 ** size of an AS clause in the result-set of a SELECT. The Z expression
75323 ** is replaced by a copy of the left-hand side of the result-set expression.
75324 ** Table-name and function resolution occurs on the substituted expression
75325 ** tree. For example, in:
75327 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
75329 ** The "x" term of the order by is replaced by "a+b" to render:
75331 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
75333 ** Function calls are checked to make sure that the function is
75334 ** defined and that the correct number of arguments are specified.
75335 ** If the function is an aggregate function, then the NC_HasAgg flag is
75336 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
75337 ** If an expression contains aggregate functions then the EP_Agg
75338 ** property on the expression is set.
75340 ** An error message is left in pParse if anything is amiss. The number
75341 ** if errors is returned.
75343 SQLITE_PRIVATE int sqlite3ResolveExprNames(
75344 NameContext *pNC, /* Namespace to resolve expressions in. */
75345 Expr *pExpr /* The expression to be analyzed. */
75347 u8 savedHasAgg;
75348 Walker w;
75350 if( pExpr==0 ) return 0;
75351 #if SQLITE_MAX_EXPR_DEPTH>0
75353 Parse *pParse = pNC->pParse;
75354 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
75355 return 1;
75357 pParse->nHeight += pExpr->nHeight;
75359 #endif
75360 savedHasAgg = pNC->ncFlags & NC_HasAgg;
75361 pNC->ncFlags &= ~NC_HasAgg;
75362 memset(&w, 0, sizeof(w));
75363 w.xExprCallback = resolveExprStep;
75364 w.xSelectCallback = resolveSelectStep;
75365 w.pParse = pNC->pParse;
75366 w.u.pNC = pNC;
75367 sqlite3WalkExpr(&w, pExpr);
75368 #if SQLITE_MAX_EXPR_DEPTH>0
75369 pNC->pParse->nHeight -= pExpr->nHeight;
75370 #endif
75371 if( pNC->nErr>0 || w.pParse->nErr>0 ){
75372 ExprSetProperty(pExpr, EP_Error);
75374 if( pNC->ncFlags & NC_HasAgg ){
75375 ExprSetProperty(pExpr, EP_Agg);
75376 }else if( savedHasAgg ){
75377 pNC->ncFlags |= NC_HasAgg;
75379 return ExprHasProperty(pExpr, EP_Error);
75384 ** Resolve all names in all expressions of a SELECT and in all
75385 ** decendents of the SELECT, including compounds off of p->pPrior,
75386 ** subqueries in expressions, and subqueries used as FROM clause
75387 ** terms.
75389 ** See sqlite3ResolveExprNames() for a description of the kinds of
75390 ** transformations that occur.
75392 ** All SELECT statements should have been expanded using
75393 ** sqlite3SelectExpand() prior to invoking this routine.
75395 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
75396 Parse *pParse, /* The parser context */
75397 Select *p, /* The SELECT statement being coded. */
75398 NameContext *pOuterNC /* Name context for parent SELECT statement */
75400 Walker w;
75402 assert( p!=0 );
75403 memset(&w, 0, sizeof(w));
75404 w.xExprCallback = resolveExprStep;
75405 w.xSelectCallback = resolveSelectStep;
75406 w.pParse = pParse;
75407 w.u.pNC = pOuterNC;
75408 sqlite3WalkSelect(&w, p);
75412 ** Resolve names in expressions that can only reference a single table:
75414 ** * CHECK constraints
75415 ** * WHERE clauses on partial indices
75417 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
75418 ** is set to -1 and the Expr.iColumn value is set to the column number.
75420 ** Any errors cause an error message to be set in pParse.
75422 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
75423 Parse *pParse, /* Parsing context */
75424 Table *pTab, /* The table being referenced */
75425 int type, /* NC_IsCheck or NC_PartIdx */
75426 Expr *pExpr, /* Expression to resolve. May be NULL. */
75427 ExprList *pList /* Expression list to resolve. May be NUL. */
75429 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
75430 NameContext sNC; /* Name context for pParse->pNewTable */
75431 int i; /* Loop counter */
75433 assert( type==NC_IsCheck || type==NC_PartIdx );
75434 memset(&sNC, 0, sizeof(sNC));
75435 memset(&sSrc, 0, sizeof(sSrc));
75436 sSrc.nSrc = 1;
75437 sSrc.a[0].zName = pTab->zName;
75438 sSrc.a[0].pTab = pTab;
75439 sSrc.a[0].iCursor = -1;
75440 sNC.pParse = pParse;
75441 sNC.pSrcList = &sSrc;
75442 sNC.ncFlags = type;
75443 if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
75444 if( pList ){
75445 for(i=0; i<pList->nExpr; i++){
75446 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
75447 return;
75453 /************** End of resolve.c *********************************************/
75454 /************** Begin file expr.c ********************************************/
75456 ** 2001 September 15
75458 ** The author disclaims copyright to this source code. In place of
75459 ** a legal notice, here is a blessing:
75461 ** May you do good and not evil.
75462 ** May you find forgiveness for yourself and forgive others.
75463 ** May you share freely, never taking more than you give.
75465 *************************************************************************
75466 ** This file contains routines used for analyzing expressions and
75467 ** for generating VDBE code that evaluates expressions in SQLite.
75471 ** Return the 'affinity' of the expression pExpr if any.
75473 ** If pExpr is a column, a reference to a column via an 'AS' alias,
75474 ** or a sub-select with a column as the return value, then the
75475 ** affinity of that column is returned. Otherwise, 0x00 is returned,
75476 ** indicating no affinity for the expression.
75478 ** i.e. the WHERE clause expresssions in the following statements all
75479 ** have an affinity:
75481 ** CREATE TABLE t1(a);
75482 ** SELECT * FROM t1 WHERE a;
75483 ** SELECT a AS b FROM t1 WHERE b;
75484 ** SELECT * FROM t1 WHERE (select a from t1);
75486 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
75487 int op;
75488 pExpr = sqlite3ExprSkipCollate(pExpr);
75489 op = pExpr->op;
75490 if( op==TK_SELECT ){
75491 assert( pExpr->flags&EP_xIsSelect );
75492 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
75494 #ifndef SQLITE_OMIT_CAST
75495 if( op==TK_CAST ){
75496 assert( !ExprHasProperty(pExpr, EP_IntValue) );
75497 return sqlite3AffinityType(pExpr->u.zToken);
75499 #endif
75500 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
75501 && pExpr->pTab!=0
75503 /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
75504 ** a TK_COLUMN but was previously evaluated and cached in a register */
75505 int j = pExpr->iColumn;
75506 if( j<0 ) return SQLITE_AFF_INTEGER;
75507 assert( pExpr->pTab && j<pExpr->pTab->nCol );
75508 return pExpr->pTab->aCol[j].affinity;
75510 return pExpr->affinity;
75514 ** Set the collating sequence for expression pExpr to be the collating
75515 ** sequence named by pToken. Return a pointer to a new Expr node that
75516 ** implements the COLLATE operator.
75518 ** If a memory allocation error occurs, that fact is recorded in pParse->db
75519 ** and the pExpr parameter is returned unchanged.
75521 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
75522 if( pCollName->n>0 ){
75523 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
75524 if( pNew ){
75525 pNew->pLeft = pExpr;
75526 pNew->flags |= EP_Collate;
75527 pExpr = pNew;
75530 return pExpr;
75532 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
75533 Token s;
75534 assert( zC!=0 );
75535 s.z = zC;
75536 s.n = sqlite3Strlen30(s.z);
75537 return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
75541 ** Skip over any TK_COLLATE and/or TK_AS operators at the root of
75542 ** an expression.
75544 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
75545 while( pExpr && (pExpr->op==TK_COLLATE || pExpr->op==TK_AS) ){
75546 pExpr = pExpr->pLeft;
75548 return pExpr;
75552 ** Return the collation sequence for the expression pExpr. If
75553 ** there is no defined collating sequence, return NULL.
75555 ** The collating sequence might be determined by a COLLATE operator
75556 ** or by the presence of a column with a defined collating sequence.
75557 ** COLLATE operators take first precedence. Left operands take
75558 ** precedence over right operands.
75560 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
75561 sqlite3 *db = pParse->db;
75562 CollSeq *pColl = 0;
75563 Expr *p = pExpr;
75564 while( p ){
75565 int op = p->op;
75566 if( op==TK_CAST || op==TK_UPLUS ){
75567 p = p->pLeft;
75568 continue;
75570 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
75571 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
75572 break;
75574 if( p->pTab!=0
75575 && (op==TK_AGG_COLUMN || op==TK_COLUMN
75576 || op==TK_REGISTER || op==TK_TRIGGER)
75578 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
75579 ** a TK_COLUMN but was previously evaluated and cached in a register */
75580 int j = p->iColumn;
75581 if( j>=0 ){
75582 const char *zColl = p->pTab->aCol[j].zColl;
75583 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
75585 break;
75587 if( p->flags & EP_Collate ){
75588 if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
75589 p = p->pLeft;
75590 }else{
75591 p = p->pRight;
75593 }else{
75594 break;
75597 if( sqlite3CheckCollSeq(pParse, pColl) ){
75598 pColl = 0;
75600 return pColl;
75604 ** pExpr is an operand of a comparison operator. aff2 is the
75605 ** type affinity of the other operand. This routine returns the
75606 ** type affinity that should be used for the comparison operator.
75608 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
75609 char aff1 = sqlite3ExprAffinity(pExpr);
75610 if( aff1 && aff2 ){
75611 /* Both sides of the comparison are columns. If one has numeric
75612 ** affinity, use that. Otherwise use no affinity.
75614 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
75615 return SQLITE_AFF_NUMERIC;
75616 }else{
75617 return SQLITE_AFF_NONE;
75619 }else if( !aff1 && !aff2 ){
75620 /* Neither side of the comparison is a column. Compare the
75621 ** results directly.
75623 return SQLITE_AFF_NONE;
75624 }else{
75625 /* One side is a column, the other is not. Use the columns affinity. */
75626 assert( aff1==0 || aff2==0 );
75627 return (aff1 + aff2);
75632 ** pExpr is a comparison operator. Return the type affinity that should
75633 ** be applied to both operands prior to doing the comparison.
75635 static char comparisonAffinity(Expr *pExpr){
75636 char aff;
75637 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
75638 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
75639 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
75640 assert( pExpr->pLeft );
75641 aff = sqlite3ExprAffinity(pExpr->pLeft);
75642 if( pExpr->pRight ){
75643 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
75644 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
75645 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
75646 }else if( !aff ){
75647 aff = SQLITE_AFF_NONE;
75649 return aff;
75653 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
75654 ** idx_affinity is the affinity of an indexed column. Return true
75655 ** if the index with affinity idx_affinity may be used to implement
75656 ** the comparison in pExpr.
75658 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
75659 char aff = comparisonAffinity(pExpr);
75660 switch( aff ){
75661 case SQLITE_AFF_NONE:
75662 return 1;
75663 case SQLITE_AFF_TEXT:
75664 return idx_affinity==SQLITE_AFF_TEXT;
75665 default:
75666 return sqlite3IsNumericAffinity(idx_affinity);
75671 ** Return the P5 value that should be used for a binary comparison
75672 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
75674 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
75675 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
75676 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
75677 return aff;
75681 ** Return a pointer to the collation sequence that should be used by
75682 ** a binary comparison operator comparing pLeft and pRight.
75684 ** If the left hand expression has a collating sequence type, then it is
75685 ** used. Otherwise the collation sequence for the right hand expression
75686 ** is used, or the default (BINARY) if neither expression has a collating
75687 ** type.
75689 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
75690 ** it is not considered.
75692 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
75693 Parse *pParse,
75694 Expr *pLeft,
75695 Expr *pRight
75697 CollSeq *pColl;
75698 assert( pLeft );
75699 if( pLeft->flags & EP_Collate ){
75700 pColl = sqlite3ExprCollSeq(pParse, pLeft);
75701 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
75702 pColl = sqlite3ExprCollSeq(pParse, pRight);
75703 }else{
75704 pColl = sqlite3ExprCollSeq(pParse, pLeft);
75705 if( !pColl ){
75706 pColl = sqlite3ExprCollSeq(pParse, pRight);
75709 return pColl;
75713 ** Generate code for a comparison operator.
75715 static int codeCompare(
75716 Parse *pParse, /* The parsing (and code generating) context */
75717 Expr *pLeft, /* The left operand */
75718 Expr *pRight, /* The right operand */
75719 int opcode, /* The comparison opcode */
75720 int in1, int in2, /* Register holding operands */
75721 int dest, /* Jump here if true. */
75722 int jumpIfNull /* If true, jump if either operand is NULL */
75724 int p5;
75725 int addr;
75726 CollSeq *p4;
75728 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
75729 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
75730 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
75731 (void*)p4, P4_COLLSEQ);
75732 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
75733 return addr;
75736 #if SQLITE_MAX_EXPR_DEPTH>0
75738 ** Check that argument nHeight is less than or equal to the maximum
75739 ** expression depth allowed. If it is not, leave an error message in
75740 ** pParse.
75742 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
75743 int rc = SQLITE_OK;
75744 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
75745 if( nHeight>mxHeight ){
75746 sqlite3ErrorMsg(pParse,
75747 "Expression tree is too large (maximum depth %d)", mxHeight
75749 rc = SQLITE_ERROR;
75751 return rc;
75754 /* The following three functions, heightOfExpr(), heightOfExprList()
75755 ** and heightOfSelect(), are used to determine the maximum height
75756 ** of any expression tree referenced by the structure passed as the
75757 ** first argument.
75759 ** If this maximum height is greater than the current value pointed
75760 ** to by pnHeight, the second parameter, then set *pnHeight to that
75761 ** value.
75763 static void heightOfExpr(Expr *p, int *pnHeight){
75764 if( p ){
75765 if( p->nHeight>*pnHeight ){
75766 *pnHeight = p->nHeight;
75770 static void heightOfExprList(ExprList *p, int *pnHeight){
75771 if( p ){
75772 int i;
75773 for(i=0; i<p->nExpr; i++){
75774 heightOfExpr(p->a[i].pExpr, pnHeight);
75778 static void heightOfSelect(Select *p, int *pnHeight){
75779 if( p ){
75780 heightOfExpr(p->pWhere, pnHeight);
75781 heightOfExpr(p->pHaving, pnHeight);
75782 heightOfExpr(p->pLimit, pnHeight);
75783 heightOfExpr(p->pOffset, pnHeight);
75784 heightOfExprList(p->pEList, pnHeight);
75785 heightOfExprList(p->pGroupBy, pnHeight);
75786 heightOfExprList(p->pOrderBy, pnHeight);
75787 heightOfSelect(p->pPrior, pnHeight);
75792 ** Set the Expr.nHeight variable in the structure passed as an
75793 ** argument. An expression with no children, Expr.pList or
75794 ** Expr.pSelect member has a height of 1. Any other expression
75795 ** has a height equal to the maximum height of any other
75796 ** referenced Expr plus one.
75798 static void exprSetHeight(Expr *p){
75799 int nHeight = 0;
75800 heightOfExpr(p->pLeft, &nHeight);
75801 heightOfExpr(p->pRight, &nHeight);
75802 if( ExprHasProperty(p, EP_xIsSelect) ){
75803 heightOfSelect(p->x.pSelect, &nHeight);
75804 }else{
75805 heightOfExprList(p->x.pList, &nHeight);
75807 p->nHeight = nHeight + 1;
75811 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
75812 ** the height is greater than the maximum allowed expression depth,
75813 ** leave an error in pParse.
75815 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
75816 exprSetHeight(p);
75817 sqlite3ExprCheckHeight(pParse, p->nHeight);
75821 ** Return the maximum height of any expression tree referenced
75822 ** by the select statement passed as an argument.
75824 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
75825 int nHeight = 0;
75826 heightOfSelect(p, &nHeight);
75827 return nHeight;
75829 #else
75830 #define exprSetHeight(y)
75831 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
75834 ** This routine is the core allocator for Expr nodes.
75836 ** Construct a new expression node and return a pointer to it. Memory
75837 ** for this node and for the pToken argument is a single allocation
75838 ** obtained from sqlite3DbMalloc(). The calling function
75839 ** is responsible for making sure the node eventually gets freed.
75841 ** If dequote is true, then the token (if it exists) is dequoted.
75842 ** If dequote is false, no dequoting is performance. The deQuote
75843 ** parameter is ignored if pToken is NULL or if the token does not
75844 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
75845 ** then the EP_DblQuoted flag is set on the expression node.
75847 ** Special case: If op==TK_INTEGER and pToken points to a string that
75848 ** can be translated into a 32-bit integer, then the token is not
75849 ** stored in u.zToken. Instead, the integer values is written
75850 ** into u.iValue and the EP_IntValue flag is set. No extra storage
75851 ** is allocated to hold the integer text and the dequote flag is ignored.
75853 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
75854 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
75855 int op, /* Expression opcode */
75856 const Token *pToken, /* Token argument. Might be NULL */
75857 int dequote /* True to dequote */
75859 Expr *pNew;
75860 int nExtra = 0;
75861 int iValue = 0;
75863 if( pToken ){
75864 if( op!=TK_INTEGER || pToken->z==0
75865 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
75866 nExtra = pToken->n+1;
75867 assert( iValue>=0 );
75870 pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
75871 if( pNew ){
75872 pNew->op = (u8)op;
75873 pNew->iAgg = -1;
75874 if( pToken ){
75875 if( nExtra==0 ){
75876 pNew->flags |= EP_IntValue;
75877 pNew->u.iValue = iValue;
75878 }else{
75879 int c;
75880 pNew->u.zToken = (char*)&pNew[1];
75881 assert( pToken->z!=0 || pToken->n==0 );
75882 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
75883 pNew->u.zToken[pToken->n] = 0;
75884 if( dequote && nExtra>=3
75885 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
75886 sqlite3Dequote(pNew->u.zToken);
75887 if( c=='"' ) pNew->flags |= EP_DblQuoted;
75891 #if SQLITE_MAX_EXPR_DEPTH>0
75892 pNew->nHeight = 1;
75893 #endif
75895 return pNew;
75899 ** Allocate a new expression node from a zero-terminated token that has
75900 ** already been dequoted.
75902 SQLITE_PRIVATE Expr *sqlite3Expr(
75903 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
75904 int op, /* Expression opcode */
75905 const char *zToken /* Token argument. Might be NULL */
75907 Token x;
75908 x.z = zToken;
75909 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
75910 return sqlite3ExprAlloc(db, op, &x, 0);
75914 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
75916 ** If pRoot==NULL that means that a memory allocation error has occurred.
75917 ** In that case, delete the subtrees pLeft and pRight.
75919 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
75920 sqlite3 *db,
75921 Expr *pRoot,
75922 Expr *pLeft,
75923 Expr *pRight
75925 if( pRoot==0 ){
75926 assert( db->mallocFailed );
75927 sqlite3ExprDelete(db, pLeft);
75928 sqlite3ExprDelete(db, pRight);
75929 }else{
75930 if( pRight ){
75931 pRoot->pRight = pRight;
75932 pRoot->flags |= EP_Collate & pRight->flags;
75934 if( pLeft ){
75935 pRoot->pLeft = pLeft;
75936 pRoot->flags |= EP_Collate & pLeft->flags;
75938 exprSetHeight(pRoot);
75943 ** Allocate a Expr node which joins as many as two subtrees.
75945 ** One or both of the subtrees can be NULL. Return a pointer to the new
75946 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
75947 ** free the subtrees and return NULL.
75949 SQLITE_PRIVATE Expr *sqlite3PExpr(
75950 Parse *pParse, /* Parsing context */
75951 int op, /* Expression opcode */
75952 Expr *pLeft, /* Left operand */
75953 Expr *pRight, /* Right operand */
75954 const Token *pToken /* Argument token */
75956 Expr *p;
75957 if( op==TK_AND && pLeft && pRight ){
75958 /* Take advantage of short-circuit false optimization for AND */
75959 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
75960 }else{
75961 p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
75962 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
75964 if( p ) {
75965 sqlite3ExprCheckHeight(pParse, p->nHeight);
75967 return p;
75971 ** Return 1 if an expression must be FALSE in all cases and 0 if the
75972 ** expression might be true. This is an optimization. If is OK to
75973 ** return 0 here even if the expression really is always false (a
75974 ** false negative). But it is a bug to return 1 if the expression
75975 ** might be true in some rare circumstances (a false positive.)
75977 ** Note that if the expression is part of conditional for a
75978 ** LEFT JOIN, then we cannot determine at compile-time whether or not
75979 ** is it true or false, so always return 0.
75981 static int exprAlwaysFalse(Expr *p){
75982 int v = 0;
75983 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
75984 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
75985 return v==0;
75989 ** Join two expressions using an AND operator. If either expression is
75990 ** NULL, then just return the other expression.
75992 ** If one side or the other of the AND is known to be false, then instead
75993 ** of returning an AND expression, just return a constant expression with
75994 ** a value of false.
75996 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
75997 if( pLeft==0 ){
75998 return pRight;
75999 }else if( pRight==0 ){
76000 return pLeft;
76001 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
76002 sqlite3ExprDelete(db, pLeft);
76003 sqlite3ExprDelete(db, pRight);
76004 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
76005 }else{
76006 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
76007 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
76008 return pNew;
76013 ** Construct a new expression node for a function with multiple
76014 ** arguments.
76016 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
76017 Expr *pNew;
76018 sqlite3 *db = pParse->db;
76019 assert( pToken );
76020 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
76021 if( pNew==0 ){
76022 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
76023 return 0;
76025 pNew->x.pList = pList;
76026 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
76027 sqlite3ExprSetHeight(pParse, pNew);
76028 return pNew;
76032 ** Assign a variable number to an expression that encodes a wildcard
76033 ** in the original SQL statement.
76035 ** Wildcards consisting of a single "?" are assigned the next sequential
76036 ** variable number.
76038 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
76039 ** sure "nnn" is not too be to avoid a denial of service attack when
76040 ** the SQL statement comes from an external source.
76042 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
76043 ** as the previous instance of the same wildcard. Or if this is the first
76044 ** instance of the wildcard, the next sequenial variable number is
76045 ** assigned.
76047 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
76048 sqlite3 *db = pParse->db;
76049 const char *z;
76051 if( pExpr==0 ) return;
76052 assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
76053 z = pExpr->u.zToken;
76054 assert( z!=0 );
76055 assert( z[0]!=0 );
76056 if( z[1]==0 ){
76057 /* Wildcard of the form "?". Assign the next variable number */
76058 assert( z[0]=='?' );
76059 pExpr->iColumn = (ynVar)(++pParse->nVar);
76060 }else{
76061 ynVar x = 0;
76062 u32 n = sqlite3Strlen30(z);
76063 if( z[0]=='?' ){
76064 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
76065 ** use it as the variable number */
76066 i64 i;
76067 int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
76068 pExpr->iColumn = x = (ynVar)i;
76069 testcase( i==0 );
76070 testcase( i==1 );
76071 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
76072 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
76073 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
76074 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
76075 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
76076 x = 0;
76078 if( i>pParse->nVar ){
76079 pParse->nVar = (int)i;
76081 }else{
76082 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
76083 ** number as the prior appearance of the same name, or if the name
76084 ** has never appeared before, reuse the same variable number
76086 ynVar i;
76087 for(i=0; i<pParse->nzVar; i++){
76088 if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
76089 pExpr->iColumn = x = (ynVar)i+1;
76090 break;
76093 if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
76095 if( x>0 ){
76096 if( x>pParse->nzVar ){
76097 char **a;
76098 a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
76099 if( a==0 ) return; /* Error reported through db->mallocFailed */
76100 pParse->azVar = a;
76101 memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
76102 pParse->nzVar = x;
76104 if( z[0]!='?' || pParse->azVar[x-1]==0 ){
76105 sqlite3DbFree(db, pParse->azVar[x-1]);
76106 pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
76110 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
76111 sqlite3ErrorMsg(pParse, "too many SQL variables");
76116 ** Recursively delete an expression tree.
76118 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
76119 if( p==0 ) return;
76120 /* Sanity check: Assert that the IntValue is non-negative if it exists */
76121 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
76122 if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
76123 sqlite3ExprDelete(db, p->pLeft);
76124 sqlite3ExprDelete(db, p->pRight);
76125 if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
76126 sqlite3DbFree(db, p->u.zToken);
76128 if( ExprHasProperty(p, EP_xIsSelect) ){
76129 sqlite3SelectDelete(db, p->x.pSelect);
76130 }else{
76131 sqlite3ExprListDelete(db, p->x.pList);
76134 if( !ExprHasProperty(p, EP_Static) ){
76135 sqlite3DbFree(db, p);
76140 ** Return the number of bytes allocated for the expression structure
76141 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
76142 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
76144 static int exprStructSize(Expr *p){
76145 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
76146 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
76147 return EXPR_FULLSIZE;
76151 ** The dupedExpr*Size() routines each return the number of bytes required
76152 ** to store a copy of an expression or expression tree. They differ in
76153 ** how much of the tree is measured.
76155 ** dupedExprStructSize() Size of only the Expr structure
76156 ** dupedExprNodeSize() Size of Expr + space for token
76157 ** dupedExprSize() Expr + token + subtree components
76159 ***************************************************************************
76161 ** The dupedExprStructSize() function returns two values OR-ed together:
76162 ** (1) the space required for a copy of the Expr structure only and
76163 ** (2) the EP_xxx flags that indicate what the structure size should be.
76164 ** The return values is always one of:
76166 ** EXPR_FULLSIZE
76167 ** EXPR_REDUCEDSIZE | EP_Reduced
76168 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
76170 ** The size of the structure can be found by masking the return value
76171 ** of this routine with 0xfff. The flags can be found by masking the
76172 ** return value with EP_Reduced|EP_TokenOnly.
76174 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
76175 ** (unreduced) Expr objects as they or originally constructed by the parser.
76176 ** During expression analysis, extra information is computed and moved into
76177 ** later parts of teh Expr object and that extra information might get chopped
76178 ** off if the expression is reduced. Note also that it does not work to
76179 ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
76180 ** to reduce a pristine expression tree from the parser. The implementation
76181 ** of dupedExprStructSize() contain multiple assert() statements that attempt
76182 ** to enforce this constraint.
76184 static int dupedExprStructSize(Expr *p, int flags){
76185 int nSize;
76186 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
76187 if( 0==(flags&EXPRDUP_REDUCE) ){
76188 nSize = EXPR_FULLSIZE;
76189 }else{
76190 assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
76191 assert( !ExprHasProperty(p, EP_FromJoin) );
76192 assert( (p->flags2 & EP2_MallocedToken)==0 );
76193 assert( (p->flags2 & EP2_Irreducible)==0 );
76194 if( p->pLeft || p->pRight || p->x.pList ){
76195 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
76196 }else{
76197 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
76200 return nSize;
76204 ** This function returns the space in bytes required to store the copy
76205 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
76206 ** string is defined.)
76208 static int dupedExprNodeSize(Expr *p, int flags){
76209 int nByte = dupedExprStructSize(p, flags) & 0xfff;
76210 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
76211 nByte += sqlite3Strlen30(p->u.zToken)+1;
76213 return ROUND8(nByte);
76217 ** Return the number of bytes required to create a duplicate of the
76218 ** expression passed as the first argument. The second argument is a
76219 ** mask containing EXPRDUP_XXX flags.
76221 ** The value returned includes space to create a copy of the Expr struct
76222 ** itself and the buffer referred to by Expr.u.zToken, if any.
76224 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
76225 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
76226 ** and Expr.pRight variables (but not for any structures pointed to or
76227 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
76229 static int dupedExprSize(Expr *p, int flags){
76230 int nByte = 0;
76231 if( p ){
76232 nByte = dupedExprNodeSize(p, flags);
76233 if( flags&EXPRDUP_REDUCE ){
76234 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
76237 return nByte;
76241 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
76242 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
76243 ** to store the copy of expression p, the copies of p->u.zToken
76244 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
76245 ** if any. Before returning, *pzBuffer is set to the first byte passed the
76246 ** portion of the buffer copied into by this function.
76248 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
76249 Expr *pNew = 0; /* Value to return */
76250 if( p ){
76251 const int isReduced = (flags&EXPRDUP_REDUCE);
76252 u8 *zAlloc;
76253 u32 staticFlag = 0;
76255 assert( pzBuffer==0 || isReduced );
76257 /* Figure out where to write the new Expr structure. */
76258 if( pzBuffer ){
76259 zAlloc = *pzBuffer;
76260 staticFlag = EP_Static;
76261 }else{
76262 zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
76264 pNew = (Expr *)zAlloc;
76266 if( pNew ){
76267 /* Set nNewSize to the size allocated for the structure pointed to
76268 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
76269 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
76270 ** by the copy of the p->u.zToken string (if any).
76272 const unsigned nStructSize = dupedExprStructSize(p, flags);
76273 const int nNewSize = nStructSize & 0xfff;
76274 int nToken;
76275 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
76276 nToken = sqlite3Strlen30(p->u.zToken) + 1;
76277 }else{
76278 nToken = 0;
76280 if( isReduced ){
76281 assert( ExprHasProperty(p, EP_Reduced)==0 );
76282 memcpy(zAlloc, p, nNewSize);
76283 }else{
76284 int nSize = exprStructSize(p);
76285 memcpy(zAlloc, p, nSize);
76286 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
76289 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
76290 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
76291 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
76292 pNew->flags |= staticFlag;
76294 /* Copy the p->u.zToken string, if any. */
76295 if( nToken ){
76296 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
76297 memcpy(zToken, p->u.zToken, nToken);
76300 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
76301 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
76302 if( ExprHasProperty(p, EP_xIsSelect) ){
76303 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
76304 }else{
76305 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
76309 /* Fill in pNew->pLeft and pNew->pRight. */
76310 if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
76311 zAlloc += dupedExprNodeSize(p, flags);
76312 if( ExprHasProperty(pNew, EP_Reduced) ){
76313 pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
76314 pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
76316 if( pzBuffer ){
76317 *pzBuffer = zAlloc;
76319 }else{
76320 pNew->flags2 = 0;
76321 if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
76322 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
76323 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
76329 return pNew;
76333 ** The following group of routines make deep copies of expressions,
76334 ** expression lists, ID lists, and select statements. The copies can
76335 ** be deleted (by being passed to their respective ...Delete() routines)
76336 ** without effecting the originals.
76338 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
76339 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
76340 ** by subsequent calls to sqlite*ListAppend() routines.
76342 ** Any tables that the SrcList might point to are not duplicated.
76344 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
76345 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
76346 ** truncated version of the usual Expr structure that will be stored as
76347 ** part of the in-memory representation of the database schema.
76349 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
76350 return exprDup(db, p, flags, 0);
76352 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
76353 ExprList *pNew;
76354 struct ExprList_item *pItem, *pOldItem;
76355 int i;
76356 if( p==0 ) return 0;
76357 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
76358 if( pNew==0 ) return 0;
76359 pNew->iECursor = 0;
76360 pNew->nExpr = i = p->nExpr;
76361 if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
76362 pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
76363 if( pItem==0 ){
76364 sqlite3DbFree(db, pNew);
76365 return 0;
76367 pOldItem = p->a;
76368 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
76369 Expr *pOldExpr = pOldItem->pExpr;
76370 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
76371 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76372 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
76373 pItem->sortOrder = pOldItem->sortOrder;
76374 pItem->done = 0;
76375 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
76376 pItem->iOrderByCol = pOldItem->iOrderByCol;
76377 pItem->iAlias = pOldItem->iAlias;
76379 return pNew;
76383 ** If cursors, triggers, views and subqueries are all omitted from
76384 ** the build, then none of the following routines, except for
76385 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
76386 ** called with a NULL argument.
76388 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
76389 || !defined(SQLITE_OMIT_SUBQUERY)
76390 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
76391 SrcList *pNew;
76392 int i;
76393 int nByte;
76394 if( p==0 ) return 0;
76395 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
76396 pNew = sqlite3DbMallocRaw(db, nByte );
76397 if( pNew==0 ) return 0;
76398 pNew->nSrc = pNew->nAlloc = p->nSrc;
76399 for(i=0; i<p->nSrc; i++){
76400 struct SrcList_item *pNewItem = &pNew->a[i];
76401 struct SrcList_item *pOldItem = &p->a[i];
76402 Table *pTab;
76403 pNewItem->pSchema = pOldItem->pSchema;
76404 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
76405 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76406 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
76407 pNewItem->jointype = pOldItem->jointype;
76408 pNewItem->iCursor = pOldItem->iCursor;
76409 pNewItem->addrFillSub = pOldItem->addrFillSub;
76410 pNewItem->regReturn = pOldItem->regReturn;
76411 pNewItem->isCorrelated = pOldItem->isCorrelated;
76412 pNewItem->viaCoroutine = pOldItem->viaCoroutine;
76413 pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
76414 pNewItem->notIndexed = pOldItem->notIndexed;
76415 pNewItem->pIndex = pOldItem->pIndex;
76416 pTab = pNewItem->pTab = pOldItem->pTab;
76417 if( pTab ){
76418 pTab->nRef++;
76420 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
76421 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
76422 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
76423 pNewItem->colUsed = pOldItem->colUsed;
76425 return pNew;
76427 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
76428 IdList *pNew;
76429 int i;
76430 if( p==0 ) return 0;
76431 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
76432 if( pNew==0 ) return 0;
76433 pNew->nId = p->nId;
76434 pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
76435 if( pNew->a==0 ){
76436 sqlite3DbFree(db, pNew);
76437 return 0;
76439 /* Note that because the size of the allocation for p->a[] is not
76440 ** necessarily a power of two, sqlite3IdListAppend() may not be called
76441 ** on the duplicate created by this function. */
76442 for(i=0; i<p->nId; i++){
76443 struct IdList_item *pNewItem = &pNew->a[i];
76444 struct IdList_item *pOldItem = &p->a[i];
76445 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76446 pNewItem->idx = pOldItem->idx;
76448 return pNew;
76450 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
76451 Select *pNew, *pPrior;
76452 if( p==0 ) return 0;
76453 pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
76454 if( pNew==0 ) return 0;
76455 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
76456 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
76457 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
76458 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
76459 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
76460 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
76461 pNew->op = p->op;
76462 pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
76463 if( pPrior ) pPrior->pNext = pNew;
76464 pNew->pNext = 0;
76465 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
76466 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
76467 pNew->iLimit = 0;
76468 pNew->iOffset = 0;
76469 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
76470 pNew->pRightmost = 0;
76471 pNew->addrOpenEphm[0] = -1;
76472 pNew->addrOpenEphm[1] = -1;
76473 pNew->addrOpenEphm[2] = -1;
76474 return pNew;
76476 #else
76477 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
76478 assert( p==0 );
76479 return 0;
76481 #endif
76485 ** Add a new element to the end of an expression list. If pList is
76486 ** initially NULL, then create a new expression list.
76488 ** If a memory allocation error occurs, the entire list is freed and
76489 ** NULL is returned. If non-NULL is returned, then it is guaranteed
76490 ** that the new entry was successfully appended.
76492 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
76493 Parse *pParse, /* Parsing context */
76494 ExprList *pList, /* List to which to append. Might be NULL */
76495 Expr *pExpr /* Expression to be appended. Might be NULL */
76497 sqlite3 *db = pParse->db;
76498 if( pList==0 ){
76499 pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
76500 if( pList==0 ){
76501 goto no_mem;
76503 pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
76504 if( pList->a==0 ) goto no_mem;
76505 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
76506 struct ExprList_item *a;
76507 assert( pList->nExpr>0 );
76508 a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
76509 if( a==0 ){
76510 goto no_mem;
76512 pList->a = a;
76514 assert( pList->a!=0 );
76515 if( 1 ){
76516 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
76517 memset(pItem, 0, sizeof(*pItem));
76518 pItem->pExpr = pExpr;
76520 return pList;
76522 no_mem:
76523 /* Avoid leaking memory if malloc has failed. */
76524 sqlite3ExprDelete(db, pExpr);
76525 sqlite3ExprListDelete(db, pList);
76526 return 0;
76530 ** Set the ExprList.a[].zName element of the most recently added item
76531 ** on the expression list.
76533 ** pList might be NULL following an OOM error. But pName should never be
76534 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
76535 ** is set.
76537 SQLITE_PRIVATE void sqlite3ExprListSetName(
76538 Parse *pParse, /* Parsing context */
76539 ExprList *pList, /* List to which to add the span. */
76540 Token *pName, /* Name to be added */
76541 int dequote /* True to cause the name to be dequoted */
76543 assert( pList!=0 || pParse->db->mallocFailed!=0 );
76544 if( pList ){
76545 struct ExprList_item *pItem;
76546 assert( pList->nExpr>0 );
76547 pItem = &pList->a[pList->nExpr-1];
76548 assert( pItem->zName==0 );
76549 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
76550 if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
76555 ** Set the ExprList.a[].zSpan element of the most recently added item
76556 ** on the expression list.
76558 ** pList might be NULL following an OOM error. But pSpan should never be
76559 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
76560 ** is set.
76562 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
76563 Parse *pParse, /* Parsing context */
76564 ExprList *pList, /* List to which to add the span. */
76565 ExprSpan *pSpan /* The span to be added */
76567 sqlite3 *db = pParse->db;
76568 assert( pList!=0 || db->mallocFailed!=0 );
76569 if( pList ){
76570 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
76571 assert( pList->nExpr>0 );
76572 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
76573 sqlite3DbFree(db, pItem->zSpan);
76574 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
76575 (int)(pSpan->zEnd - pSpan->zStart));
76580 ** If the expression list pEList contains more than iLimit elements,
76581 ** leave an error message in pParse.
76583 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
76584 Parse *pParse,
76585 ExprList *pEList,
76586 const char *zObject
76588 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
76589 testcase( pEList && pEList->nExpr==mx );
76590 testcase( pEList && pEList->nExpr==mx+1 );
76591 if( pEList && pEList->nExpr>mx ){
76592 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
76597 ** Delete an entire expression list.
76599 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
76600 int i;
76601 struct ExprList_item *pItem;
76602 if( pList==0 ) return;
76603 assert( pList->a!=0 || pList->nExpr==0 );
76604 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
76605 sqlite3ExprDelete(db, pItem->pExpr);
76606 sqlite3DbFree(db, pItem->zName);
76607 sqlite3DbFree(db, pItem->zSpan);
76609 sqlite3DbFree(db, pList->a);
76610 sqlite3DbFree(db, pList);
76614 ** These routines are Walker callbacks. Walker.u.pi is a pointer
76615 ** to an integer. These routines are checking an expression to see
76616 ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
76617 ** not constant.
76619 ** These callback routines are used to implement the following:
76621 ** sqlite3ExprIsConstant()
76622 ** sqlite3ExprIsConstantNotJoin()
76623 ** sqlite3ExprIsConstantOrFunction()
76626 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
76628 /* If pWalker->u.i is 3 then any term of the expression that comes from
76629 ** the ON or USING clauses of a join disqualifies the expression
76630 ** from being considered constant. */
76631 if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
76632 pWalker->u.i = 0;
76633 return WRC_Abort;
76636 switch( pExpr->op ){
76637 /* Consider functions to be constant if all their arguments are constant
76638 ** and pWalker->u.i==2 */
76639 case TK_FUNCTION:
76640 if( pWalker->u.i==2 ) return 0;
76641 /* Fall through */
76642 case TK_ID:
76643 case TK_COLUMN:
76644 case TK_AGG_FUNCTION:
76645 case TK_AGG_COLUMN:
76646 testcase( pExpr->op==TK_ID );
76647 testcase( pExpr->op==TK_COLUMN );
76648 testcase( pExpr->op==TK_AGG_FUNCTION );
76649 testcase( pExpr->op==TK_AGG_COLUMN );
76650 pWalker->u.i = 0;
76651 return WRC_Abort;
76652 default:
76653 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
76654 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
76655 return WRC_Continue;
76658 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
76659 UNUSED_PARAMETER(NotUsed);
76660 pWalker->u.i = 0;
76661 return WRC_Abort;
76663 static int exprIsConst(Expr *p, int initFlag){
76664 Walker w;
76665 memset(&w, 0, sizeof(w));
76666 w.u.i = initFlag;
76667 w.xExprCallback = exprNodeIsConstant;
76668 w.xSelectCallback = selectNodeIsConstant;
76669 sqlite3WalkExpr(&w, p);
76670 return w.u.i;
76674 ** Walk an expression tree. Return 1 if the expression is constant
76675 ** and 0 if it involves variables or function calls.
76677 ** For the purposes of this function, a double-quoted string (ex: "abc")
76678 ** is considered a variable but a single-quoted string (ex: 'abc') is
76679 ** a constant.
76681 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
76682 return exprIsConst(p, 1);
76686 ** Walk an expression tree. Return 1 if the expression is constant
76687 ** that does no originate from the ON or USING clauses of a join.
76688 ** Return 0 if it involves variables or function calls or terms from
76689 ** an ON or USING clause.
76691 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
76692 return exprIsConst(p, 3);
76696 ** Walk an expression tree. Return 1 if the expression is constant
76697 ** or a function call with constant arguments. Return and 0 if there
76698 ** are any variables.
76700 ** For the purposes of this function, a double-quoted string (ex: "abc")
76701 ** is considered a variable but a single-quoted string (ex: 'abc') is
76702 ** a constant.
76704 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
76705 return exprIsConst(p, 2);
76709 ** If the expression p codes a constant integer that is small enough
76710 ** to fit in a 32-bit integer, return 1 and put the value of the integer
76711 ** in *pValue. If the expression is not an integer or if it is too big
76712 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
76714 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
76715 int rc = 0;
76717 /* If an expression is an integer literal that fits in a signed 32-bit
76718 ** integer, then the EP_IntValue flag will have already been set */
76719 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
76720 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
76722 if( p->flags & EP_IntValue ){
76723 *pValue = p->u.iValue;
76724 return 1;
76726 switch( p->op ){
76727 case TK_UPLUS: {
76728 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
76729 break;
76731 case TK_UMINUS: {
76732 int v;
76733 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
76734 assert( v!=-2147483648 );
76735 *pValue = -v;
76736 rc = 1;
76738 break;
76740 default: break;
76742 return rc;
76746 ** Return FALSE if there is no chance that the expression can be NULL.
76748 ** If the expression might be NULL or if the expression is too complex
76749 ** to tell return TRUE.
76751 ** This routine is used as an optimization, to skip OP_IsNull opcodes
76752 ** when we know that a value cannot be NULL. Hence, a false positive
76753 ** (returning TRUE when in fact the expression can never be NULL) might
76754 ** be a small performance hit but is otherwise harmless. On the other
76755 ** hand, a false negative (returning FALSE when the result could be NULL)
76756 ** will likely result in an incorrect answer. So when in doubt, return
76757 ** TRUE.
76759 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
76760 u8 op;
76761 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
76762 op = p->op;
76763 if( op==TK_REGISTER ) op = p->op2;
76764 switch( op ){
76765 case TK_INTEGER:
76766 case TK_STRING:
76767 case TK_FLOAT:
76768 case TK_BLOB:
76769 return 0;
76770 default:
76771 return 1;
76776 ** Generate an OP_IsNull instruction that tests register iReg and jumps
76777 ** to location iDest if the value in iReg is NULL. The value in iReg
76778 ** was computed by pExpr. If we can look at pExpr at compile-time and
76779 ** determine that it can never generate a NULL, then the OP_IsNull operation
76780 ** can be omitted.
76782 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
76783 Vdbe *v, /* The VDBE under construction */
76784 const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
76785 int iReg, /* Test the value in this register for NULL */
76786 int iDest /* Jump here if the value is null */
76788 if( sqlite3ExprCanBeNull(pExpr) ){
76789 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
76794 ** Return TRUE if the given expression is a constant which would be
76795 ** unchanged by OP_Affinity with the affinity given in the second
76796 ** argument.
76798 ** This routine is used to determine if the OP_Affinity operation
76799 ** can be omitted. When in doubt return FALSE. A false negative
76800 ** is harmless. A false positive, however, can result in the wrong
76801 ** answer.
76803 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
76804 u8 op;
76805 if( aff==SQLITE_AFF_NONE ) return 1;
76806 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
76807 op = p->op;
76808 if( op==TK_REGISTER ) op = p->op2;
76809 switch( op ){
76810 case TK_INTEGER: {
76811 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
76813 case TK_FLOAT: {
76814 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
76816 case TK_STRING: {
76817 return aff==SQLITE_AFF_TEXT;
76819 case TK_BLOB: {
76820 return 1;
76822 case TK_COLUMN: {
76823 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
76824 return p->iColumn<0
76825 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
76827 default: {
76828 return 0;
76834 ** Return TRUE if the given string is a row-id column name.
76836 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
76837 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
76838 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
76839 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
76840 return 0;
76844 ** Return true if we are able to the IN operator optimization on a
76845 ** query of the form
76847 ** x IN (SELECT ...)
76849 ** Where the SELECT... clause is as specified by the parameter to this
76850 ** routine.
76852 ** The Select object passed in has already been preprocessed and no
76853 ** errors have been found.
76855 #ifndef SQLITE_OMIT_SUBQUERY
76856 static int isCandidateForInOpt(Select *p){
76857 SrcList *pSrc;
76858 ExprList *pEList;
76859 Table *pTab;
76860 if( p==0 ) return 0; /* right-hand side of IN is SELECT */
76861 if( p->pPrior ) return 0; /* Not a compound SELECT */
76862 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
76863 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
76864 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
76865 return 0; /* No DISTINCT keyword and no aggregate functions */
76867 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
76868 if( p->pLimit ) return 0; /* Has no LIMIT clause */
76869 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
76870 if( p->pWhere ) return 0; /* Has no WHERE clause */
76871 pSrc = p->pSrc;
76872 assert( pSrc!=0 );
76873 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
76874 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
76875 pTab = pSrc->a[0].pTab;
76876 if( NEVER(pTab==0) ) return 0;
76877 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
76878 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
76879 pEList = p->pEList;
76880 if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
76881 if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
76882 return 1;
76884 #endif /* SQLITE_OMIT_SUBQUERY */
76887 ** Code an OP_Once instruction and allocate space for its flag. Return the
76888 ** address of the new instruction.
76890 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
76891 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
76892 return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
76896 ** This function is used by the implementation of the IN (...) operator.
76897 ** The pX parameter is the expression on the RHS of the IN operator, which
76898 ** might be either a list of expressions or a subquery.
76900 ** The job of this routine is to find or create a b-tree object that can
76901 ** be used either to test for membership in the RHS set or to iterate through
76902 ** all members of the RHS set, skipping duplicates.
76904 ** A cursor is opened on the b-tree object that the RHS of the IN operator
76905 ** and pX->iTable is set to the index of that cursor.
76907 ** The returned value of this function indicates the b-tree type, as follows:
76909 ** IN_INDEX_ROWID - The cursor was opened on a database table.
76910 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
76911 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
76912 ** IN_INDEX_EPH - The cursor was opened on a specially created and
76913 ** populated epheremal table.
76915 ** An existing b-tree might be used if the RHS expression pX is a simple
76916 ** subquery such as:
76918 ** SELECT <column> FROM <table>
76920 ** If the RHS of the IN operator is a list or a more complex subquery, then
76921 ** an ephemeral table might need to be generated from the RHS and then
76922 ** pX->iTable made to point to the ephermeral table instead of an
76923 ** existing table.
76925 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
76926 ** through the set members, skipping any duplicates. In this case an
76927 ** epheremal table must be used unless the selected <column> is guaranteed
76928 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
76929 ** has a UNIQUE constraint or UNIQUE index.
76931 ** If the prNotFound parameter is not 0, then the b-tree will be used
76932 ** for fast set membership tests. In this case an epheremal table must
76933 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
76934 ** be found with <column> as its left-most column.
76936 ** When the b-tree is being used for membership tests, the calling function
76937 ** needs to know whether or not the structure contains an SQL NULL
76938 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
76939 ** If there is any chance that the (...) might contain a NULL value at
76940 ** runtime, then a register is allocated and the register number written
76941 ** to *prNotFound. If there is no chance that the (...) contains a
76942 ** NULL value, then *prNotFound is left unchanged.
76944 ** If a register is allocated and its location stored in *prNotFound, then
76945 ** its initial value is NULL. If the (...) does not remain constant
76946 ** for the duration of the query (i.e. the SELECT within the (...)
76947 ** is a correlated subquery) then the value of the allocated register is
76948 ** reset to NULL each time the subquery is rerun. This allows the
76949 ** caller to use vdbe code equivalent to the following:
76951 ** if( register==NULL ){
76952 ** has_null = <test if data structure contains null>
76953 ** register = 1
76954 ** }
76956 ** in order to avoid running the <test if data structure contains null>
76957 ** test more often than is necessary.
76959 #ifndef SQLITE_OMIT_SUBQUERY
76960 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
76961 Select *p; /* SELECT to the right of IN operator */
76962 int eType = 0; /* Type of RHS table. IN_INDEX_* */
76963 int iTab = pParse->nTab++; /* Cursor of the RHS table */
76964 int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
76965 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
76967 assert( pX->op==TK_IN );
76969 /* Check to see if an existing table or index can be used to
76970 ** satisfy the query. This is preferable to generating a new
76971 ** ephemeral table.
76973 p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
76974 if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
76975 sqlite3 *db = pParse->db; /* Database connection */
76976 Table *pTab; /* Table <table>. */
76977 Expr *pExpr; /* Expression <column> */
76978 int iCol; /* Index of column <column> */
76979 int iDb; /* Database idx for pTab */
76981 assert( p ); /* Because of isCandidateForInOpt(p) */
76982 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
76983 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
76984 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
76985 pTab = p->pSrc->a[0].pTab;
76986 pExpr = p->pEList->a[0].pExpr;
76987 iCol = pExpr->iColumn;
76989 /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
76990 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76991 sqlite3CodeVerifySchema(pParse, iDb);
76992 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
76994 /* This function is only called from two places. In both cases the vdbe
76995 ** has already been allocated. So assume sqlite3GetVdbe() is always
76996 ** successful here.
76998 assert(v);
76999 if( iCol<0 ){
77000 int iAddr;
77002 iAddr = sqlite3CodeOnce(pParse);
77004 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
77005 eType = IN_INDEX_ROWID;
77007 sqlite3VdbeJumpHere(v, iAddr);
77008 }else{
77009 Index *pIdx; /* Iterator variable */
77011 /* The collation sequence used by the comparison. If an index is to
77012 ** be used in place of a temp-table, it must be ordered according
77013 ** to this collation sequence. */
77014 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
77016 /* Check that the affinity that will be used to perform the
77017 ** comparison is the same as the affinity of the column. If
77018 ** it is not, it is not possible to use any index.
77020 int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
77022 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
77023 if( (pIdx->aiColumn[0]==iCol)
77024 && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
77025 && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
77027 int iAddr;
77028 char *pKey;
77030 pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
77031 iAddr = sqlite3CodeOnce(pParse);
77033 sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
77034 pKey,P4_KEYINFO_HANDOFF);
77035 VdbeComment((v, "%s", pIdx->zName));
77036 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
77037 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
77039 sqlite3VdbeJumpHere(v, iAddr);
77040 if( prNotFound && !pTab->aCol[iCol].notNull ){
77041 *prNotFound = ++pParse->nMem;
77042 sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
77049 if( eType==0 ){
77050 /* Could not found an existing table or index to use as the RHS b-tree.
77051 ** We will have to generate an ephemeral table to do the job.
77053 u32 savedNQueryLoop = pParse->nQueryLoop;
77054 int rMayHaveNull = 0;
77055 eType = IN_INDEX_EPH;
77056 if( prNotFound ){
77057 *prNotFound = rMayHaveNull = ++pParse->nMem;
77058 sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
77059 }else{
77060 testcase( pParse->nQueryLoop>0 );
77061 pParse->nQueryLoop = 0;
77062 if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
77063 eType = IN_INDEX_ROWID;
77066 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
77067 pParse->nQueryLoop = savedNQueryLoop;
77068 }else{
77069 pX->iTable = iTab;
77071 return eType;
77073 #endif
77076 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
77077 ** or IN operators. Examples:
77079 ** (SELECT a FROM b) -- subquery
77080 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
77081 ** x IN (4,5,11) -- IN operator with list on right-hand side
77082 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
77084 ** The pExpr parameter describes the expression that contains the IN
77085 ** operator or subquery.
77087 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
77088 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
77089 ** to some integer key column of a table B-Tree. In this case, use an
77090 ** intkey B-Tree to store the set of IN(...) values instead of the usual
77091 ** (slower) variable length keys B-Tree.
77093 ** If rMayHaveNull is non-zero, that means that the operation is an IN
77094 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
77095 ** Furthermore, the IN is in a WHERE clause and that we really want
77096 ** to iterate over the RHS of the IN operator in order to quickly locate
77097 ** all corresponding LHS elements. All this routine does is initialize
77098 ** the register given by rMayHaveNull to NULL. Calling routines will take
77099 ** care of changing this register value to non-NULL if the RHS is NULL-free.
77101 ** If rMayHaveNull is zero, that means that the subquery is being used
77102 ** for membership testing only. There is no need to initialize any
77103 ** registers to indicate the presence or absence of NULLs on the RHS.
77105 ** For a SELECT or EXISTS operator, return the register that holds the
77106 ** result. For IN operators or if an error occurs, the return value is 0.
77108 #ifndef SQLITE_OMIT_SUBQUERY
77109 SQLITE_PRIVATE int sqlite3CodeSubselect(
77110 Parse *pParse, /* Parsing context */
77111 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
77112 int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
77113 int isRowid /* If true, LHS of IN operator is a rowid */
77115 int testAddr = -1; /* One-time test address */
77116 int rReg = 0; /* Register storing resulting */
77117 Vdbe *v = sqlite3GetVdbe(pParse);
77118 if( NEVER(v==0) ) return 0;
77119 sqlite3ExprCachePush(pParse);
77121 /* This code must be run in its entirety every time it is encountered
77122 ** if any of the following is true:
77124 ** * The right-hand side is a correlated subquery
77125 ** * The right-hand side is an expression list containing variables
77126 ** * We are inside a trigger
77128 ** If all of the above are false, then we can run this code just once
77129 ** save the results, and reuse the same result on subsequent invocations.
77131 if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
77132 testAddr = sqlite3CodeOnce(pParse);
77135 #ifndef SQLITE_OMIT_EXPLAIN
77136 if( pParse->explain==2 ){
77137 char *zMsg = sqlite3MPrintf(
77138 pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
77139 pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
77141 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
77143 #endif
77145 switch( pExpr->op ){
77146 case TK_IN: {
77147 char affinity; /* Affinity of the LHS of the IN */
77148 int addr; /* Address of OP_OpenEphemeral instruction */
77149 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
77150 KeyInfo *pKeyInfo = 0; /* Key information */
77152 if( rMayHaveNull ){
77153 sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
77156 affinity = sqlite3ExprAffinity(pLeft);
77158 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
77159 ** expression it is handled the same way. An ephemeral table is
77160 ** filled with single-field index keys representing the results
77161 ** from the SELECT or the <exprlist>.
77163 ** If the 'x' expression is a column value, or the SELECT...
77164 ** statement returns a column value, then the affinity of that
77165 ** column is used to build the index keys. If both 'x' and the
77166 ** SELECT... statement are columns, then numeric affinity is used
77167 ** if either column has NUMERIC or INTEGER affinity. If neither
77168 ** 'x' nor the SELECT... statement are columns, then numeric affinity
77169 ** is used.
77171 pExpr->iTable = pParse->nTab++;
77172 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
77173 if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
77174 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1);
77176 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
77177 /* Case 1: expr IN (SELECT ...)
77179 ** Generate code to write the results of the select into the temporary
77180 ** table allocated and opened above.
77182 SelectDest dest;
77183 ExprList *pEList;
77185 assert( !isRowid );
77186 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
77187 dest.affSdst = (u8)affinity;
77188 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
77189 pExpr->x.pSelect->iLimit = 0;
77190 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
77191 if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
77192 sqlite3DbFree(pParse->db, pKeyInfo);
77193 return 0;
77195 pEList = pExpr->x.pSelect->pEList;
77196 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
77197 assert( pEList!=0 );
77198 assert( pEList->nExpr>0 );
77199 pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
77200 pEList->a[0].pExpr);
77201 }else if( ALWAYS(pExpr->x.pList!=0) ){
77202 /* Case 2: expr IN (exprlist)
77204 ** For each expression, build an index key from the evaluation and
77205 ** store it in the temporary table. If <expr> is a column, then use
77206 ** that columns affinity when building index keys. If <expr> is not
77207 ** a column, use numeric affinity.
77209 int i;
77210 ExprList *pList = pExpr->x.pList;
77211 struct ExprList_item *pItem;
77212 int r1, r2, r3;
77214 if( !affinity ){
77215 affinity = SQLITE_AFF_NONE;
77217 if( pKeyInfo ){
77218 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
77221 /* Loop through each expression in <exprlist>. */
77222 r1 = sqlite3GetTempReg(pParse);
77223 r2 = sqlite3GetTempReg(pParse);
77224 sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
77225 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
77226 Expr *pE2 = pItem->pExpr;
77227 int iValToIns;
77229 /* If the expression is not constant then we will need to
77230 ** disable the test that was generated above that makes sure
77231 ** this code only executes once. Because for a non-constant
77232 ** expression we need to rerun this code each time.
77234 if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
77235 sqlite3VdbeChangeToNoop(v, testAddr);
77236 testAddr = -1;
77239 /* Evaluate the expression and insert it into the temp table */
77240 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
77241 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
77242 }else{
77243 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
77244 if( isRowid ){
77245 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
77246 sqlite3VdbeCurrentAddr(v)+2);
77247 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
77248 }else{
77249 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
77250 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
77251 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
77255 sqlite3ReleaseTempReg(pParse, r1);
77256 sqlite3ReleaseTempReg(pParse, r2);
77258 if( pKeyInfo ){
77259 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF);
77261 break;
77264 case TK_EXISTS:
77265 case TK_SELECT:
77266 default: {
77267 /* If this has to be a scalar SELECT. Generate code to put the
77268 ** value of this select in a memory cell and record the number
77269 ** of the memory cell in iColumn. If this is an EXISTS, write
77270 ** an integer 0 (not exists) or 1 (exists) into a memory cell
77271 ** and record that memory cell in iColumn.
77273 Select *pSel; /* SELECT statement to encode */
77274 SelectDest dest; /* How to deal with SELECt result */
77276 testcase( pExpr->op==TK_EXISTS );
77277 testcase( pExpr->op==TK_SELECT );
77278 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
77280 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
77281 pSel = pExpr->x.pSelect;
77282 sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
77283 if( pExpr->op==TK_SELECT ){
77284 dest.eDest = SRT_Mem;
77285 sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
77286 VdbeComment((v, "Init subquery result"));
77287 }else{
77288 dest.eDest = SRT_Exists;
77289 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
77290 VdbeComment((v, "Init EXISTS result"));
77292 sqlite3ExprDelete(pParse->db, pSel->pLimit);
77293 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
77294 &sqlite3IntTokens[1]);
77295 pSel->iLimit = 0;
77296 if( sqlite3Select(pParse, pSel, &dest) ){
77297 return 0;
77299 rReg = dest.iSDParm;
77300 ExprSetIrreducible(pExpr);
77301 break;
77305 if( testAddr>=0 ){
77306 sqlite3VdbeJumpHere(v, testAddr);
77308 sqlite3ExprCachePop(pParse, 1);
77310 return rReg;
77312 #endif /* SQLITE_OMIT_SUBQUERY */
77314 #ifndef SQLITE_OMIT_SUBQUERY
77316 ** Generate code for an IN expression.
77318 ** x IN (SELECT ...)
77319 ** x IN (value, value, ...)
77321 ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
77322 ** is an array of zero or more values. The expression is true if the LHS is
77323 ** contained within the RHS. The value of the expression is unknown (NULL)
77324 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
77325 ** RHS contains one or more NULL values.
77327 ** This routine generates code will jump to destIfFalse if the LHS is not
77328 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
77329 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
77330 ** within the RHS then fall through.
77332 static void sqlite3ExprCodeIN(
77333 Parse *pParse, /* Parsing and code generating context */
77334 Expr *pExpr, /* The IN expression */
77335 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
77336 int destIfNull /* Jump here if the results are unknown due to NULLs */
77338 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
77339 char affinity; /* Comparison affinity to use */
77340 int eType; /* Type of the RHS */
77341 int r1; /* Temporary use register */
77342 Vdbe *v; /* Statement under construction */
77344 /* Compute the RHS. After this step, the table with cursor
77345 ** pExpr->iTable will contains the values that make up the RHS.
77347 v = pParse->pVdbe;
77348 assert( v!=0 ); /* OOM detected prior to this routine */
77349 VdbeNoopComment((v, "begin IN expr"));
77350 eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
77352 /* Figure out the affinity to use to create a key from the results
77353 ** of the expression. affinityStr stores a static string suitable for
77354 ** P4 of OP_MakeRecord.
77356 affinity = comparisonAffinity(pExpr);
77358 /* Code the LHS, the <expr> from "<expr> IN (...)".
77360 sqlite3ExprCachePush(pParse);
77361 r1 = sqlite3GetTempReg(pParse);
77362 sqlite3ExprCode(pParse, pExpr->pLeft, r1);
77364 /* If the LHS is NULL, then the result is either false or NULL depending
77365 ** on whether the RHS is empty or not, respectively.
77367 if( destIfNull==destIfFalse ){
77368 /* Shortcut for the common case where the false and NULL outcomes are
77369 ** the same. */
77370 sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
77371 }else{
77372 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
77373 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
77374 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
77375 sqlite3VdbeJumpHere(v, addr1);
77378 if( eType==IN_INDEX_ROWID ){
77379 /* In this case, the RHS is the ROWID of table b-tree
77381 sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
77382 sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
77383 }else{
77384 /* In this case, the RHS is an index b-tree.
77386 sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
77388 /* If the set membership test fails, then the result of the
77389 ** "x IN (...)" expression must be either 0 or NULL. If the set
77390 ** contains no NULL values, then the result is 0. If the set
77391 ** contains one or more NULL values, then the result of the
77392 ** expression is also NULL.
77394 if( rRhsHasNull==0 || destIfFalse==destIfNull ){
77395 /* This branch runs if it is known at compile time that the RHS
77396 ** cannot contain NULL values. This happens as the result
77397 ** of a "NOT NULL" constraint in the database schema.
77399 ** Also run this branch if NULL is equivalent to FALSE
77400 ** for this particular IN operator.
77402 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
77404 }else{
77405 /* In this branch, the RHS of the IN might contain a NULL and
77406 ** the presence of a NULL on the RHS makes a difference in the
77407 ** outcome.
77409 int j1, j2, j3;
77411 /* First check to see if the LHS is contained in the RHS. If so,
77412 ** then the presence of NULLs in the RHS does not matter, so jump
77413 ** over all of the code that follows.
77415 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
77417 /* Here we begin generating code that runs if the LHS is not
77418 ** contained within the RHS. Generate additional code that
77419 ** tests the RHS for NULLs. If the RHS contains a NULL then
77420 ** jump to destIfNull. If there are no NULLs in the RHS then
77421 ** jump to destIfFalse.
77423 j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
77424 j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
77425 sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
77426 sqlite3VdbeJumpHere(v, j3);
77427 sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
77428 sqlite3VdbeJumpHere(v, j2);
77430 /* Jump to the appropriate target depending on whether or not
77431 ** the RHS contains a NULL
77433 sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
77434 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
77436 /* The OP_Found at the top of this branch jumps here when true,
77437 ** causing the overall IN expression evaluation to fall through.
77439 sqlite3VdbeJumpHere(v, j1);
77442 sqlite3ReleaseTempReg(pParse, r1);
77443 sqlite3ExprCachePop(pParse, 1);
77444 VdbeComment((v, "end IN expr"));
77446 #endif /* SQLITE_OMIT_SUBQUERY */
77449 ** Duplicate an 8-byte value
77451 static char *dup8bytes(Vdbe *v, const char *in){
77452 char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
77453 if( out ){
77454 memcpy(out, in, 8);
77456 return out;
77459 #ifndef SQLITE_OMIT_FLOATING_POINT
77461 ** Generate an instruction that will put the floating point
77462 ** value described by z[0..n-1] into register iMem.
77464 ** The z[] string will probably not be zero-terminated. But the
77465 ** z[n] character is guaranteed to be something that does not look
77466 ** like the continuation of the number.
77468 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
77469 if( ALWAYS(z!=0) ){
77470 double value;
77471 char *zV;
77472 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
77473 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
77474 if( negateFlag ) value = -value;
77475 zV = dup8bytes(v, (char*)&value);
77476 sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
77479 #endif
77483 ** Generate an instruction that will put the integer describe by
77484 ** text z[0..n-1] into register iMem.
77486 ** Expr.u.zToken is always UTF8 and zero-terminated.
77488 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
77489 Vdbe *v = pParse->pVdbe;
77490 if( pExpr->flags & EP_IntValue ){
77491 int i = pExpr->u.iValue;
77492 assert( i>=0 );
77493 if( negFlag ) i = -i;
77494 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
77495 }else{
77496 int c;
77497 i64 value;
77498 const char *z = pExpr->u.zToken;
77499 assert( z!=0 );
77500 c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
77501 if( c==0 || (c==2 && negFlag) ){
77502 char *zV;
77503 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
77504 zV = dup8bytes(v, (char*)&value);
77505 sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
77506 }else{
77507 #ifdef SQLITE_OMIT_FLOATING_POINT
77508 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
77509 #else
77510 codeReal(v, z, negFlag, iMem);
77511 #endif
77517 ** Clear a cache entry.
77519 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
77520 if( p->tempReg ){
77521 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
77522 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
77524 p->tempReg = 0;
77530 ** Record in the column cache that a particular column from a
77531 ** particular table is stored in a particular register.
77533 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
77534 int i;
77535 int minLru;
77536 int idxLru;
77537 struct yColCache *p;
77539 assert( iReg>0 ); /* Register numbers are always positive */
77540 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
77542 /* The SQLITE_ColumnCache flag disables the column cache. This is used
77543 ** for testing only - to verify that SQLite always gets the same answer
77544 ** with and without the column cache.
77546 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
77548 /* First replace any existing entry.
77550 ** Actually, the way the column cache is currently used, we are guaranteed
77551 ** that the object will never already be in cache. Verify this guarantee.
77553 #ifndef NDEBUG
77554 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77555 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
77557 #endif
77559 /* Find an empty slot and replace it */
77560 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77561 if( p->iReg==0 ){
77562 p->iLevel = pParse->iCacheLevel;
77563 p->iTable = iTab;
77564 p->iColumn = iCol;
77565 p->iReg = iReg;
77566 p->tempReg = 0;
77567 p->lru = pParse->iCacheCnt++;
77568 return;
77572 /* Replace the last recently used */
77573 minLru = 0x7fffffff;
77574 idxLru = -1;
77575 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77576 if( p->lru<minLru ){
77577 idxLru = i;
77578 minLru = p->lru;
77581 if( ALWAYS(idxLru>=0) ){
77582 p = &pParse->aColCache[idxLru];
77583 p->iLevel = pParse->iCacheLevel;
77584 p->iTable = iTab;
77585 p->iColumn = iCol;
77586 p->iReg = iReg;
77587 p->tempReg = 0;
77588 p->lru = pParse->iCacheCnt++;
77589 return;
77594 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
77595 ** Purge the range of registers from the column cache.
77597 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
77598 int i;
77599 int iLast = iReg + nReg - 1;
77600 struct yColCache *p;
77601 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77602 int r = p->iReg;
77603 if( r>=iReg && r<=iLast ){
77604 cacheEntryClear(pParse, p);
77605 p->iReg = 0;
77611 ** Remember the current column cache context. Any new entries added
77612 ** added to the column cache after this call are removed when the
77613 ** corresponding pop occurs.
77615 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
77616 pParse->iCacheLevel++;
77620 ** Remove from the column cache any entries that were added since the
77621 ** the previous N Push operations. In other words, restore the cache
77622 ** to the state it was in N Pushes ago.
77624 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
77625 int i;
77626 struct yColCache *p;
77627 assert( N>0 );
77628 assert( pParse->iCacheLevel>=N );
77629 pParse->iCacheLevel -= N;
77630 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77631 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
77632 cacheEntryClear(pParse, p);
77633 p->iReg = 0;
77639 ** When a cached column is reused, make sure that its register is
77640 ** no longer available as a temp register. ticket #3879: that same
77641 ** register might be in the cache in multiple places, so be sure to
77642 ** get them all.
77644 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
77645 int i;
77646 struct yColCache *p;
77647 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77648 if( p->iReg==iReg ){
77649 p->tempReg = 0;
77655 ** Generate code to extract the value of the iCol-th column of a table.
77657 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
77658 Vdbe *v, /* The VDBE under construction */
77659 Table *pTab, /* The table containing the value */
77660 int iTabCur, /* The cursor for this table */
77661 int iCol, /* Index of the column to extract */
77662 int regOut /* Extract the valud into this register */
77664 if( iCol<0 || iCol==pTab->iPKey ){
77665 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
77666 }else{
77667 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
77668 sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
77670 if( iCol>=0 ){
77671 sqlite3ColumnDefault(v, pTab, iCol, regOut);
77676 ** Generate code that will extract the iColumn-th column from
77677 ** table pTab and store the column value in a register. An effort
77678 ** is made to store the column value in register iReg, but this is
77679 ** not guaranteed. The location of the column value is returned.
77681 ** There must be an open cursor to pTab in iTable when this routine
77682 ** is called. If iColumn<0 then code is generated that extracts the rowid.
77684 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
77685 Parse *pParse, /* Parsing and code generating context */
77686 Table *pTab, /* Description of the table we are reading from */
77687 int iColumn, /* Index of the table column */
77688 int iTable, /* The cursor pointing to the table */
77689 int iReg, /* Store results here */
77690 u8 p5 /* P5 value for OP_Column */
77692 Vdbe *v = pParse->pVdbe;
77693 int i;
77694 struct yColCache *p;
77696 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77697 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
77698 p->lru = pParse->iCacheCnt++;
77699 sqlite3ExprCachePinRegister(pParse, p->iReg);
77700 return p->iReg;
77703 assert( v!=0 );
77704 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
77705 if( p5 ){
77706 sqlite3VdbeChangeP5(v, p5);
77707 }else{
77708 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
77710 return iReg;
77714 ** Clear all column cache entries.
77716 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
77717 int i;
77718 struct yColCache *p;
77720 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77721 if( p->iReg ){
77722 cacheEntryClear(pParse, p);
77723 p->iReg = 0;
77729 ** Record the fact that an affinity change has occurred on iCount
77730 ** registers starting with iStart.
77732 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
77733 sqlite3ExprCacheRemove(pParse, iStart, iCount);
77737 ** Generate code to move content from registers iFrom...iFrom+nReg-1
77738 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
77740 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
77741 int i;
77742 struct yColCache *p;
77743 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
77744 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
77745 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77746 int x = p->iReg;
77747 if( x>=iFrom && x<iFrom+nReg ){
77748 p->iReg += iTo-iFrom;
77753 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
77755 ** Return true if any register in the range iFrom..iTo (inclusive)
77756 ** is used as part of the column cache.
77758 ** This routine is used within assert() and testcase() macros only
77759 ** and does not appear in a normal build.
77761 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
77762 int i;
77763 struct yColCache *p;
77764 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77765 int r = p->iReg;
77766 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
77768 return 0;
77770 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
77773 ** Generate code into the current Vdbe to evaluate the given
77774 ** expression. Attempt to store the results in register "target".
77775 ** Return the register where results are stored.
77777 ** With this routine, there is no guarantee that results will
77778 ** be stored in target. The result might be stored in some other
77779 ** register if it is convenient to do so. The calling function
77780 ** must check the return code and move the results to the desired
77781 ** register.
77783 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
77784 Vdbe *v = pParse->pVdbe; /* The VM under construction */
77785 int op; /* The opcode being coded */
77786 int inReg = target; /* Results stored in register inReg */
77787 int regFree1 = 0; /* If non-zero free this temporary register */
77788 int regFree2 = 0; /* If non-zero free this temporary register */
77789 int r1, r2, r3, r4; /* Various register numbers */
77790 sqlite3 *db = pParse->db; /* The database connection */
77792 assert( target>0 && target<=pParse->nMem );
77793 if( v==0 ){
77794 assert( pParse->db->mallocFailed );
77795 return 0;
77798 if( pExpr==0 ){
77799 op = TK_NULL;
77800 }else{
77801 op = pExpr->op;
77803 switch( op ){
77804 case TK_AGG_COLUMN: {
77805 AggInfo *pAggInfo = pExpr->pAggInfo;
77806 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
77807 if( !pAggInfo->directMode ){
77808 assert( pCol->iMem>0 );
77809 inReg = pCol->iMem;
77810 break;
77811 }else if( pAggInfo->useSortingIdx ){
77812 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
77813 pCol->iSorterColumn, target);
77814 break;
77816 /* Otherwise, fall thru into the TK_COLUMN case */
77818 case TK_COLUMN: {
77819 int iTab = pExpr->iTable;
77820 if( iTab<0 ){
77821 if( pParse->ckBase>0 ){
77822 /* Generating CHECK constraints or inserting into partial index */
77823 inReg = pExpr->iColumn + pParse->ckBase;
77824 break;
77825 }else{
77826 /* Deleting from a partial index */
77827 iTab = pParse->iPartIdxTab;
77830 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
77831 pExpr->iColumn, iTab, target,
77832 pExpr->op2);
77833 break;
77835 case TK_INTEGER: {
77836 codeInteger(pParse, pExpr, 0, target);
77837 break;
77839 #ifndef SQLITE_OMIT_FLOATING_POINT
77840 case TK_FLOAT: {
77841 assert( !ExprHasProperty(pExpr, EP_IntValue) );
77842 codeReal(v, pExpr->u.zToken, 0, target);
77843 break;
77845 #endif
77846 case TK_STRING: {
77847 assert( !ExprHasProperty(pExpr, EP_IntValue) );
77848 sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
77849 break;
77851 case TK_NULL: {
77852 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77853 break;
77855 #ifndef SQLITE_OMIT_BLOB_LITERAL
77856 case TK_BLOB: {
77857 int n;
77858 const char *z;
77859 char *zBlob;
77860 assert( !ExprHasProperty(pExpr, EP_IntValue) );
77861 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
77862 assert( pExpr->u.zToken[1]=='\'' );
77863 z = &pExpr->u.zToken[2];
77864 n = sqlite3Strlen30(z) - 1;
77865 assert( z[n]=='\'' );
77866 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
77867 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
77868 break;
77870 #endif
77871 case TK_VARIABLE: {
77872 assert( !ExprHasProperty(pExpr, EP_IntValue) );
77873 assert( pExpr->u.zToken!=0 );
77874 assert( pExpr->u.zToken[0]!=0 );
77875 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
77876 if( pExpr->u.zToken[1]!=0 ){
77877 assert( pExpr->u.zToken[0]=='?'
77878 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
77879 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
77881 break;
77883 case TK_REGISTER: {
77884 inReg = pExpr->iTable;
77885 break;
77887 case TK_AS: {
77888 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77889 break;
77891 #ifndef SQLITE_OMIT_CAST
77892 case TK_CAST: {
77893 /* Expressions of the form: CAST(pLeft AS token) */
77894 int aff, to_op;
77895 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77896 assert( !ExprHasProperty(pExpr, EP_IntValue) );
77897 aff = sqlite3AffinityType(pExpr->u.zToken);
77898 to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
77899 assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
77900 assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
77901 assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
77902 assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
77903 assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
77904 testcase( to_op==OP_ToText );
77905 testcase( to_op==OP_ToBlob );
77906 testcase( to_op==OP_ToNumeric );
77907 testcase( to_op==OP_ToInt );
77908 testcase( to_op==OP_ToReal );
77909 if( inReg!=target ){
77910 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
77911 inReg = target;
77913 sqlite3VdbeAddOp1(v, to_op, inReg);
77914 testcase( usedAsColumnCache(pParse, inReg, inReg) );
77915 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
77916 break;
77918 #endif /* SQLITE_OMIT_CAST */
77919 case TK_LT:
77920 case TK_LE:
77921 case TK_GT:
77922 case TK_GE:
77923 case TK_NE:
77924 case TK_EQ: {
77925 assert( TK_LT==OP_Lt );
77926 assert( TK_LE==OP_Le );
77927 assert( TK_GT==OP_Gt );
77928 assert( TK_GE==OP_Ge );
77929 assert( TK_EQ==OP_Eq );
77930 assert( TK_NE==OP_Ne );
77931 testcase( op==TK_LT );
77932 testcase( op==TK_LE );
77933 testcase( op==TK_GT );
77934 testcase( op==TK_GE );
77935 testcase( op==TK_EQ );
77936 testcase( op==TK_NE );
77937 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77938 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77939 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77940 r1, r2, inReg, SQLITE_STOREP2);
77941 testcase( regFree1==0 );
77942 testcase( regFree2==0 );
77943 break;
77945 case TK_IS:
77946 case TK_ISNOT: {
77947 testcase( op==TK_IS );
77948 testcase( op==TK_ISNOT );
77949 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77950 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77951 op = (op==TK_IS) ? TK_EQ : TK_NE;
77952 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77953 r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
77954 testcase( regFree1==0 );
77955 testcase( regFree2==0 );
77956 break;
77958 case TK_AND:
77959 case TK_OR:
77960 case TK_PLUS:
77961 case TK_STAR:
77962 case TK_MINUS:
77963 case TK_REM:
77964 case TK_BITAND:
77965 case TK_BITOR:
77966 case TK_SLASH:
77967 case TK_LSHIFT:
77968 case TK_RSHIFT:
77969 case TK_CONCAT: {
77970 assert( TK_AND==OP_And );
77971 assert( TK_OR==OP_Or );
77972 assert( TK_PLUS==OP_Add );
77973 assert( TK_MINUS==OP_Subtract );
77974 assert( TK_REM==OP_Remainder );
77975 assert( TK_BITAND==OP_BitAnd );
77976 assert( TK_BITOR==OP_BitOr );
77977 assert( TK_SLASH==OP_Divide );
77978 assert( TK_LSHIFT==OP_ShiftLeft );
77979 assert( TK_RSHIFT==OP_ShiftRight );
77980 assert( TK_CONCAT==OP_Concat );
77981 testcase( op==TK_AND );
77982 testcase( op==TK_OR );
77983 testcase( op==TK_PLUS );
77984 testcase( op==TK_MINUS );
77985 testcase( op==TK_REM );
77986 testcase( op==TK_BITAND );
77987 testcase( op==TK_BITOR );
77988 testcase( op==TK_SLASH );
77989 testcase( op==TK_LSHIFT );
77990 testcase( op==TK_RSHIFT );
77991 testcase( op==TK_CONCAT );
77992 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77993 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77994 sqlite3VdbeAddOp3(v, op, r2, r1, target);
77995 testcase( regFree1==0 );
77996 testcase( regFree2==0 );
77997 break;
77999 case TK_UMINUS: {
78000 Expr *pLeft = pExpr->pLeft;
78001 assert( pLeft );
78002 if( pLeft->op==TK_INTEGER ){
78003 codeInteger(pParse, pLeft, 1, target);
78004 #ifndef SQLITE_OMIT_FLOATING_POINT
78005 }else if( pLeft->op==TK_FLOAT ){
78006 assert( !ExprHasProperty(pExpr, EP_IntValue) );
78007 codeReal(v, pLeft->u.zToken, 1, target);
78008 #endif
78009 }else{
78010 regFree1 = r1 = sqlite3GetTempReg(pParse);
78011 sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
78012 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
78013 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
78014 testcase( regFree2==0 );
78016 inReg = target;
78017 break;
78019 case TK_BITNOT:
78020 case TK_NOT: {
78021 assert( TK_BITNOT==OP_BitNot );
78022 assert( TK_NOT==OP_Not );
78023 testcase( op==TK_BITNOT );
78024 testcase( op==TK_NOT );
78025 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78026 testcase( regFree1==0 );
78027 inReg = target;
78028 sqlite3VdbeAddOp2(v, op, r1, inReg);
78029 break;
78031 case TK_ISNULL:
78032 case TK_NOTNULL: {
78033 int addr;
78034 assert( TK_ISNULL==OP_IsNull );
78035 assert( TK_NOTNULL==OP_NotNull );
78036 testcase( op==TK_ISNULL );
78037 testcase( op==TK_NOTNULL );
78038 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
78039 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78040 testcase( regFree1==0 );
78041 addr = sqlite3VdbeAddOp1(v, op, r1);
78042 sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
78043 sqlite3VdbeJumpHere(v, addr);
78044 break;
78046 case TK_AGG_FUNCTION: {
78047 AggInfo *pInfo = pExpr->pAggInfo;
78048 if( pInfo==0 ){
78049 assert( !ExprHasProperty(pExpr, EP_IntValue) );
78050 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
78051 }else{
78052 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
78054 break;
78056 case TK_CONST_FUNC:
78057 case TK_FUNCTION: {
78058 ExprList *pFarg; /* List of function arguments */
78059 int nFarg; /* Number of function arguments */
78060 FuncDef *pDef; /* The function definition object */
78061 int nId; /* Length of the function name in bytes */
78062 const char *zId; /* The function name */
78063 int constMask = 0; /* Mask of function arguments that are constant */
78064 int i; /* Loop counter */
78065 u8 enc = ENC(db); /* The text encoding used by this database */
78066 CollSeq *pColl = 0; /* A collating sequence */
78068 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78069 testcase( op==TK_CONST_FUNC );
78070 testcase( op==TK_FUNCTION );
78071 if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
78072 pFarg = 0;
78073 }else{
78074 pFarg = pExpr->x.pList;
78076 nFarg = pFarg ? pFarg->nExpr : 0;
78077 assert( !ExprHasProperty(pExpr, EP_IntValue) );
78078 zId = pExpr->u.zToken;
78079 nId = sqlite3Strlen30(zId);
78080 pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
78081 if( pDef==0 ){
78082 sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
78083 break;
78086 /* Attempt a direct implementation of the built-in COALESCE() and
78087 ** IFNULL() functions. This avoids unnecessary evalation of
78088 ** arguments past the first non-NULL argument.
78090 if( pDef->flags & SQLITE_FUNC_COALESCE ){
78091 int endCoalesce = sqlite3VdbeMakeLabel(v);
78092 assert( nFarg>=2 );
78093 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
78094 for(i=1; i<nFarg; i++){
78095 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
78096 sqlite3ExprCacheRemove(pParse, target, 1);
78097 sqlite3ExprCachePush(pParse);
78098 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
78099 sqlite3ExprCachePop(pParse, 1);
78101 sqlite3VdbeResolveLabel(v, endCoalesce);
78102 break;
78106 if( pFarg ){
78107 r1 = sqlite3GetTempRange(pParse, nFarg);
78109 /* For length() and typeof() functions with a column argument,
78110 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
78111 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
78112 ** loading.
78114 if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
78115 u8 exprOp;
78116 assert( nFarg==1 );
78117 assert( pFarg->a[0].pExpr!=0 );
78118 exprOp = pFarg->a[0].pExpr->op;
78119 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
78120 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
78121 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
78122 testcase( pDef->flags==SQLITE_FUNC_LENGTH );
78123 pFarg->a[0].pExpr->op2 = pDef->flags;
78127 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
78128 sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
78129 sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
78130 }else{
78131 r1 = 0;
78133 #ifndef SQLITE_OMIT_VIRTUALTABLE
78134 /* Possibly overload the function if the first argument is
78135 ** a virtual table column.
78137 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
78138 ** second argument, not the first, as the argument to test to
78139 ** see if it is a column in a virtual table. This is done because
78140 ** the left operand of infix functions (the operand we want to
78141 ** control overloading) ends up as the second argument to the
78142 ** function. The expression "A glob B" is equivalent to
78143 ** "glob(B,A). We want to use the A in "A glob B" to test
78144 ** for function overloading. But we use the B term in "glob(B,A)".
78146 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
78147 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
78148 }else if( nFarg>0 ){
78149 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
78151 #endif
78152 for(i=0; i<nFarg; i++){
78153 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
78154 constMask |= (1<<i);
78156 if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
78157 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
78160 if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
78161 if( !pColl ) pColl = db->pDfltColl;
78162 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
78164 sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
78165 (char*)pDef, P4_FUNCDEF);
78166 sqlite3VdbeChangeP5(v, (u8)nFarg);
78167 if( nFarg ){
78168 sqlite3ReleaseTempRange(pParse, r1, nFarg);
78170 break;
78172 #ifndef SQLITE_OMIT_SUBQUERY
78173 case TK_EXISTS:
78174 case TK_SELECT: {
78175 testcase( op==TK_EXISTS );
78176 testcase( op==TK_SELECT );
78177 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
78178 break;
78180 case TK_IN: {
78181 int destIfFalse = sqlite3VdbeMakeLabel(v);
78182 int destIfNull = sqlite3VdbeMakeLabel(v);
78183 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
78184 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
78185 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
78186 sqlite3VdbeResolveLabel(v, destIfFalse);
78187 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
78188 sqlite3VdbeResolveLabel(v, destIfNull);
78189 break;
78191 #endif /* SQLITE_OMIT_SUBQUERY */
78195 ** x BETWEEN y AND z
78197 ** This is equivalent to
78199 ** x>=y AND x<=z
78201 ** X is stored in pExpr->pLeft.
78202 ** Y is stored in pExpr->pList->a[0].pExpr.
78203 ** Z is stored in pExpr->pList->a[1].pExpr.
78205 case TK_BETWEEN: {
78206 Expr *pLeft = pExpr->pLeft;
78207 struct ExprList_item *pLItem = pExpr->x.pList->a;
78208 Expr *pRight = pLItem->pExpr;
78210 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
78211 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
78212 testcase( regFree1==0 );
78213 testcase( regFree2==0 );
78214 r3 = sqlite3GetTempReg(pParse);
78215 r4 = sqlite3GetTempReg(pParse);
78216 codeCompare(pParse, pLeft, pRight, OP_Ge,
78217 r1, r2, r3, SQLITE_STOREP2);
78218 pLItem++;
78219 pRight = pLItem->pExpr;
78220 sqlite3ReleaseTempReg(pParse, regFree2);
78221 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
78222 testcase( regFree2==0 );
78223 codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
78224 sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
78225 sqlite3ReleaseTempReg(pParse, r3);
78226 sqlite3ReleaseTempReg(pParse, r4);
78227 break;
78229 case TK_COLLATE:
78230 case TK_UPLUS: {
78231 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
78232 break;
78235 case TK_TRIGGER: {
78236 /* If the opcode is TK_TRIGGER, then the expression is a reference
78237 ** to a column in the new.* or old.* pseudo-tables available to
78238 ** trigger programs. In this case Expr.iTable is set to 1 for the
78239 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
78240 ** is set to the column of the pseudo-table to read, or to -1 to
78241 ** read the rowid field.
78243 ** The expression is implemented using an OP_Param opcode. The p1
78244 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
78245 ** to reference another column of the old.* pseudo-table, where
78246 ** i is the index of the column. For a new.rowid reference, p1 is
78247 ** set to (n+1), where n is the number of columns in each pseudo-table.
78248 ** For a reference to any other column in the new.* pseudo-table, p1
78249 ** is set to (n+2+i), where n and i are as defined previously. For
78250 ** example, if the table on which triggers are being fired is
78251 ** declared as:
78253 ** CREATE TABLE t1(a, b);
78255 ** Then p1 is interpreted as follows:
78257 ** p1==0 -> old.rowid p1==3 -> new.rowid
78258 ** p1==1 -> old.a p1==4 -> new.a
78259 ** p1==2 -> old.b p1==5 -> new.b
78261 Table *pTab = pExpr->pTab;
78262 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
78264 assert( pExpr->iTable==0 || pExpr->iTable==1 );
78265 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
78266 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
78267 assert( p1>=0 && p1<(pTab->nCol*2+2) );
78269 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
78270 VdbeComment((v, "%s.%s -> $%d",
78271 (pExpr->iTable ? "new" : "old"),
78272 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
78273 target
78276 #ifndef SQLITE_OMIT_FLOATING_POINT
78277 /* If the column has REAL affinity, it may currently be stored as an
78278 ** integer. Use OP_RealAffinity to make sure it is really real. */
78279 if( pExpr->iColumn>=0
78280 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
78282 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
78284 #endif
78285 break;
78290 ** Form A:
78291 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
78293 ** Form B:
78294 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
78296 ** Form A is can be transformed into the equivalent form B as follows:
78297 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
78298 ** WHEN x=eN THEN rN ELSE y END
78300 ** X (if it exists) is in pExpr->pLeft.
78301 ** Y is in pExpr->pRight. The Y is also optional. If there is no
78302 ** ELSE clause and no other term matches, then the result of the
78303 ** exprssion is NULL.
78304 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
78306 ** The result of the expression is the Ri for the first matching Ei,
78307 ** or if there is no matching Ei, the ELSE term Y, or if there is
78308 ** no ELSE term, NULL.
78310 default: assert( op==TK_CASE ); {
78311 int endLabel; /* GOTO label for end of CASE stmt */
78312 int nextCase; /* GOTO label for next WHEN clause */
78313 int nExpr; /* 2x number of WHEN terms */
78314 int i; /* Loop counter */
78315 ExprList *pEList; /* List of WHEN terms */
78316 struct ExprList_item *aListelem; /* Array of WHEN terms */
78317 Expr opCompare; /* The X==Ei expression */
78318 Expr cacheX; /* Cached expression X */
78319 Expr *pX; /* The X expression */
78320 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
78321 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
78323 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
78324 assert((pExpr->x.pList->nExpr % 2) == 0);
78325 assert(pExpr->x.pList->nExpr > 0);
78326 pEList = pExpr->x.pList;
78327 aListelem = pEList->a;
78328 nExpr = pEList->nExpr;
78329 endLabel = sqlite3VdbeMakeLabel(v);
78330 if( (pX = pExpr->pLeft)!=0 ){
78331 cacheX = *pX;
78332 testcase( pX->op==TK_COLUMN );
78333 testcase( pX->op==TK_REGISTER );
78334 cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
78335 testcase( regFree1==0 );
78336 cacheX.op = TK_REGISTER;
78337 opCompare.op = TK_EQ;
78338 opCompare.pLeft = &cacheX;
78339 pTest = &opCompare;
78340 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
78341 ** The value in regFree1 might get SCopy-ed into the file result.
78342 ** So make sure that the regFree1 register is not reused for other
78343 ** purposes and possibly overwritten. */
78344 regFree1 = 0;
78346 for(i=0; i<nExpr; i=i+2){
78347 sqlite3ExprCachePush(pParse);
78348 if( pX ){
78349 assert( pTest!=0 );
78350 opCompare.pRight = aListelem[i].pExpr;
78351 }else{
78352 pTest = aListelem[i].pExpr;
78354 nextCase = sqlite3VdbeMakeLabel(v);
78355 testcase( pTest->op==TK_COLUMN );
78356 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
78357 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
78358 testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
78359 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
78360 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
78361 sqlite3ExprCachePop(pParse, 1);
78362 sqlite3VdbeResolveLabel(v, nextCase);
78364 if( pExpr->pRight ){
78365 sqlite3ExprCachePush(pParse);
78366 sqlite3ExprCode(pParse, pExpr->pRight, target);
78367 sqlite3ExprCachePop(pParse, 1);
78368 }else{
78369 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
78371 assert( db->mallocFailed || pParse->nErr>0
78372 || pParse->iCacheLevel==iCacheLevel );
78373 sqlite3VdbeResolveLabel(v, endLabel);
78374 break;
78376 #ifndef SQLITE_OMIT_TRIGGER
78377 case TK_RAISE: {
78378 assert( pExpr->affinity==OE_Rollback
78379 || pExpr->affinity==OE_Abort
78380 || pExpr->affinity==OE_Fail
78381 || pExpr->affinity==OE_Ignore
78383 if( !pParse->pTriggerTab ){
78384 sqlite3ErrorMsg(pParse,
78385 "RAISE() may only be used within a trigger-program");
78386 return 0;
78388 if( pExpr->affinity==OE_Abort ){
78389 sqlite3MayAbort(pParse);
78391 assert( !ExprHasProperty(pExpr, EP_IntValue) );
78392 if( pExpr->affinity==OE_Ignore ){
78393 sqlite3VdbeAddOp4(
78394 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
78395 }else{
78396 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
78397 pExpr->affinity, pExpr->u.zToken, 0);
78400 break;
78402 #endif
78404 sqlite3ReleaseTempReg(pParse, regFree1);
78405 sqlite3ReleaseTempReg(pParse, regFree2);
78406 return inReg;
78410 ** Generate code to evaluate an expression and store the results
78411 ** into a register. Return the register number where the results
78412 ** are stored.
78414 ** If the register is a temporary register that can be deallocated,
78415 ** then write its number into *pReg. If the result register is not
78416 ** a temporary, then set *pReg to zero.
78418 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
78419 int r1 = sqlite3GetTempReg(pParse);
78420 int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
78421 if( r2==r1 ){
78422 *pReg = r1;
78423 }else{
78424 sqlite3ReleaseTempReg(pParse, r1);
78425 *pReg = 0;
78427 return r2;
78431 ** Generate code that will evaluate expression pExpr and store the
78432 ** results in register target. The results are guaranteed to appear
78433 ** in register target.
78435 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
78436 int inReg;
78438 assert( target>0 && target<=pParse->nMem );
78439 if( pExpr && pExpr->op==TK_REGISTER ){
78440 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
78441 }else{
78442 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
78443 assert( pParse->pVdbe || pParse->db->mallocFailed );
78444 if( inReg!=target && pParse->pVdbe ){
78445 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
78448 return target;
78452 ** Generate code that evalutes the given expression and puts the result
78453 ** in register target.
78455 ** Also make a copy of the expression results into another "cache" register
78456 ** and modify the expression so that the next time it is evaluated,
78457 ** the result is a copy of the cache register.
78459 ** This routine is used for expressions that are used multiple
78460 ** times. They are evaluated once and the results of the expression
78461 ** are reused.
78463 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
78464 Vdbe *v = pParse->pVdbe;
78465 int inReg;
78466 inReg = sqlite3ExprCode(pParse, pExpr, target);
78467 assert( target>0 );
78468 /* This routine is called for terms to INSERT or UPDATE. And the only
78469 ** other place where expressions can be converted into TK_REGISTER is
78470 ** in WHERE clause processing. So as currently implemented, there is
78471 ** no way for a TK_REGISTER to exist here. But it seems prudent to
78472 ** keep the ALWAYS() in case the conditions above change with future
78473 ** modifications or enhancements. */
78474 if( ALWAYS(pExpr->op!=TK_REGISTER) ){
78475 int iMem;
78476 iMem = ++pParse->nMem;
78477 sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
78478 pExpr->iTable = iMem;
78479 pExpr->op2 = pExpr->op;
78480 pExpr->op = TK_REGISTER;
78482 return inReg;
78485 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
78487 ** Generate a human-readable explanation of an expression tree.
78489 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
78490 int op; /* The opcode being coded */
78491 const char *zBinOp = 0; /* Binary operator */
78492 const char *zUniOp = 0; /* Unary operator */
78493 if( pExpr==0 ){
78494 op = TK_NULL;
78495 }else{
78496 op = pExpr->op;
78498 switch( op ){
78499 case TK_AGG_COLUMN: {
78500 sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
78501 pExpr->iTable, pExpr->iColumn);
78502 break;
78504 case TK_COLUMN: {
78505 if( pExpr->iTable<0 ){
78506 /* This only happens when coding check constraints */
78507 sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
78508 }else{
78509 sqlite3ExplainPrintf(pOut, "{%d:%d}",
78510 pExpr->iTable, pExpr->iColumn);
78512 break;
78514 case TK_INTEGER: {
78515 if( pExpr->flags & EP_IntValue ){
78516 sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
78517 }else{
78518 sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
78520 break;
78522 #ifndef SQLITE_OMIT_FLOATING_POINT
78523 case TK_FLOAT: {
78524 sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
78525 break;
78527 #endif
78528 case TK_STRING: {
78529 sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
78530 break;
78532 case TK_NULL: {
78533 sqlite3ExplainPrintf(pOut,"NULL");
78534 break;
78536 #ifndef SQLITE_OMIT_BLOB_LITERAL
78537 case TK_BLOB: {
78538 sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
78539 break;
78541 #endif
78542 case TK_VARIABLE: {
78543 sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
78544 pExpr->u.zToken, pExpr->iColumn);
78545 break;
78547 case TK_REGISTER: {
78548 sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
78549 break;
78551 case TK_AS: {
78552 sqlite3ExplainExpr(pOut, pExpr->pLeft);
78553 break;
78555 #ifndef SQLITE_OMIT_CAST
78556 case TK_CAST: {
78557 /* Expressions of the form: CAST(pLeft AS token) */
78558 const char *zAff = "unk";
78559 switch( sqlite3AffinityType(pExpr->u.zToken) ){
78560 case SQLITE_AFF_TEXT: zAff = "TEXT"; break;
78561 case SQLITE_AFF_NONE: zAff = "NONE"; break;
78562 case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break;
78563 case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break;
78564 case SQLITE_AFF_REAL: zAff = "REAL"; break;
78566 sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
78567 sqlite3ExplainExpr(pOut, pExpr->pLeft);
78568 sqlite3ExplainPrintf(pOut, ")");
78569 break;
78571 #endif /* SQLITE_OMIT_CAST */
78572 case TK_LT: zBinOp = "LT"; break;
78573 case TK_LE: zBinOp = "LE"; break;
78574 case TK_GT: zBinOp = "GT"; break;
78575 case TK_GE: zBinOp = "GE"; break;
78576 case TK_NE: zBinOp = "NE"; break;
78577 case TK_EQ: zBinOp = "EQ"; break;
78578 case TK_IS: zBinOp = "IS"; break;
78579 case TK_ISNOT: zBinOp = "ISNOT"; break;
78580 case TK_AND: zBinOp = "AND"; break;
78581 case TK_OR: zBinOp = "OR"; break;
78582 case TK_PLUS: zBinOp = "ADD"; break;
78583 case TK_STAR: zBinOp = "MUL"; break;
78584 case TK_MINUS: zBinOp = "SUB"; break;
78585 case TK_REM: zBinOp = "REM"; break;
78586 case TK_BITAND: zBinOp = "BITAND"; break;
78587 case TK_BITOR: zBinOp = "BITOR"; break;
78588 case TK_SLASH: zBinOp = "DIV"; break;
78589 case TK_LSHIFT: zBinOp = "LSHIFT"; break;
78590 case TK_RSHIFT: zBinOp = "RSHIFT"; break;
78591 case TK_CONCAT: zBinOp = "CONCAT"; break;
78593 case TK_UMINUS: zUniOp = "UMINUS"; break;
78594 case TK_UPLUS: zUniOp = "UPLUS"; break;
78595 case TK_BITNOT: zUniOp = "BITNOT"; break;
78596 case TK_NOT: zUniOp = "NOT"; break;
78597 case TK_ISNULL: zUniOp = "ISNULL"; break;
78598 case TK_NOTNULL: zUniOp = "NOTNULL"; break;
78600 case TK_COLLATE: {
78601 sqlite3ExplainExpr(pOut, pExpr->pLeft);
78602 sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
78603 break;
78606 case TK_AGG_FUNCTION:
78607 case TK_CONST_FUNC:
78608 case TK_FUNCTION: {
78609 ExprList *pFarg; /* List of function arguments */
78610 if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
78611 pFarg = 0;
78612 }else{
78613 pFarg = pExpr->x.pList;
78615 if( op==TK_AGG_FUNCTION ){
78616 sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
78617 pExpr->op2, pExpr->u.zToken);
78618 }else{
78619 sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
78621 if( pFarg ){
78622 sqlite3ExplainExprList(pOut, pFarg);
78624 sqlite3ExplainPrintf(pOut, ")");
78625 break;
78627 #ifndef SQLITE_OMIT_SUBQUERY
78628 case TK_EXISTS: {
78629 sqlite3ExplainPrintf(pOut, "EXISTS(");
78630 sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78631 sqlite3ExplainPrintf(pOut,")");
78632 break;
78634 case TK_SELECT: {
78635 sqlite3ExplainPrintf(pOut, "(");
78636 sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78637 sqlite3ExplainPrintf(pOut, ")");
78638 break;
78640 case TK_IN: {
78641 sqlite3ExplainPrintf(pOut, "IN(");
78642 sqlite3ExplainExpr(pOut, pExpr->pLeft);
78643 sqlite3ExplainPrintf(pOut, ",");
78644 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
78645 sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78646 }else{
78647 sqlite3ExplainExprList(pOut, pExpr->x.pList);
78649 sqlite3ExplainPrintf(pOut, ")");
78650 break;
78652 #endif /* SQLITE_OMIT_SUBQUERY */
78655 ** x BETWEEN y AND z
78657 ** This is equivalent to
78659 ** x>=y AND x<=z
78661 ** X is stored in pExpr->pLeft.
78662 ** Y is stored in pExpr->pList->a[0].pExpr.
78663 ** Z is stored in pExpr->pList->a[1].pExpr.
78665 case TK_BETWEEN: {
78666 Expr *pX = pExpr->pLeft;
78667 Expr *pY = pExpr->x.pList->a[0].pExpr;
78668 Expr *pZ = pExpr->x.pList->a[1].pExpr;
78669 sqlite3ExplainPrintf(pOut, "BETWEEN(");
78670 sqlite3ExplainExpr(pOut, pX);
78671 sqlite3ExplainPrintf(pOut, ",");
78672 sqlite3ExplainExpr(pOut, pY);
78673 sqlite3ExplainPrintf(pOut, ",");
78674 sqlite3ExplainExpr(pOut, pZ);
78675 sqlite3ExplainPrintf(pOut, ")");
78676 break;
78678 case TK_TRIGGER: {
78679 /* If the opcode is TK_TRIGGER, then the expression is a reference
78680 ** to a column in the new.* or old.* pseudo-tables available to
78681 ** trigger programs. In this case Expr.iTable is set to 1 for the
78682 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
78683 ** is set to the column of the pseudo-table to read, or to -1 to
78684 ** read the rowid field.
78686 sqlite3ExplainPrintf(pOut, "%s(%d)",
78687 pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
78688 break;
78690 case TK_CASE: {
78691 sqlite3ExplainPrintf(pOut, "CASE(");
78692 sqlite3ExplainExpr(pOut, pExpr->pLeft);
78693 sqlite3ExplainPrintf(pOut, ",");
78694 sqlite3ExplainExprList(pOut, pExpr->x.pList);
78695 break;
78697 #ifndef SQLITE_OMIT_TRIGGER
78698 case TK_RAISE: {
78699 const char *zType = "unk";
78700 switch( pExpr->affinity ){
78701 case OE_Rollback: zType = "rollback"; break;
78702 case OE_Abort: zType = "abort"; break;
78703 case OE_Fail: zType = "fail"; break;
78704 case OE_Ignore: zType = "ignore"; break;
78706 sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
78707 break;
78709 #endif
78711 if( zBinOp ){
78712 sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
78713 sqlite3ExplainExpr(pOut, pExpr->pLeft);
78714 sqlite3ExplainPrintf(pOut,",");
78715 sqlite3ExplainExpr(pOut, pExpr->pRight);
78716 sqlite3ExplainPrintf(pOut,")");
78717 }else if( zUniOp ){
78718 sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
78719 sqlite3ExplainExpr(pOut, pExpr->pLeft);
78720 sqlite3ExplainPrintf(pOut,")");
78723 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
78725 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
78727 ** Generate a human-readable explanation of an expression list.
78729 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
78730 int i;
78731 if( pList==0 || pList->nExpr==0 ){
78732 sqlite3ExplainPrintf(pOut, "(empty-list)");
78733 return;
78734 }else if( pList->nExpr==1 ){
78735 sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
78736 }else{
78737 sqlite3ExplainPush(pOut);
78738 for(i=0; i<pList->nExpr; i++){
78739 sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
78740 sqlite3ExplainPush(pOut);
78741 sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
78742 sqlite3ExplainPop(pOut);
78743 if( pList->a[i].zName ){
78744 sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
78746 if( pList->a[i].bSpanIsTab ){
78747 sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
78749 if( i<pList->nExpr-1 ){
78750 sqlite3ExplainNL(pOut);
78753 sqlite3ExplainPop(pOut);
78756 #endif /* SQLITE_DEBUG */
78759 ** Return TRUE if pExpr is an constant expression that is appropriate
78760 ** for factoring out of a loop. Appropriate expressions are:
78762 ** * Any expression that evaluates to two or more opcodes.
78764 ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
78765 ** or OP_Variable that does not need to be placed in a
78766 ** specific register.
78768 ** There is no point in factoring out single-instruction constant
78769 ** expressions that need to be placed in a particular register.
78770 ** We could factor them out, but then we would end up adding an
78771 ** OP_SCopy instruction to move the value into the correct register
78772 ** later. We might as well just use the original instruction and
78773 ** avoid the OP_SCopy.
78775 static int isAppropriateForFactoring(Expr *p){
78776 if( !sqlite3ExprIsConstantNotJoin(p) ){
78777 return 0; /* Only constant expressions are appropriate for factoring */
78779 if( (p->flags & EP_FixedDest)==0 ){
78780 return 1; /* Any constant without a fixed destination is appropriate */
78782 while( p->op==TK_UPLUS ) p = p->pLeft;
78783 switch( p->op ){
78784 #ifndef SQLITE_OMIT_BLOB_LITERAL
78785 case TK_BLOB:
78786 #endif
78787 case TK_VARIABLE:
78788 case TK_INTEGER:
78789 case TK_FLOAT:
78790 case TK_NULL:
78791 case TK_STRING: {
78792 testcase( p->op==TK_BLOB );
78793 testcase( p->op==TK_VARIABLE );
78794 testcase( p->op==TK_INTEGER );
78795 testcase( p->op==TK_FLOAT );
78796 testcase( p->op==TK_NULL );
78797 testcase( p->op==TK_STRING );
78798 /* Single-instruction constants with a fixed destination are
78799 ** better done in-line. If we factor them, they will just end
78800 ** up generating an OP_SCopy to move the value to the destination
78801 ** register. */
78802 return 0;
78804 case TK_UMINUS: {
78805 if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
78806 return 0;
78808 break;
78810 default: {
78811 break;
78814 return 1;
78818 ** If pExpr is a constant expression that is appropriate for
78819 ** factoring out of a loop, then evaluate the expression
78820 ** into a register and convert the expression into a TK_REGISTER
78821 ** expression.
78823 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
78824 Parse *pParse = pWalker->pParse;
78825 switch( pExpr->op ){
78826 case TK_IN:
78827 case TK_REGISTER: {
78828 return WRC_Prune;
78830 case TK_COLLATE: {
78831 return WRC_Continue;
78833 case TK_FUNCTION:
78834 case TK_AGG_FUNCTION:
78835 case TK_CONST_FUNC: {
78836 /* The arguments to a function have a fixed destination.
78837 ** Mark them this way to avoid generated unneeded OP_SCopy
78838 ** instructions.
78840 ExprList *pList = pExpr->x.pList;
78841 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78842 if( pList ){
78843 int i = pList->nExpr;
78844 struct ExprList_item *pItem = pList->a;
78845 for(; i>0; i--, pItem++){
78846 if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
78849 break;
78852 if( isAppropriateForFactoring(pExpr) ){
78853 int r1 = ++pParse->nMem;
78854 int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
78855 /* If r2!=r1, it means that register r1 is never used. That is harmless
78856 ** but suboptimal, so we want to know about the situation to fix it.
78857 ** Hence the following assert: */
78858 assert( r2==r1 );
78859 pExpr->op2 = pExpr->op;
78860 pExpr->op = TK_REGISTER;
78861 pExpr->iTable = r2;
78862 return WRC_Prune;
78864 return WRC_Continue;
78868 ** Preevaluate constant subexpressions within pExpr and store the
78869 ** results in registers. Modify pExpr so that the constant subexpresions
78870 ** are TK_REGISTER opcodes that refer to the precomputed values.
78872 ** This routine is a no-op if the jump to the cookie-check code has
78873 ** already occur. Since the cookie-check jump is generated prior to
78874 ** any other serious processing, this check ensures that there is no
78875 ** way to accidently bypass the constant initializations.
78877 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
78878 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
78879 ** interface. This allows test logic to verify that the same answer is
78880 ** obtained for queries regardless of whether or not constants are
78881 ** precomputed into registers or if they are inserted in-line.
78883 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
78884 Walker w;
78885 if( pParse->cookieGoto ) return;
78886 if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
78887 memset(&w, 0, sizeof(w));
78888 w.xExprCallback = evalConstExpr;
78889 w.pParse = pParse;
78890 sqlite3WalkExpr(&w, pExpr);
78895 ** Generate code that pushes the value of every element of the given
78896 ** expression list into a sequence of registers beginning at target.
78898 ** Return the number of elements evaluated.
78900 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
78901 Parse *pParse, /* Parsing context */
78902 ExprList *pList, /* The expression list to be coded */
78903 int target, /* Where to write results */
78904 int doHardCopy /* Make a hard copy of every element */
78906 struct ExprList_item *pItem;
78907 int i, n;
78908 assert( pList!=0 );
78909 assert( target>0 );
78910 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
78911 n = pList->nExpr;
78912 for(pItem=pList->a, i=0; i<n; i++, pItem++){
78913 Expr *pExpr = pItem->pExpr;
78914 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
78915 if( inReg!=target+i ){
78916 sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
78917 inReg, target+i);
78920 return n;
78924 ** Generate code for a BETWEEN operator.
78926 ** x BETWEEN y AND z
78928 ** The above is equivalent to
78930 ** x>=y AND x<=z
78932 ** Code it as such, taking care to do the common subexpression
78933 ** elementation of x.
78935 static void exprCodeBetween(
78936 Parse *pParse, /* Parsing and code generating context */
78937 Expr *pExpr, /* The BETWEEN expression */
78938 int dest, /* Jump here if the jump is taken */
78939 int jumpIfTrue, /* Take the jump if the BETWEEN is true */
78940 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
78942 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
78943 Expr compLeft; /* The x>=y term */
78944 Expr compRight; /* The x<=z term */
78945 Expr exprX; /* The x subexpression */
78946 int regFree1 = 0; /* Temporary use register */
78948 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78949 exprX = *pExpr->pLeft;
78950 exprAnd.op = TK_AND;
78951 exprAnd.pLeft = &compLeft;
78952 exprAnd.pRight = &compRight;
78953 compLeft.op = TK_GE;
78954 compLeft.pLeft = &exprX;
78955 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
78956 compRight.op = TK_LE;
78957 compRight.pLeft = &exprX;
78958 compRight.pRight = pExpr->x.pList->a[1].pExpr;
78959 exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
78960 exprX.op2 = exprX.op;
78961 exprX.op = TK_REGISTER;
78962 if( jumpIfTrue ){
78963 sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
78964 }else{
78965 sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
78967 sqlite3ReleaseTempReg(pParse, regFree1);
78969 /* Ensure adequate test coverage */
78970 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
78971 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
78972 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
78973 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
78974 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
78975 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
78976 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
78977 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
78981 ** Generate code for a boolean expression such that a jump is made
78982 ** to the label "dest" if the expression is true but execution
78983 ** continues straight thru if the expression is false.
78985 ** If the expression evaluates to NULL (neither true nor false), then
78986 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
78988 ** This code depends on the fact that certain token values (ex: TK_EQ)
78989 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
78990 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
78991 ** the make process cause these values to align. Assert()s in the code
78992 ** below verify that the numbers are aligned correctly.
78994 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
78995 Vdbe *v = pParse->pVdbe;
78996 int op = 0;
78997 int regFree1 = 0;
78998 int regFree2 = 0;
78999 int r1, r2;
79001 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
79002 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
79003 if( NEVER(pExpr==0) ) return; /* No way this can happen */
79004 op = pExpr->op;
79005 switch( op ){
79006 case TK_AND: {
79007 int d2 = sqlite3VdbeMakeLabel(v);
79008 testcase( jumpIfNull==0 );
79009 sqlite3ExprCachePush(pParse);
79010 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
79011 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
79012 sqlite3VdbeResolveLabel(v, d2);
79013 sqlite3ExprCachePop(pParse, 1);
79014 break;
79016 case TK_OR: {
79017 testcase( jumpIfNull==0 );
79018 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
79019 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
79020 break;
79022 case TK_NOT: {
79023 testcase( jumpIfNull==0 );
79024 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
79025 break;
79027 case TK_LT:
79028 case TK_LE:
79029 case TK_GT:
79030 case TK_GE:
79031 case TK_NE:
79032 case TK_EQ: {
79033 assert( TK_LT==OP_Lt );
79034 assert( TK_LE==OP_Le );
79035 assert( TK_GT==OP_Gt );
79036 assert( TK_GE==OP_Ge );
79037 assert( TK_EQ==OP_Eq );
79038 assert( TK_NE==OP_Ne );
79039 testcase( op==TK_LT );
79040 testcase( op==TK_LE );
79041 testcase( op==TK_GT );
79042 testcase( op==TK_GE );
79043 testcase( op==TK_EQ );
79044 testcase( op==TK_NE );
79045 testcase( jumpIfNull==0 );
79046 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79047 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79048 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
79049 r1, r2, dest, jumpIfNull);
79050 testcase( regFree1==0 );
79051 testcase( regFree2==0 );
79052 break;
79054 case TK_IS:
79055 case TK_ISNOT: {
79056 testcase( op==TK_IS );
79057 testcase( op==TK_ISNOT );
79058 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79059 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79060 op = (op==TK_IS) ? TK_EQ : TK_NE;
79061 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
79062 r1, r2, dest, SQLITE_NULLEQ);
79063 testcase( regFree1==0 );
79064 testcase( regFree2==0 );
79065 break;
79067 case TK_ISNULL:
79068 case TK_NOTNULL: {
79069 assert( TK_ISNULL==OP_IsNull );
79070 assert( TK_NOTNULL==OP_NotNull );
79071 testcase( op==TK_ISNULL );
79072 testcase( op==TK_NOTNULL );
79073 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79074 sqlite3VdbeAddOp2(v, op, r1, dest);
79075 testcase( regFree1==0 );
79076 break;
79078 case TK_BETWEEN: {
79079 testcase( jumpIfNull==0 );
79080 exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
79081 break;
79083 #ifndef SQLITE_OMIT_SUBQUERY
79084 case TK_IN: {
79085 int destIfFalse = sqlite3VdbeMakeLabel(v);
79086 int destIfNull = jumpIfNull ? dest : destIfFalse;
79087 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
79088 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
79089 sqlite3VdbeResolveLabel(v, destIfFalse);
79090 break;
79092 #endif
79093 default: {
79094 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
79095 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
79096 testcase( regFree1==0 );
79097 testcase( jumpIfNull==0 );
79098 break;
79101 sqlite3ReleaseTempReg(pParse, regFree1);
79102 sqlite3ReleaseTempReg(pParse, regFree2);
79106 ** Generate code for a boolean expression such that a jump is made
79107 ** to the label "dest" if the expression is false but execution
79108 ** continues straight thru if the expression is true.
79110 ** If the expression evaluates to NULL (neither true nor false) then
79111 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
79112 ** is 0.
79114 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
79115 Vdbe *v = pParse->pVdbe;
79116 int op = 0;
79117 int regFree1 = 0;
79118 int regFree2 = 0;
79119 int r1, r2;
79121 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
79122 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
79123 if( pExpr==0 ) return;
79125 /* The value of pExpr->op and op are related as follows:
79127 ** pExpr->op op
79128 ** --------- ----------
79129 ** TK_ISNULL OP_NotNull
79130 ** TK_NOTNULL OP_IsNull
79131 ** TK_NE OP_Eq
79132 ** TK_EQ OP_Ne
79133 ** TK_GT OP_Le
79134 ** TK_LE OP_Gt
79135 ** TK_GE OP_Lt
79136 ** TK_LT OP_Ge
79138 ** For other values of pExpr->op, op is undefined and unused.
79139 ** The value of TK_ and OP_ constants are arranged such that we
79140 ** can compute the mapping above using the following expression.
79141 ** Assert()s verify that the computation is correct.
79143 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
79145 /* Verify correct alignment of TK_ and OP_ constants
79147 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
79148 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
79149 assert( pExpr->op!=TK_NE || op==OP_Eq );
79150 assert( pExpr->op!=TK_EQ || op==OP_Ne );
79151 assert( pExpr->op!=TK_LT || op==OP_Ge );
79152 assert( pExpr->op!=TK_LE || op==OP_Gt );
79153 assert( pExpr->op!=TK_GT || op==OP_Le );
79154 assert( pExpr->op!=TK_GE || op==OP_Lt );
79156 switch( pExpr->op ){
79157 case TK_AND: {
79158 testcase( jumpIfNull==0 );
79159 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
79160 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
79161 break;
79163 case TK_OR: {
79164 int d2 = sqlite3VdbeMakeLabel(v);
79165 testcase( jumpIfNull==0 );
79166 sqlite3ExprCachePush(pParse);
79167 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
79168 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
79169 sqlite3VdbeResolveLabel(v, d2);
79170 sqlite3ExprCachePop(pParse, 1);
79171 break;
79173 case TK_NOT: {
79174 testcase( jumpIfNull==0 );
79175 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
79176 break;
79178 case TK_LT:
79179 case TK_LE:
79180 case TK_GT:
79181 case TK_GE:
79182 case TK_NE:
79183 case TK_EQ: {
79184 testcase( op==TK_LT );
79185 testcase( op==TK_LE );
79186 testcase( op==TK_GT );
79187 testcase( op==TK_GE );
79188 testcase( op==TK_EQ );
79189 testcase( op==TK_NE );
79190 testcase( jumpIfNull==0 );
79191 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79192 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79193 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
79194 r1, r2, dest, jumpIfNull);
79195 testcase( regFree1==0 );
79196 testcase( regFree2==0 );
79197 break;
79199 case TK_IS:
79200 case TK_ISNOT: {
79201 testcase( pExpr->op==TK_IS );
79202 testcase( pExpr->op==TK_ISNOT );
79203 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79204 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79205 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
79206 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
79207 r1, r2, dest, SQLITE_NULLEQ);
79208 testcase( regFree1==0 );
79209 testcase( regFree2==0 );
79210 break;
79212 case TK_ISNULL:
79213 case TK_NOTNULL: {
79214 testcase( op==TK_ISNULL );
79215 testcase( op==TK_NOTNULL );
79216 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79217 sqlite3VdbeAddOp2(v, op, r1, dest);
79218 testcase( regFree1==0 );
79219 break;
79221 case TK_BETWEEN: {
79222 testcase( jumpIfNull==0 );
79223 exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
79224 break;
79226 #ifndef SQLITE_OMIT_SUBQUERY
79227 case TK_IN: {
79228 if( jumpIfNull ){
79229 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
79230 }else{
79231 int destIfNull = sqlite3VdbeMakeLabel(v);
79232 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
79233 sqlite3VdbeResolveLabel(v, destIfNull);
79235 break;
79237 #endif
79238 default: {
79239 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
79240 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
79241 testcase( regFree1==0 );
79242 testcase( jumpIfNull==0 );
79243 break;
79246 sqlite3ReleaseTempReg(pParse, regFree1);
79247 sqlite3ReleaseTempReg(pParse, regFree2);
79251 ** Do a deep comparison of two expression trees. Return 0 if the two
79252 ** expressions are completely identical. Return 1 if they differ only
79253 ** by a COLLATE operator at the top level. Return 2 if there are differences
79254 ** other than the top-level COLLATE operator.
79256 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
79257 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
79259 ** The pA side might be using TK_REGISTER. If that is the case and pB is
79260 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
79262 ** Sometimes this routine will return 2 even if the two expressions
79263 ** really are equivalent. If we cannot prove that the expressions are
79264 ** identical, we return 2 just to be safe. So if this routine
79265 ** returns 2, then you do not really know for certain if the two
79266 ** expressions are the same. But if you get a 0 or 1 return, then you
79267 ** can be sure the expressions are the same. In the places where
79268 ** this routine is used, it does not hurt to get an extra 2 - that
79269 ** just might result in some slightly slower code. But returning
79270 ** an incorrect 0 or 1 could lead to a malfunction.
79272 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
79273 if( pA==0||pB==0 ){
79274 return pB==pA ? 0 : 2;
79276 assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
79277 assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
79278 if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
79279 return 2;
79281 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
79282 if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){
79283 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
79284 return 1;
79286 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
79287 return 1;
79289 return 2;
79291 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
79292 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
79293 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
79294 if( pA->iColumn!=pB->iColumn ) return 2;
79295 if( pA->iTable!=pB->iTable
79296 && pA->op!=TK_REGISTER
79297 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
79298 if( ExprHasProperty(pA, EP_IntValue) ){
79299 if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
79300 return 2;
79302 }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
79303 if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
79304 if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
79305 return pA->op==TK_COLLATE ? 1 : 2;
79308 return 0;
79312 ** Compare two ExprList objects. Return 0 if they are identical and
79313 ** non-zero if they differ in any way.
79315 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
79316 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
79318 ** This routine might return non-zero for equivalent ExprLists. The
79319 ** only consequence will be disabled optimizations. But this routine
79320 ** must never return 0 if the two ExprList objects are different, or
79321 ** a malfunction will result.
79323 ** Two NULL pointers are considered to be the same. But a NULL pointer
79324 ** always differs from a non-NULL pointer.
79326 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
79327 int i;
79328 if( pA==0 && pB==0 ) return 0;
79329 if( pA==0 || pB==0 ) return 1;
79330 if( pA->nExpr!=pB->nExpr ) return 1;
79331 for(i=0; i<pA->nExpr; i++){
79332 Expr *pExprA = pA->a[i].pExpr;
79333 Expr *pExprB = pB->a[i].pExpr;
79334 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
79335 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
79337 return 0;
79341 ** Return true if we can prove the pE2 will always be true if pE1 is
79342 ** true. Return false if we cannot complete the proof or if pE2 might
79343 ** be false. Examples:
79345 ** pE1: x==5 pE2: x==5 Result: true
79346 ** pE1: x>0 pE2: x==5 Result: false
79347 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
79348 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
79349 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
79350 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
79351 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
79353 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
79354 ** Expr.iTable<0 then assume a table number given by iTab.
79356 ** When in doubt, return false. Returning true might give a performance
79357 ** improvement. Returning false might cause a performance reduction, but
79358 ** it will always give the correct answer and is hence always safe.
79360 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
79361 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
79362 return 1;
79364 if( pE2->op==TK_OR
79365 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
79366 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
79368 return 1;
79370 if( pE2->op==TK_NOTNULL
79371 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
79372 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
79374 return 1;
79376 return 0;
79380 ** An instance of the following structure is used by the tree walker
79381 ** to count references to table columns in the arguments of an
79382 ** aggregate function, in order to implement the
79383 ** sqlite3FunctionThisSrc() routine.
79385 struct SrcCount {
79386 SrcList *pSrc; /* One particular FROM clause in a nested query */
79387 int nThis; /* Number of references to columns in pSrcList */
79388 int nOther; /* Number of references to columns in other FROM clauses */
79392 ** Count the number of references to columns.
79394 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
79395 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
79396 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
79397 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
79398 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
79399 ** NEVER() will need to be removed. */
79400 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
79401 int i;
79402 struct SrcCount *p = pWalker->u.pSrcCount;
79403 SrcList *pSrc = p->pSrc;
79404 for(i=0; i<pSrc->nSrc; i++){
79405 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
79407 if( i<pSrc->nSrc ){
79408 p->nThis++;
79409 }else{
79410 p->nOther++;
79413 return WRC_Continue;
79417 ** Determine if any of the arguments to the pExpr Function reference
79418 ** pSrcList. Return true if they do. Also return true if the function
79419 ** has no arguments or has only constant arguments. Return false if pExpr
79420 ** references columns but not columns of tables found in pSrcList.
79422 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
79423 Walker w;
79424 struct SrcCount cnt;
79425 assert( pExpr->op==TK_AGG_FUNCTION );
79426 memset(&w, 0, sizeof(w));
79427 w.xExprCallback = exprSrcCount;
79428 w.u.pSrcCount = &cnt;
79429 cnt.pSrc = pSrcList;
79430 cnt.nThis = 0;
79431 cnt.nOther = 0;
79432 sqlite3WalkExprList(&w, pExpr->x.pList);
79433 return cnt.nThis>0 || cnt.nOther==0;
79437 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
79438 ** the new element. Return a negative number if malloc fails.
79440 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
79441 int i;
79442 pInfo->aCol = sqlite3ArrayAllocate(
79444 pInfo->aCol,
79445 sizeof(pInfo->aCol[0]),
79446 &pInfo->nColumn,
79449 return i;
79453 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
79454 ** the new element. Return a negative number if malloc fails.
79456 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
79457 int i;
79458 pInfo->aFunc = sqlite3ArrayAllocate(
79459 db,
79460 pInfo->aFunc,
79461 sizeof(pInfo->aFunc[0]),
79462 &pInfo->nFunc,
79465 return i;
79469 ** This is the xExprCallback for a tree walker. It is used to
79470 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
79471 ** for additional information.
79473 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
79474 int i;
79475 NameContext *pNC = pWalker->u.pNC;
79476 Parse *pParse = pNC->pParse;
79477 SrcList *pSrcList = pNC->pSrcList;
79478 AggInfo *pAggInfo = pNC->pAggInfo;
79480 switch( pExpr->op ){
79481 case TK_AGG_COLUMN:
79482 case TK_COLUMN: {
79483 testcase( pExpr->op==TK_AGG_COLUMN );
79484 testcase( pExpr->op==TK_COLUMN );
79485 /* Check to see if the column is in one of the tables in the FROM
79486 ** clause of the aggregate query */
79487 if( ALWAYS(pSrcList!=0) ){
79488 struct SrcList_item *pItem = pSrcList->a;
79489 for(i=0; i<pSrcList->nSrc; i++, pItem++){
79490 struct AggInfo_col *pCol;
79491 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79492 if( pExpr->iTable==pItem->iCursor ){
79493 /* If we reach this point, it means that pExpr refers to a table
79494 ** that is in the FROM clause of the aggregate query.
79496 ** Make an entry for the column in pAggInfo->aCol[] if there
79497 ** is not an entry there already.
79499 int k;
79500 pCol = pAggInfo->aCol;
79501 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
79502 if( pCol->iTable==pExpr->iTable &&
79503 pCol->iColumn==pExpr->iColumn ){
79504 break;
79507 if( (k>=pAggInfo->nColumn)
79508 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
79510 pCol = &pAggInfo->aCol[k];
79511 pCol->pTab = pExpr->pTab;
79512 pCol->iTable = pExpr->iTable;
79513 pCol->iColumn = pExpr->iColumn;
79514 pCol->iMem = ++pParse->nMem;
79515 pCol->iSorterColumn = -1;
79516 pCol->pExpr = pExpr;
79517 if( pAggInfo->pGroupBy ){
79518 int j, n;
79519 ExprList *pGB = pAggInfo->pGroupBy;
79520 struct ExprList_item *pTerm = pGB->a;
79521 n = pGB->nExpr;
79522 for(j=0; j<n; j++, pTerm++){
79523 Expr *pE = pTerm->pExpr;
79524 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
79525 pE->iColumn==pExpr->iColumn ){
79526 pCol->iSorterColumn = j;
79527 break;
79531 if( pCol->iSorterColumn<0 ){
79532 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
79535 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
79536 ** because it was there before or because we just created it).
79537 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
79538 ** pAggInfo->aCol[] entry.
79540 ExprSetIrreducible(pExpr);
79541 pExpr->pAggInfo = pAggInfo;
79542 pExpr->op = TK_AGG_COLUMN;
79543 pExpr->iAgg = (i16)k;
79544 break;
79545 } /* endif pExpr->iTable==pItem->iCursor */
79546 } /* end loop over pSrcList */
79548 return WRC_Prune;
79550 case TK_AGG_FUNCTION: {
79551 if( (pNC->ncFlags & NC_InAggFunc)==0
79552 && pWalker->walkerDepth==pExpr->op2
79554 /* Check to see if pExpr is a duplicate of another aggregate
79555 ** function that is already in the pAggInfo structure
79557 struct AggInfo_func *pItem = pAggInfo->aFunc;
79558 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
79559 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
79560 break;
79563 if( i>=pAggInfo->nFunc ){
79564 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
79566 u8 enc = ENC(pParse->db);
79567 i = addAggInfoFunc(pParse->db, pAggInfo);
79568 if( i>=0 ){
79569 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79570 pItem = &pAggInfo->aFunc[i];
79571 pItem->pExpr = pExpr;
79572 pItem->iMem = ++pParse->nMem;
79573 assert( !ExprHasProperty(pExpr, EP_IntValue) );
79574 pItem->pFunc = sqlite3FindFunction(pParse->db,
79575 pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
79576 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
79577 if( pExpr->flags & EP_Distinct ){
79578 pItem->iDistinct = pParse->nTab++;
79579 }else{
79580 pItem->iDistinct = -1;
79584 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
79586 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79587 ExprSetIrreducible(pExpr);
79588 pExpr->iAgg = (i16)i;
79589 pExpr->pAggInfo = pAggInfo;
79590 return WRC_Prune;
79591 }else{
79592 return WRC_Continue;
79596 return WRC_Continue;
79598 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
79599 UNUSED_PARAMETER(pWalker);
79600 UNUSED_PARAMETER(pSelect);
79601 return WRC_Continue;
79605 ** Analyze the pExpr expression looking for aggregate functions and
79606 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
79607 ** points to. Additional entries are made on the AggInfo object as
79608 ** necessary.
79610 ** This routine should only be called after the expression has been
79611 ** analyzed by sqlite3ResolveExprNames().
79613 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
79614 Walker w;
79615 memset(&w, 0, sizeof(w));
79616 w.xExprCallback = analyzeAggregate;
79617 w.xSelectCallback = analyzeAggregatesInSelect;
79618 w.u.pNC = pNC;
79619 assert( pNC->pSrcList!=0 );
79620 sqlite3WalkExpr(&w, pExpr);
79624 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
79625 ** expression list. Return the number of errors.
79627 ** If an error is found, the analysis is cut short.
79629 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
79630 struct ExprList_item *pItem;
79631 int i;
79632 if( pList ){
79633 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
79634 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
79640 ** Allocate a single new register for use to hold some intermediate result.
79642 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
79643 if( pParse->nTempReg==0 ){
79644 return ++pParse->nMem;
79646 return pParse->aTempReg[--pParse->nTempReg];
79650 ** Deallocate a register, making available for reuse for some other
79651 ** purpose.
79653 ** If a register is currently being used by the column cache, then
79654 ** the dallocation is deferred until the column cache line that uses
79655 ** the register becomes stale.
79657 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
79658 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
79659 int i;
79660 struct yColCache *p;
79661 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79662 if( p->iReg==iReg ){
79663 p->tempReg = 1;
79664 return;
79667 pParse->aTempReg[pParse->nTempReg++] = iReg;
79672 ** Allocate or deallocate a block of nReg consecutive registers
79674 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
79675 int i, n;
79676 i = pParse->iRangeReg;
79677 n = pParse->nRangeReg;
79678 if( nReg<=n ){
79679 assert( !usedAsColumnCache(pParse, i, i+n-1) );
79680 pParse->iRangeReg += nReg;
79681 pParse->nRangeReg -= nReg;
79682 }else{
79683 i = pParse->nMem+1;
79684 pParse->nMem += nReg;
79686 return i;
79688 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
79689 sqlite3ExprCacheRemove(pParse, iReg, nReg);
79690 if( nReg>pParse->nRangeReg ){
79691 pParse->nRangeReg = nReg;
79692 pParse->iRangeReg = iReg;
79697 ** Mark all temporary registers as being unavailable for reuse.
79699 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
79700 pParse->nTempReg = 0;
79701 pParse->nRangeReg = 0;
79704 /************** End of expr.c ************************************************/
79705 /************** Begin file alter.c *******************************************/
79707 ** 2005 February 15
79709 ** The author disclaims copyright to this source code. In place of
79710 ** a legal notice, here is a blessing:
79712 ** May you do good and not evil.
79713 ** May you find forgiveness for yourself and forgive others.
79714 ** May you share freely, never taking more than you give.
79716 *************************************************************************
79717 ** This file contains C code routines that used to generate VDBE code
79718 ** that implements the ALTER TABLE command.
79722 ** The code in this file only exists if we are not omitting the
79723 ** ALTER TABLE logic from the build.
79725 #ifndef SQLITE_OMIT_ALTERTABLE
79729 ** This function is used by SQL generated to implement the
79730 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
79731 ** CREATE INDEX command. The second is a table name. The table name in
79732 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
79733 ** argument and the result returned. Examples:
79735 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
79736 ** -> 'CREATE TABLE def(a, b, c)'
79738 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
79739 ** -> 'CREATE INDEX i ON def(a, b, c)'
79741 static void renameTableFunc(
79742 sqlite3_context *context,
79743 int NotUsed,
79744 sqlite3_value **argv
79746 unsigned char const *zSql = sqlite3_value_text(argv[0]);
79747 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
79749 int token;
79750 Token tname;
79751 unsigned char const *zCsr = zSql;
79752 int len = 0;
79753 char *zRet;
79755 sqlite3 *db = sqlite3_context_db_handle(context);
79757 UNUSED_PARAMETER(NotUsed);
79759 /* The principle used to locate the table name in the CREATE TABLE
79760 ** statement is that the table name is the first non-space token that
79761 ** is immediately followed by a TK_LP or TK_USING token.
79763 if( zSql ){
79764 do {
79765 if( !*zCsr ){
79766 /* Ran out of input before finding an opening bracket. Return NULL. */
79767 return;
79770 /* Store the token that zCsr points to in tname. */
79771 tname.z = (char*)zCsr;
79772 tname.n = len;
79774 /* Advance zCsr to the next token. Store that token type in 'token',
79775 ** and its length in 'len' (to be used next iteration of this loop).
79777 do {
79778 zCsr += len;
79779 len = sqlite3GetToken(zCsr, &token);
79780 } while( token==TK_SPACE );
79781 assert( len>0 );
79782 } while( token!=TK_LP && token!=TK_USING );
79784 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
79785 zTableName, tname.z+tname.n);
79786 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
79791 ** This C function implements an SQL user function that is used by SQL code
79792 ** generated by the ALTER TABLE ... RENAME command to modify the definition
79793 ** of any foreign key constraints that use the table being renamed as the
79794 ** parent table. It is passed three arguments:
79796 ** 1) The complete text of the CREATE TABLE statement being modified,
79797 ** 2) The old name of the table being renamed, and
79798 ** 3) The new name of the table being renamed.
79800 ** It returns the new CREATE TABLE statement. For example:
79802 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
79803 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
79805 #ifndef SQLITE_OMIT_FOREIGN_KEY
79806 static void renameParentFunc(
79807 sqlite3_context *context,
79808 int NotUsed,
79809 sqlite3_value **argv
79811 sqlite3 *db = sqlite3_context_db_handle(context);
79812 char *zOutput = 0;
79813 char *zResult;
79814 unsigned char const *zInput = sqlite3_value_text(argv[0]);
79815 unsigned char const *zOld = sqlite3_value_text(argv[1]);
79816 unsigned char const *zNew = sqlite3_value_text(argv[2]);
79818 unsigned const char *z; /* Pointer to token */
79819 int n; /* Length of token z */
79820 int token; /* Type of token */
79822 UNUSED_PARAMETER(NotUsed);
79823 for(z=zInput; *z; z=z+n){
79824 n = sqlite3GetToken(z, &token);
79825 if( token==TK_REFERENCES ){
79826 char *zParent;
79827 do {
79828 z += n;
79829 n = sqlite3GetToken(z, &token);
79830 }while( token==TK_SPACE );
79832 zParent = sqlite3DbStrNDup(db, (const char *)z, n);
79833 if( zParent==0 ) break;
79834 sqlite3Dequote(zParent);
79835 if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
79836 char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
79837 (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
79839 sqlite3DbFree(db, zOutput);
79840 zOutput = zOut;
79841 zInput = &z[n];
79843 sqlite3DbFree(db, zParent);
79847 zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
79848 sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
79849 sqlite3DbFree(db, zOutput);
79851 #endif
79853 #ifndef SQLITE_OMIT_TRIGGER
79854 /* This function is used by SQL generated to implement the
79855 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
79856 ** statement. The second is a table name. The table name in the CREATE
79857 ** TRIGGER statement is replaced with the third argument and the result
79858 ** returned. This is analagous to renameTableFunc() above, except for CREATE
79859 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
79861 static void renameTriggerFunc(
79862 sqlite3_context *context,
79863 int NotUsed,
79864 sqlite3_value **argv
79866 unsigned char const *zSql = sqlite3_value_text(argv[0]);
79867 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
79869 int token;
79870 Token tname;
79871 int dist = 3;
79872 unsigned char const *zCsr = zSql;
79873 int len = 0;
79874 char *zRet;
79875 sqlite3 *db = sqlite3_context_db_handle(context);
79877 UNUSED_PARAMETER(NotUsed);
79879 /* The principle used to locate the table name in the CREATE TRIGGER
79880 ** statement is that the table name is the first token that is immediatedly
79881 ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
79882 ** of TK_WHEN, TK_BEGIN or TK_FOR.
79884 if( zSql ){
79885 do {
79887 if( !*zCsr ){
79888 /* Ran out of input before finding the table name. Return NULL. */
79889 return;
79892 /* Store the token that zCsr points to in tname. */
79893 tname.z = (char*)zCsr;
79894 tname.n = len;
79896 /* Advance zCsr to the next token. Store that token type in 'token',
79897 ** and its length in 'len' (to be used next iteration of this loop).
79899 do {
79900 zCsr += len;
79901 len = sqlite3GetToken(zCsr, &token);
79902 }while( token==TK_SPACE );
79903 assert( len>0 );
79905 /* Variable 'dist' stores the number of tokens read since the most
79906 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
79907 ** token is read and 'dist' equals 2, the condition stated above
79908 ** to be met.
79910 ** Note that ON cannot be a database, table or column name, so
79911 ** there is no need to worry about syntax like
79912 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
79914 dist++;
79915 if( token==TK_DOT || token==TK_ON ){
79916 dist = 0;
79918 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
79920 /* Variable tname now contains the token that is the old table-name
79921 ** in the CREATE TRIGGER statement.
79923 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
79924 zTableName, tname.z+tname.n);
79925 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
79928 #endif /* !SQLITE_OMIT_TRIGGER */
79931 ** Register built-in functions used to help implement ALTER TABLE
79933 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
79934 static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
79935 FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
79936 #ifndef SQLITE_OMIT_TRIGGER
79937 FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
79938 #endif
79939 #ifndef SQLITE_OMIT_FOREIGN_KEY
79940 FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
79941 #endif
79943 int i;
79944 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
79945 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
79947 for(i=0; i<ArraySize(aAlterTableFuncs); i++){
79948 sqlite3FuncDefInsert(pHash, &aFunc[i]);
79953 ** This function is used to create the text of expressions of the form:
79955 ** name=<constant1> OR name=<constant2> OR ...
79957 ** If argument zWhere is NULL, then a pointer string containing the text
79958 ** "name=<constant>" is returned, where <constant> is the quoted version
79959 ** of the string passed as argument zConstant. The returned buffer is
79960 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
79961 ** caller to ensure that it is eventually freed.
79963 ** If argument zWhere is not NULL, then the string returned is
79964 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
79965 ** In this case zWhere is passed to sqlite3DbFree() before returning.
79968 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
79969 char *zNew;
79970 if( !zWhere ){
79971 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
79972 }else{
79973 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
79974 sqlite3DbFree(db, zWhere);
79976 return zNew;
79979 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79981 ** Generate the text of a WHERE expression which can be used to select all
79982 ** tables that have foreign key constraints that refer to table pTab (i.e.
79983 ** constraints for which pTab is the parent table) from the sqlite_master
79984 ** table.
79986 static char *whereForeignKeys(Parse *pParse, Table *pTab){
79987 FKey *p;
79988 char *zWhere = 0;
79989 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79990 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
79992 return zWhere;
79994 #endif
79997 ** Generate the text of a WHERE expression which can be used to select all
79998 ** temporary triggers on table pTab from the sqlite_temp_master table. If
79999 ** table pTab has no temporary triggers, or is itself stored in the
80000 ** temporary database, NULL is returned.
80002 static char *whereTempTriggers(Parse *pParse, Table *pTab){
80003 Trigger *pTrig;
80004 char *zWhere = 0;
80005 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
80007 /* If the table is not located in the temp-db (in which case NULL is
80008 ** returned, loop through the tables list of triggers. For each trigger
80009 ** that is not part of the temp-db schema, add a clause to the WHERE
80010 ** expression being built up in zWhere.
80012 if( pTab->pSchema!=pTempSchema ){
80013 sqlite3 *db = pParse->db;
80014 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
80015 if( pTrig->pSchema==pTempSchema ){
80016 zWhere = whereOrName(db, zWhere, pTrig->zName);
80020 if( zWhere ){
80021 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
80022 sqlite3DbFree(pParse->db, zWhere);
80023 zWhere = zNew;
80025 return zWhere;
80029 ** Generate code to drop and reload the internal representation of table
80030 ** pTab from the database, including triggers and temporary triggers.
80031 ** Argument zName is the name of the table in the database schema at
80032 ** the time the generated code is executed. This can be different from
80033 ** pTab->zName if this function is being called to code part of an
80034 ** "ALTER TABLE RENAME TO" statement.
80036 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
80037 Vdbe *v;
80038 char *zWhere;
80039 int iDb; /* Index of database containing pTab */
80040 #ifndef SQLITE_OMIT_TRIGGER
80041 Trigger *pTrig;
80042 #endif
80044 v = sqlite3GetVdbe(pParse);
80045 if( NEVER(v==0) ) return;
80046 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
80047 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80048 assert( iDb>=0 );
80050 #ifndef SQLITE_OMIT_TRIGGER
80051 /* Drop any table triggers from the internal schema. */
80052 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
80053 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
80054 assert( iTrigDb==iDb || iTrigDb==1 );
80055 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
80057 #endif
80059 /* Drop the table and index from the internal schema. */
80060 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
80062 /* Reload the table, index and permanent trigger schemas. */
80063 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
80064 if( !zWhere ) return;
80065 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
80067 #ifndef SQLITE_OMIT_TRIGGER
80068 /* Now, if the table is not stored in the temp database, reload any temp
80069 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
80071 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
80072 sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
80074 #endif
80078 ** Parameter zName is the name of a table that is about to be altered
80079 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
80080 ** If the table is a system table, this function leaves an error message
80081 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
80083 ** Or, if zName is not a system table, zero is returned.
80085 static int isSystemTable(Parse *pParse, const char *zName){
80086 if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
80087 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
80088 return 1;
80090 return 0;
80094 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
80095 ** command.
80097 SQLITE_PRIVATE void sqlite3AlterRenameTable(
80098 Parse *pParse, /* Parser context. */
80099 SrcList *pSrc, /* The table to rename. */
80100 Token *pName /* The new table name. */
80102 int iDb; /* Database that contains the table */
80103 char *zDb; /* Name of database iDb */
80104 Table *pTab; /* Table being renamed */
80105 char *zName = 0; /* NULL-terminated version of pName */
80106 sqlite3 *db = pParse->db; /* Database connection */
80107 int nTabName; /* Number of UTF-8 characters in zTabName */
80108 const char *zTabName; /* Original name of the table */
80109 Vdbe *v;
80110 #ifndef SQLITE_OMIT_TRIGGER
80111 char *zWhere = 0; /* Where clause to locate temp triggers */
80112 #endif
80113 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
80114 int savedDbFlags; /* Saved value of db->flags */
80116 savedDbFlags = db->flags;
80117 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
80118 assert( pSrc->nSrc==1 );
80119 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
80121 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
80122 if( !pTab ) goto exit_rename_table;
80123 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80124 zDb = db->aDb[iDb].zName;
80125 db->flags |= SQLITE_PreferBuiltin;
80127 /* Get a NULL terminated version of the new table name. */
80128 zName = sqlite3NameFromToken(db, pName);
80129 if( !zName ) goto exit_rename_table;
80131 /* Check that a table or index named 'zName' does not already exist
80132 ** in database iDb. If so, this is an error.
80134 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
80135 sqlite3ErrorMsg(pParse,
80136 "there is already another table or index with this name: %s", zName);
80137 goto exit_rename_table;
80140 /* Make sure it is not a system table being altered, or a reserved name
80141 ** that the table is being renamed to.
80143 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
80144 goto exit_rename_table;
80146 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
80147 exit_rename_table;
80150 #ifndef SQLITE_OMIT_VIEW
80151 if( pTab->pSelect ){
80152 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
80153 goto exit_rename_table;
80155 #endif
80157 #ifndef SQLITE_OMIT_AUTHORIZATION
80158 /* Invoke the authorization callback. */
80159 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
80160 goto exit_rename_table;
80162 #endif
80164 #ifndef SQLITE_OMIT_VIRTUALTABLE
80165 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
80166 goto exit_rename_table;
80168 if( IsVirtual(pTab) ){
80169 pVTab = sqlite3GetVTable(db, pTab);
80170 if( pVTab->pVtab->pModule->xRename==0 ){
80171 pVTab = 0;
80174 #endif
80176 /* Begin a transaction and code the VerifyCookie for database iDb.
80177 ** Then modify the schema cookie (since the ALTER TABLE modifies the
80178 ** schema). Open a statement transaction if the table is a virtual
80179 ** table.
80181 v = sqlite3GetVdbe(pParse);
80182 if( v==0 ){
80183 goto exit_rename_table;
80185 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
80186 sqlite3ChangeCookie(pParse, iDb);
80188 /* If this is a virtual table, invoke the xRename() function if
80189 ** one is defined. The xRename() callback will modify the names
80190 ** of any resources used by the v-table implementation (including other
80191 ** SQLite tables) that are identified by the name of the virtual table.
80193 #ifndef SQLITE_OMIT_VIRTUALTABLE
80194 if( pVTab ){
80195 int i = ++pParse->nMem;
80196 sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
80197 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
80198 sqlite3MayAbort(pParse);
80200 #endif
80202 /* figure out how many UTF-8 characters are in zName */
80203 zTabName = pTab->zName;
80204 nTabName = sqlite3Utf8CharLen(zTabName, -1);
80206 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
80207 if( db->flags&SQLITE_ForeignKeys ){
80208 /* If foreign-key support is enabled, rewrite the CREATE TABLE
80209 ** statements corresponding to all child tables of foreign key constraints
80210 ** for which the renamed table is the parent table. */
80211 if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
80212 sqlite3NestedParse(pParse,
80213 "UPDATE \"%w\".%s SET "
80214 "sql = sqlite_rename_parent(sql, %Q, %Q) "
80215 "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
80216 sqlite3DbFree(db, zWhere);
80219 #endif
80221 /* Modify the sqlite_master table to use the new table name. */
80222 sqlite3NestedParse(pParse,
80223 "UPDATE %Q.%s SET "
80224 #ifdef SQLITE_OMIT_TRIGGER
80225 "sql = sqlite_rename_table(sql, %Q), "
80226 #else
80227 "sql = CASE "
80228 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
80229 "ELSE sqlite_rename_table(sql, %Q) END, "
80230 #endif
80231 "tbl_name = %Q, "
80232 "name = CASE "
80233 "WHEN type='table' THEN %Q "
80234 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
80235 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
80236 "ELSE name END "
80237 "WHERE tbl_name=%Q COLLATE nocase AND "
80238 "(type='table' OR type='index' OR type='trigger');",
80239 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
80240 #ifndef SQLITE_OMIT_TRIGGER
80241 zName,
80242 #endif
80243 zName, nTabName, zTabName
80246 #ifndef SQLITE_OMIT_AUTOINCREMENT
80247 /* If the sqlite_sequence table exists in this database, then update
80248 ** it with the new table name.
80250 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
80251 sqlite3NestedParse(pParse,
80252 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
80253 zDb, zName, pTab->zName);
80255 #endif
80257 #ifndef SQLITE_OMIT_TRIGGER
80258 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
80259 ** table. Don't do this if the table being ALTERed is itself located in
80260 ** the temp database.
80262 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
80263 sqlite3NestedParse(pParse,
80264 "UPDATE sqlite_temp_master SET "
80265 "sql = sqlite_rename_trigger(sql, %Q), "
80266 "tbl_name = %Q "
80267 "WHERE %s;", zName, zName, zWhere);
80268 sqlite3DbFree(db, zWhere);
80270 #endif
80272 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
80273 if( db->flags&SQLITE_ForeignKeys ){
80274 FKey *p;
80275 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
80276 Table *pFrom = p->pFrom;
80277 if( pFrom!=pTab ){
80278 reloadTableSchema(pParse, p->pFrom, pFrom->zName);
80282 #endif
80284 /* Drop and reload the internal table schema. */
80285 reloadTableSchema(pParse, pTab, zName);
80287 exit_rename_table:
80288 sqlite3SrcListDelete(db, pSrc);
80289 sqlite3DbFree(db, zName);
80290 db->flags = savedDbFlags;
80295 ** Generate code to make sure the file format number is at least minFormat.
80296 ** The generated code will increase the file format number if necessary.
80298 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
80299 Vdbe *v;
80300 v = sqlite3GetVdbe(pParse);
80301 /* The VDBE should have been allocated before this routine is called.
80302 ** If that allocation failed, we would have quit before reaching this
80303 ** point */
80304 if( ALWAYS(v) ){
80305 int r1 = sqlite3GetTempReg(pParse);
80306 int r2 = sqlite3GetTempReg(pParse);
80307 int j1;
80308 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
80309 sqlite3VdbeUsesBtree(v, iDb);
80310 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
80311 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
80312 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
80313 sqlite3VdbeJumpHere(v, j1);
80314 sqlite3ReleaseTempReg(pParse, r1);
80315 sqlite3ReleaseTempReg(pParse, r2);
80320 ** This function is called after an "ALTER TABLE ... ADD" statement
80321 ** has been parsed. Argument pColDef contains the text of the new
80322 ** column definition.
80324 ** The Table structure pParse->pNewTable was extended to include
80325 ** the new column during parsing.
80327 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
80328 Table *pNew; /* Copy of pParse->pNewTable */
80329 Table *pTab; /* Table being altered */
80330 int iDb; /* Database number */
80331 const char *zDb; /* Database name */
80332 const char *zTab; /* Table name */
80333 char *zCol; /* Null-terminated column definition */
80334 Column *pCol; /* The new column */
80335 Expr *pDflt; /* Default value for the new column */
80336 sqlite3 *db; /* The database connection; */
80338 db = pParse->db;
80339 if( pParse->nErr || db->mallocFailed ) return;
80340 pNew = pParse->pNewTable;
80341 assert( pNew );
80343 assert( sqlite3BtreeHoldsAllMutexes(db) );
80344 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
80345 zDb = db->aDb[iDb].zName;
80346 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
80347 pCol = &pNew->aCol[pNew->nCol-1];
80348 pDflt = pCol->pDflt;
80349 pTab = sqlite3FindTable(db, zTab, zDb);
80350 assert( pTab );
80352 #ifndef SQLITE_OMIT_AUTHORIZATION
80353 /* Invoke the authorization callback. */
80354 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
80355 return;
80357 #endif
80359 /* If the default value for the new column was specified with a
80360 ** literal NULL, then set pDflt to 0. This simplifies checking
80361 ** for an SQL NULL default below.
80363 if( pDflt && pDflt->op==TK_NULL ){
80364 pDflt = 0;
80367 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
80368 ** If there is a NOT NULL constraint, then the default value for the
80369 ** column must not be NULL.
80371 if( pCol->colFlags & COLFLAG_PRIMKEY ){
80372 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
80373 return;
80375 if( pNew->pIndex ){
80376 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
80377 return;
80379 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
80380 sqlite3ErrorMsg(pParse,
80381 "Cannot add a REFERENCES column with non-NULL default value");
80382 return;
80384 if( pCol->notNull && !pDflt ){
80385 sqlite3ErrorMsg(pParse,
80386 "Cannot add a NOT NULL column with default value NULL");
80387 return;
80390 /* Ensure the default expression is something that sqlite3ValueFromExpr()
80391 ** can handle (i.e. not CURRENT_TIME etc.)
80393 if( pDflt ){
80394 sqlite3_value *pVal;
80395 if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
80396 db->mallocFailed = 1;
80397 return;
80399 if( !pVal ){
80400 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
80401 return;
80403 sqlite3ValueFree(pVal);
80406 /* Modify the CREATE TABLE statement. */
80407 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
80408 if( zCol ){
80409 char *zEnd = &zCol[pColDef->n-1];
80410 int savedDbFlags = db->flags;
80411 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
80412 *zEnd-- = '\0';
80414 db->flags |= SQLITE_PreferBuiltin;
80415 sqlite3NestedParse(pParse,
80416 "UPDATE \"%w\".%s SET "
80417 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
80418 "WHERE type = 'table' AND name = %Q",
80419 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
80420 zTab
80422 sqlite3DbFree(db, zCol);
80423 db->flags = savedDbFlags;
80426 /* If the default value of the new column is NULL, then set the file
80427 ** format to 2. If the default value of the new column is not NULL,
80428 ** the file format becomes 3.
80430 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
80432 /* Reload the schema of the modified table. */
80433 reloadTableSchema(pParse, pTab, pTab->zName);
80437 ** This function is called by the parser after the table-name in
80438 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
80439 ** pSrc is the full-name of the table being altered.
80441 ** This routine makes a (partial) copy of the Table structure
80442 ** for the table being altered and sets Parse.pNewTable to point
80443 ** to it. Routines called by the parser as the column definition
80444 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
80445 ** the copy. The copy of the Table structure is deleted by tokenize.c
80446 ** after parsing is finished.
80448 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
80449 ** coding the "ALTER TABLE ... ADD" statement.
80451 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
80452 Table *pNew;
80453 Table *pTab;
80454 Vdbe *v;
80455 int iDb;
80456 int i;
80457 int nAlloc;
80458 sqlite3 *db = pParse->db;
80460 /* Look up the table being altered. */
80461 assert( pParse->pNewTable==0 );
80462 assert( sqlite3BtreeHoldsAllMutexes(db) );
80463 if( db->mallocFailed ) goto exit_begin_add_column;
80464 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
80465 if( !pTab ) goto exit_begin_add_column;
80467 #ifndef SQLITE_OMIT_VIRTUALTABLE
80468 if( IsVirtual(pTab) ){
80469 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
80470 goto exit_begin_add_column;
80472 #endif
80474 /* Make sure this is not an attempt to ALTER a view. */
80475 if( pTab->pSelect ){
80476 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
80477 goto exit_begin_add_column;
80479 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
80480 goto exit_begin_add_column;
80483 assert( pTab->addColOffset>0 );
80484 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80486 /* Put a copy of the Table struct in Parse.pNewTable for the
80487 ** sqlite3AddColumn() function and friends to modify. But modify
80488 ** the name by adding an "sqlite_altertab_" prefix. By adding this
80489 ** prefix, we insure that the name will not collide with an existing
80490 ** table because user table are not allowed to have the "sqlite_"
80491 ** prefix on their name.
80493 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
80494 if( !pNew ) goto exit_begin_add_column;
80495 pParse->pNewTable = pNew;
80496 pNew->nRef = 1;
80497 pNew->nCol = pTab->nCol;
80498 assert( pNew->nCol>0 );
80499 nAlloc = (((pNew->nCol-1)/8)*8)+8;
80500 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
80501 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
80502 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
80503 if( !pNew->aCol || !pNew->zName ){
80504 db->mallocFailed = 1;
80505 goto exit_begin_add_column;
80507 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
80508 for(i=0; i<pNew->nCol; i++){
80509 Column *pCol = &pNew->aCol[i];
80510 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
80511 pCol->zColl = 0;
80512 pCol->zType = 0;
80513 pCol->pDflt = 0;
80514 pCol->zDflt = 0;
80516 pNew->pSchema = db->aDb[iDb].pSchema;
80517 pNew->addColOffset = pTab->addColOffset;
80518 pNew->nRef = 1;
80520 /* Begin a transaction and increment the schema cookie. */
80521 sqlite3BeginWriteOperation(pParse, 0, iDb);
80522 v = sqlite3GetVdbe(pParse);
80523 if( !v ) goto exit_begin_add_column;
80524 sqlite3ChangeCookie(pParse, iDb);
80526 exit_begin_add_column:
80527 sqlite3SrcListDelete(db, pSrc);
80528 return;
80530 #endif /* SQLITE_ALTER_TABLE */
80532 /************** End of alter.c ***********************************************/
80533 /************** Begin file analyze.c *****************************************/
80535 ** 2005 July 8
80537 ** The author disclaims copyright to this source code. In place of
80538 ** a legal notice, here is a blessing:
80540 ** May you do good and not evil.
80541 ** May you find forgiveness for yourself and forgive others.
80542 ** May you share freely, never taking more than you give.
80544 *************************************************************************
80545 ** This file contains code associated with the ANALYZE command.
80547 ** The ANALYZE command gather statistics about the content of tables
80548 ** and indices. These statistics are made available to the query planner
80549 ** to help it make better decisions about how to perform queries.
80551 ** The following system tables are or have been supported:
80553 ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
80554 ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
80555 ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
80557 ** Additional tables might be added in future releases of SQLite.
80558 ** The sqlite_stat2 table is not created or used unless the SQLite version
80559 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
80560 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
80561 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
80562 ** created and used by SQLite versions 3.7.9 and later and with
80563 ** SQLITE_ENABLE_STAT3 defined. The fucntionality of sqlite_stat3
80564 ** is a superset of sqlite_stat2.
80566 ** Format of sqlite_stat1:
80568 ** There is normally one row per index, with the index identified by the
80569 ** name in the idx column. The tbl column is the name of the table to
80570 ** which the index belongs. In each such row, the stat column will be
80571 ** a string consisting of a list of integers. The first integer in this
80572 ** list is the number of rows in the index and in the table. The second
80573 ** integer is the average number of rows in the index that have the same
80574 ** value in the first column of the index. The third integer is the average
80575 ** number of rows in the index that have the same value for the first two
80576 ** columns. The N-th integer (for N>1) is the average number of rows in
80577 ** the index which have the same value for the first N-1 columns. For
80578 ** a K-column index, there will be K+1 integers in the stat column. If
80579 ** the index is unique, then the last integer will be 1.
80581 ** The list of integers in the stat column can optionally be followed
80582 ** by the keyword "unordered". The "unordered" keyword, if it is present,
80583 ** must be separated from the last integer by a single space. If the
80584 ** "unordered" keyword is present, then the query planner assumes that
80585 ** the index is unordered and will not use the index for a range query.
80587 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
80588 ** column contains a single integer which is the (estimated) number of
80589 ** rows in the table identified by sqlite_stat1.tbl.
80591 ** Format of sqlite_stat2:
80593 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
80594 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
80595 ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
80596 ** about the distribution of keys within an index. The index is identified by
80597 ** the "idx" column and the "tbl" column is the name of the table to which
80598 ** the index belongs. There are usually 10 rows in the sqlite_stat2
80599 ** table for each index.
80601 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
80602 ** inclusive are samples of the left-most key value in the index taken at
80603 ** evenly spaced points along the index. Let the number of samples be S
80604 ** (10 in the standard build) and let C be the number of rows in the index.
80605 ** Then the sampled rows are given by:
80607 ** rownumber = (i*C*2 + C)/(S*2)
80609 ** For i between 0 and S-1. Conceptually, the index space is divided into
80610 ** S uniform buckets and the samples are the middle row from each bucket.
80612 ** The format for sqlite_stat2 is recorded here for legacy reference. This
80613 ** version of SQLite does not support sqlite_stat2. It neither reads nor
80614 ** writes the sqlite_stat2 table. This version of SQLite only supports
80615 ** sqlite_stat3.
80617 ** Format for sqlite_stat3:
80619 ** The sqlite_stat3 is an enhancement to sqlite_stat2. A new name is
80620 ** used to avoid compatibility problems.
80622 ** The format of the sqlite_stat3 table is similar to the format of
80623 ** the sqlite_stat2 table. There are multiple entries for each index.
80624 ** The idx column names the index and the tbl column is the table of the
80625 ** index. If the idx and tbl columns are the same, then the sample is
80626 ** of the INTEGER PRIMARY KEY. The sample column is a value taken from
80627 ** the left-most column of the index. The nEq column is the approximate
80628 ** number of entires in the index whose left-most column exactly matches
80629 ** the sample. nLt is the approximate number of entires whose left-most
80630 ** column is less than the sample. The nDLt column is the approximate
80631 ** number of distinct left-most entries in the index that are less than
80632 ** the sample.
80634 ** Future versions of SQLite might change to store a string containing
80635 ** multiple integers values in the nDLt column of sqlite_stat3. The first
80636 ** integer will be the number of prior index entires that are distinct in
80637 ** the left-most column. The second integer will be the number of prior index
80638 ** entries that are distinct in the first two columns. The third integer
80639 ** will be the number of prior index entries that are distinct in the first
80640 ** three columns. And so forth. With that extension, the nDLt field is
80641 ** similar in function to the sqlite_stat1.stat field.
80643 ** There can be an arbitrary number of sqlite_stat3 entries per index.
80644 ** The ANALYZE command will typically generate sqlite_stat3 tables
80645 ** that contain between 10 and 40 samples which are distributed across
80646 ** the key space, though not uniformly, and which include samples with
80647 ** largest possible nEq values.
80649 #ifndef SQLITE_OMIT_ANALYZE
80652 ** This routine generates code that opens the sqlite_stat1 table for
80653 ** writing with cursor iStatCur. If the library was built with the
80654 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
80655 ** opened for writing using cursor (iStatCur+1)
80657 ** If the sqlite_stat1 tables does not previously exist, it is created.
80658 ** Similarly, if the sqlite_stat3 table does not exist and the library
80659 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
80661 ** Argument zWhere may be a pointer to a buffer containing a table name,
80662 ** or it may be a NULL pointer. If it is not NULL, then all entries in
80663 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
80664 ** with the named table are deleted. If zWhere==0, then code is generated
80665 ** to delete all stat table entries.
80667 static void openStatTable(
80668 Parse *pParse, /* Parsing context */
80669 int iDb, /* The database we are looking in */
80670 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
80671 const char *zWhere, /* Delete entries for this table or index */
80672 const char *zWhereType /* Either "tbl" or "idx" */
80674 static const struct {
80675 const char *zName;
80676 const char *zCols;
80677 } aTable[] = {
80678 { "sqlite_stat1", "tbl,idx,stat" },
80679 #ifdef SQLITE_ENABLE_STAT3
80680 { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
80681 #endif
80684 int aRoot[] = {0, 0};
80685 u8 aCreateTbl[] = {0, 0};
80687 int i;
80688 sqlite3 *db = pParse->db;
80689 Db *pDb;
80690 Vdbe *v = sqlite3GetVdbe(pParse);
80691 if( v==0 ) return;
80692 assert( sqlite3BtreeHoldsAllMutexes(db) );
80693 assert( sqlite3VdbeDb(v)==db );
80694 pDb = &db->aDb[iDb];
80696 /* Create new statistic tables if they do not exist, or clear them
80697 ** if they do already exist.
80699 for(i=0; i<ArraySize(aTable); i++){
80700 const char *zTab = aTable[i].zName;
80701 Table *pStat;
80702 if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
80703 /* The sqlite_stat[12] table does not exist. Create it. Note that a
80704 ** side-effect of the CREATE TABLE statement is to leave the rootpage
80705 ** of the new table in register pParse->regRoot. This is important
80706 ** because the OpenWrite opcode below will be needing it. */
80707 sqlite3NestedParse(pParse,
80708 "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
80710 aRoot[i] = pParse->regRoot;
80711 aCreateTbl[i] = OPFLAG_P2ISREG;
80712 }else{
80713 /* The table already exists. If zWhere is not NULL, delete all entries
80714 ** associated with the table zWhere. If zWhere is NULL, delete the
80715 ** entire contents of the table. */
80716 aRoot[i] = pStat->tnum;
80717 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
80718 if( zWhere ){
80719 sqlite3NestedParse(pParse,
80720 "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
80722 }else{
80723 /* The sqlite_stat[12] table already exists. Delete all rows. */
80724 sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
80729 /* Open the sqlite_stat[13] tables for writing. */
80730 for(i=0; i<ArraySize(aTable); i++){
80731 sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
80732 sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
80733 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
80738 ** Recommended number of samples for sqlite_stat3
80740 #ifndef SQLITE_STAT3_SAMPLES
80741 # define SQLITE_STAT3_SAMPLES 24
80742 #endif
80745 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
80746 ** share an instance of the following structure to hold their state
80747 ** information.
80749 typedef struct Stat3Accum Stat3Accum;
80750 struct Stat3Accum {
80751 tRowcnt nRow; /* Number of rows in the entire table */
80752 tRowcnt nPSample; /* How often to do a periodic sample */
80753 int iMin; /* Index of entry with minimum nEq and hash */
80754 int mxSample; /* Maximum number of samples to accumulate */
80755 int nSample; /* Current number of samples */
80756 u32 iPrn; /* Pseudo-random number used for sampling */
80757 struct Stat3Sample {
80758 i64 iRowid; /* Rowid in main table of the key */
80759 tRowcnt nEq; /* sqlite_stat3.nEq */
80760 tRowcnt nLt; /* sqlite_stat3.nLt */
80761 tRowcnt nDLt; /* sqlite_stat3.nDLt */
80762 u8 isPSample; /* True if a periodic sample */
80763 u32 iHash; /* Tiebreaker hash */
80764 } *a; /* An array of samples */
80767 #ifdef SQLITE_ENABLE_STAT3
80769 ** Implementation of the stat3_init(C,S) SQL function. The two parameters
80770 ** are the number of rows in the table or index (C) and the number of samples
80771 ** to accumulate (S).
80773 ** This routine allocates the Stat3Accum object.
80775 ** The return value is the Stat3Accum object (P).
80777 static void stat3Init(
80778 sqlite3_context *context,
80779 int argc,
80780 sqlite3_value **argv
80782 Stat3Accum *p;
80783 tRowcnt nRow;
80784 int mxSample;
80785 int n;
80787 UNUSED_PARAMETER(argc);
80788 nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
80789 mxSample = sqlite3_value_int(argv[1]);
80790 n = sizeof(*p) + sizeof(p->a[0])*mxSample;
80791 p = sqlite3MallocZero( n );
80792 if( p==0 ){
80793 sqlite3_result_error_nomem(context);
80794 return;
80796 p->a = (struct Stat3Sample*)&p[1];
80797 p->nRow = nRow;
80798 p->mxSample = mxSample;
80799 p->nPSample = p->nRow/(mxSample/3+1) + 1;
80800 sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
80801 sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
80803 static const FuncDef stat3InitFuncdef = {
80804 2, /* nArg */
80805 SQLITE_UTF8, /* iPrefEnc */
80806 0, /* flags */
80807 0, /* pUserData */
80808 0, /* pNext */
80809 stat3Init, /* xFunc */
80810 0, /* xStep */
80811 0, /* xFinalize */
80812 "stat3_init", /* zName */
80813 0, /* pHash */
80814 0 /* pDestructor */
80819 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function. The
80820 ** arguments describe a single key instance. This routine makes the
80821 ** decision about whether or not to retain this key for the sqlite_stat3
80822 ** table.
80824 ** The return value is NULL.
80826 static void stat3Push(
80827 sqlite3_context *context,
80828 int argc,
80829 sqlite3_value **argv
80831 Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
80832 tRowcnt nEq = sqlite3_value_int64(argv[0]);
80833 tRowcnt nLt = sqlite3_value_int64(argv[1]);
80834 tRowcnt nDLt = sqlite3_value_int64(argv[2]);
80835 i64 rowid = sqlite3_value_int64(argv[3]);
80836 u8 isPSample = 0;
80837 u8 doInsert = 0;
80838 int iMin = p->iMin;
80839 struct Stat3Sample *pSample;
80840 int i;
80841 u32 h;
80843 UNUSED_PARAMETER(context);
80844 UNUSED_PARAMETER(argc);
80845 if( nEq==0 ) return;
80846 h = p->iPrn = p->iPrn*1103515245 + 12345;
80847 if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
80848 doInsert = isPSample = 1;
80849 }else if( p->nSample<p->mxSample ){
80850 doInsert = 1;
80851 }else{
80852 if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
80853 doInsert = 1;
80856 if( !doInsert ) return;
80857 if( p->nSample==p->mxSample ){
80858 assert( p->nSample - iMin - 1 >= 0 );
80859 memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
80860 pSample = &p->a[p->nSample-1];
80861 }else{
80862 pSample = &p->a[p->nSample++];
80864 pSample->iRowid = rowid;
80865 pSample->nEq = nEq;
80866 pSample->nLt = nLt;
80867 pSample->nDLt = nDLt;
80868 pSample->iHash = h;
80869 pSample->isPSample = isPSample;
80871 /* Find the new minimum */
80872 if( p->nSample==p->mxSample ){
80873 pSample = p->a;
80874 i = 0;
80875 while( pSample->isPSample ){
80876 i++;
80877 pSample++;
80878 assert( i<p->nSample );
80880 nEq = pSample->nEq;
80881 h = pSample->iHash;
80882 iMin = i;
80883 for(i++, pSample++; i<p->nSample; i++, pSample++){
80884 if( pSample->isPSample ) continue;
80885 if( pSample->nEq<nEq
80886 || (pSample->nEq==nEq && pSample->iHash<h)
80888 iMin = i;
80889 nEq = pSample->nEq;
80890 h = pSample->iHash;
80893 p->iMin = iMin;
80896 static const FuncDef stat3PushFuncdef = {
80897 5, /* nArg */
80898 SQLITE_UTF8, /* iPrefEnc */
80899 0, /* flags */
80900 0, /* pUserData */
80901 0, /* pNext */
80902 stat3Push, /* xFunc */
80903 0, /* xStep */
80904 0, /* xFinalize */
80905 "stat3_push", /* zName */
80906 0, /* pHash */
80907 0 /* pDestructor */
80911 ** Implementation of the stat3_get(P,N,...) SQL function. This routine is
80912 ** used to query the results. Content is returned for the Nth sqlite_stat3
80913 ** row where N is between 0 and S-1 and S is the number of samples. The
80914 ** value returned depends on the number of arguments.
80916 ** argc==2 result: rowid
80917 ** argc==3 result: nEq
80918 ** argc==4 result: nLt
80919 ** argc==5 result: nDLt
80921 static void stat3Get(
80922 sqlite3_context *context,
80923 int argc,
80924 sqlite3_value **argv
80926 int n = sqlite3_value_int(argv[1]);
80927 Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
80929 assert( p!=0 );
80930 if( p->nSample<=n ) return;
80931 switch( argc ){
80932 case 2: sqlite3_result_int64(context, p->a[n].iRowid); break;
80933 case 3: sqlite3_result_int64(context, p->a[n].nEq); break;
80934 case 4: sqlite3_result_int64(context, p->a[n].nLt); break;
80935 default: sqlite3_result_int64(context, p->a[n].nDLt); break;
80938 static const FuncDef stat3GetFuncdef = {
80939 -1, /* nArg */
80940 SQLITE_UTF8, /* iPrefEnc */
80941 0, /* flags */
80942 0, /* pUserData */
80943 0, /* pNext */
80944 stat3Get, /* xFunc */
80945 0, /* xStep */
80946 0, /* xFinalize */
80947 "stat3_get", /* zName */
80948 0, /* pHash */
80949 0 /* pDestructor */
80951 #endif /* SQLITE_ENABLE_STAT3 */
80957 ** Generate code to do an analysis of all indices associated with
80958 ** a single table.
80960 static void analyzeOneTable(
80961 Parse *pParse, /* Parser context */
80962 Table *pTab, /* Table whose indices are to be analyzed */
80963 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
80964 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
80965 int iMem /* Available memory locations begin here */
80967 sqlite3 *db = pParse->db; /* Database handle */
80968 Index *pIdx; /* An index to being analyzed */
80969 int iIdxCur; /* Cursor open on index being analyzed */
80970 Vdbe *v; /* The virtual machine being built up */
80971 int i; /* Loop counter */
80972 int topOfLoop; /* The top of the loop */
80973 int endOfLoop; /* The end of the loop */
80974 int jZeroRows = -1; /* Jump from here if number of rows is zero */
80975 int iDb; /* Index of database containing pTab */
80976 u8 needTableCnt = 1; /* True to count the table */
80977 int regTabname = iMem++; /* Register containing table name */
80978 int regIdxname = iMem++; /* Register containing index name */
80979 int regStat1 = iMem++; /* The stat column of sqlite_stat1 */
80980 #ifdef SQLITE_ENABLE_STAT3
80981 int regNumEq = regStat1; /* Number of instances. Same as regStat1 */
80982 int regNumLt = iMem++; /* Number of keys less than regSample */
80983 int regNumDLt = iMem++; /* Number of distinct keys less than regSample */
80984 int regSample = iMem++; /* The next sample value */
80985 int regRowid = regSample; /* Rowid of a sample */
80986 int regAccum = iMem++; /* Register to hold Stat3Accum object */
80987 int regLoop = iMem++; /* Loop counter */
80988 int regCount = iMem++; /* Number of rows in the table or index */
80989 int regTemp1 = iMem++; /* Intermediate register */
80990 int regTemp2 = iMem++; /* Intermediate register */
80991 int once = 1; /* One-time initialization */
80992 int shortJump = 0; /* Instruction address */
80993 int iTabCur = pParse->nTab++; /* Table cursor */
80994 #endif
80995 int regCol = iMem++; /* Content of a column in analyzed table */
80996 int regRec = iMem++; /* Register holding completed record */
80997 int regTemp = iMem++; /* Temporary use register */
80998 int regNewRowid = iMem++; /* Rowid for the inserted record */
81001 v = sqlite3GetVdbe(pParse);
81002 if( v==0 || NEVER(pTab==0) ){
81003 return;
81005 if( pTab->tnum==0 ){
81006 /* Do not gather statistics on views or virtual tables */
81007 return;
81009 if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
81010 /* Do not gather statistics on system tables */
81011 return;
81013 assert( sqlite3BtreeHoldsAllMutexes(db) );
81014 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81015 assert( iDb>=0 );
81016 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81017 #ifndef SQLITE_OMIT_AUTHORIZATION
81018 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
81019 db->aDb[iDb].zName ) ){
81020 return;
81022 #endif
81024 /* Establish a read-lock on the table at the shared-cache level. */
81025 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
81027 iIdxCur = pParse->nTab++;
81028 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
81029 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81030 int nCol;
81031 KeyInfo *pKey;
81032 int addrIfNot = 0; /* address of OP_IfNot */
81033 int *aChngAddr; /* Array of jump instruction addresses */
81035 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
81036 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
81037 VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
81038 nCol = pIdx->nColumn;
81039 aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
81040 if( aChngAddr==0 ) continue;
81041 pKey = sqlite3IndexKeyinfo(pParse, pIdx);
81042 if( iMem+1+(nCol*2)>pParse->nMem ){
81043 pParse->nMem = iMem+1+(nCol*2);
81046 /* Open a cursor to the index to be analyzed. */
81047 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
81048 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
81049 (char *)pKey, P4_KEYINFO_HANDOFF);
81050 VdbeComment((v, "%s", pIdx->zName));
81052 /* Populate the register containing the index name. */
81053 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
81055 #ifdef SQLITE_ENABLE_STAT3
81056 if( once ){
81057 once = 0;
81058 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
81060 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
81061 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
81062 sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
81063 sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
81064 sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
81065 sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
81066 sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
81067 (char*)&stat3InitFuncdef, P4_FUNCDEF);
81068 sqlite3VdbeChangeP5(v, 2);
81069 #endif /* SQLITE_ENABLE_STAT3 */
81071 /* The block of memory cells initialized here is used as follows.
81073 ** iMem:
81074 ** The total number of rows in the table.
81076 ** iMem+1 .. iMem+nCol:
81077 ** Number of distinct entries in index considering the
81078 ** left-most N columns only, where N is between 1 and nCol,
81079 ** inclusive.
81081 ** iMem+nCol+1 .. Mem+2*nCol:
81082 ** Previous value of indexed columns, from left to right.
81084 ** Cells iMem through iMem+nCol are initialized to 0. The others are
81085 ** initialized to contain an SQL NULL.
81087 for(i=0; i<=nCol; i++){
81088 sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
81090 for(i=0; i<nCol; i++){
81091 sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
81094 /* Start the analysis loop. This loop runs through all the entries in
81095 ** the index b-tree. */
81096 endOfLoop = sqlite3VdbeMakeLabel(v);
81097 sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
81098 topOfLoop = sqlite3VdbeCurrentAddr(v);
81099 sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1); /* Increment row counter */
81101 for(i=0; i<nCol; i++){
81102 CollSeq *pColl;
81103 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
81104 if( i==0 ){
81105 /* Always record the very first row */
81106 addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
81108 assert( pIdx->azColl!=0 );
81109 assert( pIdx->azColl[i]!=0 );
81110 pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
81111 aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
81112 (char*)pColl, P4_COLLSEQ);
81113 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
81114 VdbeComment((v, "jump if column %d changed", i));
81115 #ifdef SQLITE_ENABLE_STAT3
81116 if( i==0 ){
81117 sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
81118 VdbeComment((v, "incr repeat count"));
81120 #endif
81122 sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
81123 for(i=0; i<nCol; i++){
81124 sqlite3VdbeJumpHere(v, aChngAddr[i]); /* Set jump dest for the OP_Ne */
81125 if( i==0 ){
81126 sqlite3VdbeJumpHere(v, addrIfNot); /* Jump dest for OP_IfNot */
81127 #ifdef SQLITE_ENABLE_STAT3
81128 sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
81129 (char*)&stat3PushFuncdef, P4_FUNCDEF);
81130 sqlite3VdbeChangeP5(v, 5);
81131 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
81132 sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
81133 sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
81134 sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
81135 #endif
81137 sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
81138 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
81140 sqlite3DbFree(db, aChngAddr);
81142 /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
81143 sqlite3VdbeResolveLabel(v, endOfLoop);
81145 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
81146 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
81147 #ifdef SQLITE_ENABLE_STAT3
81148 sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
81149 (char*)&stat3PushFuncdef, P4_FUNCDEF);
81150 sqlite3VdbeChangeP5(v, 5);
81151 sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
81152 shortJump =
81153 sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
81154 sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
81155 (char*)&stat3GetFuncdef, P4_FUNCDEF);
81156 sqlite3VdbeChangeP5(v, 2);
81157 sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
81158 sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
81159 sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
81160 sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
81161 sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
81162 (char*)&stat3GetFuncdef, P4_FUNCDEF);
81163 sqlite3VdbeChangeP5(v, 3);
81164 sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
81165 (char*)&stat3GetFuncdef, P4_FUNCDEF);
81166 sqlite3VdbeChangeP5(v, 4);
81167 sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
81168 (char*)&stat3GetFuncdef, P4_FUNCDEF);
81169 sqlite3VdbeChangeP5(v, 5);
81170 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
81171 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
81172 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
81173 sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
81174 sqlite3VdbeJumpHere(v, shortJump+2);
81175 #endif
81177 /* Store the results in sqlite_stat1.
81179 ** The result is a single row of the sqlite_stat1 table. The first
81180 ** two columns are the names of the table and index. The third column
81181 ** is a string composed of a list of integer statistics about the
81182 ** index. The first integer in the list is the total number of entries
81183 ** in the index. There is one additional integer in the list for each
81184 ** column of the table. This additional integer is a guess of how many
81185 ** rows of the table the index will select. If D is the count of distinct
81186 ** values and K is the total number of rows, then the integer is computed
81187 ** as:
81189 ** I = (K+D-1)/D
81191 ** If K==0 then no entry is made into the sqlite_stat1 table.
81192 ** If K>0 then it is always the case the D>0 so division by zero
81193 ** is never possible.
81195 sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
81196 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
81197 for(i=0; i<nCol; i++){
81198 sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
81199 sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
81200 sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
81201 sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
81202 sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
81203 sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
81204 sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
81206 if( pIdx->pPartIdxWhere!=0 ) sqlite3VdbeJumpHere(v, jZeroRows);
81207 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
81208 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
81209 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
81210 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81211 if( pIdx->pPartIdxWhere==0 ) sqlite3VdbeJumpHere(v, jZeroRows);
81214 /* Create a single sqlite_stat1 entry containing NULL as the index
81215 ** name and the row count as the content.
81217 if( pOnlyIdx==0 && needTableCnt ){
81218 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
81219 VdbeComment((v, "%s", pTab->zName));
81220 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
81221 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
81222 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
81223 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
81224 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
81225 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
81226 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
81227 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81228 sqlite3VdbeJumpHere(v, jZeroRows);
81230 if( pParse->nMem<regRec ) pParse->nMem = regRec;
81235 ** Generate code that will cause the most recent index analysis to
81236 ** be loaded into internal hash tables where is can be used.
81238 static void loadAnalysis(Parse *pParse, int iDb){
81239 Vdbe *v = sqlite3GetVdbe(pParse);
81240 if( v ){
81241 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
81246 ** Generate code that will do an analysis of an entire database
81248 static void analyzeDatabase(Parse *pParse, int iDb){
81249 sqlite3 *db = pParse->db;
81250 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
81251 HashElem *k;
81252 int iStatCur;
81253 int iMem;
81255 sqlite3BeginWriteOperation(pParse, 0, iDb);
81256 iStatCur = pParse->nTab;
81257 pParse->nTab += 3;
81258 openStatTable(pParse, iDb, iStatCur, 0, 0);
81259 iMem = pParse->nMem+1;
81260 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81261 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
81262 Table *pTab = (Table*)sqliteHashData(k);
81263 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
81265 loadAnalysis(pParse, iDb);
81269 ** Generate code that will do an analysis of a single table in
81270 ** a database. If pOnlyIdx is not NULL then it is a single index
81271 ** in pTab that should be analyzed.
81273 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
81274 int iDb;
81275 int iStatCur;
81277 assert( pTab!=0 );
81278 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
81279 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81280 sqlite3BeginWriteOperation(pParse, 0, iDb);
81281 iStatCur = pParse->nTab;
81282 pParse->nTab += 3;
81283 if( pOnlyIdx ){
81284 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
81285 }else{
81286 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
81288 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
81289 loadAnalysis(pParse, iDb);
81293 ** Generate code for the ANALYZE command. The parser calls this routine
81294 ** when it recognizes an ANALYZE command.
81296 ** ANALYZE -- 1
81297 ** ANALYZE <database> -- 2
81298 ** ANALYZE ?<database>.?<tablename> -- 3
81300 ** Form 1 causes all indices in all attached databases to be analyzed.
81301 ** Form 2 analyzes all indices the single database named.
81302 ** Form 3 analyzes all indices associated with the named table.
81304 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
81305 sqlite3 *db = pParse->db;
81306 int iDb;
81307 int i;
81308 char *z, *zDb;
81309 Table *pTab;
81310 Index *pIdx;
81311 Token *pTableName;
81313 /* Read the database schema. If an error occurs, leave an error message
81314 ** and code in pParse and return NULL. */
81315 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
81316 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81317 return;
81320 assert( pName2!=0 || pName1==0 );
81321 if( pName1==0 ){
81322 /* Form 1: Analyze everything */
81323 for(i=0; i<db->nDb; i++){
81324 if( i==1 ) continue; /* Do not analyze the TEMP database */
81325 analyzeDatabase(pParse, i);
81327 }else if( pName2->n==0 ){
81328 /* Form 2: Analyze the database or table named */
81329 iDb = sqlite3FindDb(db, pName1);
81330 if( iDb>=0 ){
81331 analyzeDatabase(pParse, iDb);
81332 }else{
81333 z = sqlite3NameFromToken(db, pName1);
81334 if( z ){
81335 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
81336 analyzeTable(pParse, pIdx->pTable, pIdx);
81337 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
81338 analyzeTable(pParse, pTab, 0);
81340 sqlite3DbFree(db, z);
81343 }else{
81344 /* Form 3: Analyze the fully qualified table name */
81345 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
81346 if( iDb>=0 ){
81347 zDb = db->aDb[iDb].zName;
81348 z = sqlite3NameFromToken(db, pTableName);
81349 if( z ){
81350 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
81351 analyzeTable(pParse, pIdx->pTable, pIdx);
81352 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
81353 analyzeTable(pParse, pTab, 0);
81355 sqlite3DbFree(db, z);
81362 ** Used to pass information from the analyzer reader through to the
81363 ** callback routine.
81365 typedef struct analysisInfo analysisInfo;
81366 struct analysisInfo {
81367 sqlite3 *db;
81368 const char *zDatabase;
81372 ** This callback is invoked once for each index when reading the
81373 ** sqlite_stat1 table.
81375 ** argv[0] = name of the table
81376 ** argv[1] = name of the index (might be NULL)
81377 ** argv[2] = results of analysis - on integer for each column
81379 ** Entries for which argv[1]==NULL simply record the number of rows in
81380 ** the table.
81382 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
81383 analysisInfo *pInfo = (analysisInfo*)pData;
81384 Index *pIndex;
81385 Table *pTable;
81386 int i, c, n;
81387 tRowcnt v;
81388 const char *z;
81390 assert( argc==3 );
81391 UNUSED_PARAMETER2(NotUsed, argc);
81393 if( argv==0 || argv[0]==0 || argv[2]==0 ){
81394 return 0;
81396 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
81397 if( pTable==0 ){
81398 return 0;
81400 if( argv[1] ){
81401 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
81402 }else{
81403 pIndex = 0;
81405 n = pIndex ? pIndex->nColumn : 0;
81406 z = argv[2];
81407 for(i=0; *z && i<=n; i++){
81408 v = 0;
81409 while( (c=z[0])>='0' && c<='9' ){
81410 v = v*10 + c - '0';
81411 z++;
81413 if( i==0 && (pIndex==0 || pIndex->pPartIdxWhere==0) ){
81414 if( v>0 ) pTable->nRowEst = v;
81415 if( pIndex==0 ) break;
81417 pIndex->aiRowEst[i] = v;
81418 if( *z==' ' ) z++;
81419 if( strcmp(z, "unordered")==0 ){
81420 pIndex->bUnordered = 1;
81421 break;
81424 return 0;
81428 ** If the Index.aSample variable is not NULL, delete the aSample[] array
81429 ** and its contents.
81431 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
81432 #ifdef SQLITE_ENABLE_STAT3
81433 if( pIdx->aSample ){
81434 int j;
81435 for(j=0; j<pIdx->nSample; j++){
81436 IndexSample *p = &pIdx->aSample[j];
81437 if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
81438 sqlite3DbFree(db, p->u.z);
81441 sqlite3DbFree(db, pIdx->aSample);
81443 if( db && db->pnBytesFreed==0 ){
81444 pIdx->nSample = 0;
81445 pIdx->aSample = 0;
81447 #else
81448 UNUSED_PARAMETER(db);
81449 UNUSED_PARAMETER(pIdx);
81450 #endif
81453 #ifdef SQLITE_ENABLE_STAT3
81455 ** Load content from the sqlite_stat3 table into the Index.aSample[]
81456 ** arrays of all indices.
81458 static int loadStat3(sqlite3 *db, const char *zDb){
81459 int rc; /* Result codes from subroutines */
81460 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
81461 char *zSql; /* Text of the SQL statement */
81462 Index *pPrevIdx = 0; /* Previous index in the loop */
81463 int idx = 0; /* slot in pIdx->aSample[] for next sample */
81464 int eType; /* Datatype of a sample */
81465 IndexSample *pSample; /* A slot in pIdx->aSample[] */
81467 assert( db->lookaside.bEnabled==0 );
81468 if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
81469 return SQLITE_OK;
81472 zSql = sqlite3MPrintf(db,
81473 "SELECT idx,count(*) FROM %Q.sqlite_stat3"
81474 " GROUP BY idx", zDb);
81475 if( !zSql ){
81476 return SQLITE_NOMEM;
81478 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
81479 sqlite3DbFree(db, zSql);
81480 if( rc ) return rc;
81482 while( sqlite3_step(pStmt)==SQLITE_ROW ){
81483 char *zIndex; /* Index name */
81484 Index *pIdx; /* Pointer to the index object */
81485 int nSample; /* Number of samples */
81487 zIndex = (char *)sqlite3_column_text(pStmt, 0);
81488 if( zIndex==0 ) continue;
81489 nSample = sqlite3_column_int(pStmt, 1);
81490 pIdx = sqlite3FindIndex(db, zIndex, zDb);
81491 if( pIdx==0 ) continue;
81492 assert( pIdx->nSample==0 );
81493 pIdx->nSample = nSample;
81494 pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
81495 pIdx->avgEq = pIdx->aiRowEst[1];
81496 if( pIdx->aSample==0 ){
81497 db->mallocFailed = 1;
81498 sqlite3_finalize(pStmt);
81499 return SQLITE_NOMEM;
81502 rc = sqlite3_finalize(pStmt);
81503 if( rc ) return rc;
81505 zSql = sqlite3MPrintf(db,
81506 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
81507 if( !zSql ){
81508 return SQLITE_NOMEM;
81510 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
81511 sqlite3DbFree(db, zSql);
81512 if( rc ) return rc;
81514 while( sqlite3_step(pStmt)==SQLITE_ROW ){
81515 char *zIndex; /* Index name */
81516 Index *pIdx; /* Pointer to the index object */
81517 int i; /* Loop counter */
81518 tRowcnt sumEq; /* Sum of the nEq values */
81520 zIndex = (char *)sqlite3_column_text(pStmt, 0);
81521 if( zIndex==0 ) continue;
81522 pIdx = sqlite3FindIndex(db, zIndex, zDb);
81523 if( pIdx==0 ) continue;
81524 if( pIdx==pPrevIdx ){
81525 idx++;
81526 }else{
81527 pPrevIdx = pIdx;
81528 idx = 0;
81530 assert( idx<pIdx->nSample );
81531 pSample = &pIdx->aSample[idx];
81532 pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
81533 pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
81534 pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
81535 if( idx==pIdx->nSample-1 ){
81536 if( pSample->nDLt>0 ){
81537 for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
81538 pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
81540 if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
81542 eType = sqlite3_column_type(pStmt, 4);
81543 pSample->eType = (u8)eType;
81544 switch( eType ){
81545 case SQLITE_INTEGER: {
81546 pSample->u.i = sqlite3_column_int64(pStmt, 4);
81547 break;
81549 case SQLITE_FLOAT: {
81550 pSample->u.r = sqlite3_column_double(pStmt, 4);
81551 break;
81553 case SQLITE_NULL: {
81554 break;
81556 default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
81557 const char *z = (const char *)(
81558 (eType==SQLITE_BLOB) ?
81559 sqlite3_column_blob(pStmt, 4):
81560 sqlite3_column_text(pStmt, 4)
81562 int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
81563 pSample->nByte = n;
81564 if( n < 1){
81565 pSample->u.z = 0;
81566 }else{
81567 pSample->u.z = sqlite3DbMallocRaw(db, n);
81568 if( pSample->u.z==0 ){
81569 db->mallocFailed = 1;
81570 sqlite3_finalize(pStmt);
81571 return SQLITE_NOMEM;
81573 memcpy(pSample->u.z, z, n);
81578 return sqlite3_finalize(pStmt);
81580 #endif /* SQLITE_ENABLE_STAT3 */
81583 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
81584 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
81585 ** arrays. The contents of sqlite_stat3 are used to populate the
81586 ** Index.aSample[] arrays.
81588 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
81589 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
81590 ** during compilation and the sqlite_stat3 table is present, no data is
81591 ** read from it.
81593 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the
81594 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
81595 ** returned. However, in this case, data is read from the sqlite_stat1
81596 ** table (if it is present) before returning.
81598 ** If an OOM error occurs, this function always sets db->mallocFailed.
81599 ** This means if the caller does not care about other errors, the return
81600 ** code may be ignored.
81602 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
81603 analysisInfo sInfo;
81604 HashElem *i;
81605 char *zSql;
81606 int rc;
81608 assert( iDb>=0 && iDb<db->nDb );
81609 assert( db->aDb[iDb].pBt!=0 );
81611 /* Clear any prior statistics */
81612 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81613 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
81614 Index *pIdx = sqliteHashData(i);
81615 sqlite3DefaultRowEst(pIdx);
81616 #ifdef SQLITE_ENABLE_STAT3
81617 sqlite3DeleteIndexSamples(db, pIdx);
81618 pIdx->aSample = 0;
81619 #endif
81622 /* Check to make sure the sqlite_stat1 table exists */
81623 sInfo.db = db;
81624 sInfo.zDatabase = db->aDb[iDb].zName;
81625 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
81626 return SQLITE_ERROR;
81629 /* Load new statistics out of the sqlite_stat1 table */
81630 zSql = sqlite3MPrintf(db,
81631 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
81632 if( zSql==0 ){
81633 rc = SQLITE_NOMEM;
81634 }else{
81635 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
81636 sqlite3DbFree(db, zSql);
81640 /* Load the statistics from the sqlite_stat3 table. */
81641 #ifdef SQLITE_ENABLE_STAT3
81642 if( rc==SQLITE_OK ){
81643 int lookasideEnabled = db->lookaside.bEnabled;
81644 db->lookaside.bEnabled = 0;
81645 rc = loadStat3(db, sInfo.zDatabase);
81646 db->lookaside.bEnabled = lookasideEnabled;
81648 #endif
81650 if( rc==SQLITE_NOMEM ){
81651 db->mallocFailed = 1;
81653 return rc;
81657 #endif /* SQLITE_OMIT_ANALYZE */
81659 /************** End of analyze.c *********************************************/
81660 /************** Begin file attach.c ******************************************/
81662 ** 2003 April 6
81664 ** The author disclaims copyright to this source code. In place of
81665 ** a legal notice, here is a blessing:
81667 ** May you do good and not evil.
81668 ** May you find forgiveness for yourself and forgive others.
81669 ** May you share freely, never taking more than you give.
81671 *************************************************************************
81672 ** This file contains code used to implement the ATTACH and DETACH commands.
81675 #ifndef SQLITE_OMIT_ATTACH
81677 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
81678 ** is slightly different from resolving a normal SQL expression, because simple
81679 ** identifiers are treated as strings, not possible column names or aliases.
81681 ** i.e. if the parser sees:
81683 ** ATTACH DATABASE abc AS def
81685 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
81686 ** looking for columns of the same name.
81688 ** This only applies to the root node of pExpr, so the statement:
81690 ** ATTACH DATABASE abc||def AS 'db2'
81692 ** will fail because neither abc or def can be resolved.
81694 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
81696 int rc = SQLITE_OK;
81697 if( pExpr ){
81698 if( pExpr->op!=TK_ID ){
81699 rc = sqlite3ResolveExprNames(pName, pExpr);
81700 if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
81701 sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
81702 return SQLITE_ERROR;
81704 }else{
81705 pExpr->op = TK_STRING;
81708 return rc;
81712 ** An SQL user-function registered to do the work of an ATTACH statement. The
81713 ** three arguments to the function come directly from an attach statement:
81715 ** ATTACH DATABASE x AS y KEY z
81717 ** SELECT sqlite_attach(x, y, z)
81719 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
81720 ** third argument.
81722 static void attachFunc(
81723 sqlite3_context *context,
81724 int NotUsed,
81725 sqlite3_value **argv
81727 int i;
81728 int rc = 0;
81729 sqlite3 *db = sqlite3_context_db_handle(context);
81730 const char *zName;
81731 const char *zFile;
81732 char *zPath = 0;
81733 char *zErr = 0;
81734 unsigned int flags;
81735 Db *aNew;
81736 char *zErrDyn = 0;
81737 sqlite3_vfs *pVfs;
81739 UNUSED_PARAMETER(NotUsed);
81741 zFile = (const char *)sqlite3_value_text(argv[0]);
81742 zName = (const char *)sqlite3_value_text(argv[1]);
81743 if( zFile==0 ) zFile = "";
81744 if( zName==0 ) zName = "";
81746 /* Check for the following errors:
81748 ** * Too many attached databases,
81749 ** * Transaction currently open
81750 ** * Specified database name already being used.
81752 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
81753 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
81754 db->aLimit[SQLITE_LIMIT_ATTACHED]
81756 goto attach_error;
81758 if( !db->autoCommit ){
81759 zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
81760 goto attach_error;
81762 for(i=0; i<db->nDb; i++){
81763 char *z = db->aDb[i].zName;
81764 assert( z && zName );
81765 if( sqlite3StrICmp(z, zName)==0 ){
81766 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
81767 goto attach_error;
81771 /* Allocate the new entry in the db->aDb[] array and initialize the schema
81772 ** hash tables.
81774 if( db->aDb==db->aDbStatic ){
81775 aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
81776 if( aNew==0 ) return;
81777 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
81778 }else{
81779 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
81780 if( aNew==0 ) return;
81782 db->aDb = aNew;
81783 aNew = &db->aDb[db->nDb];
81784 memset(aNew, 0, sizeof(*aNew));
81786 /* Open the database file. If the btree is successfully opened, use
81787 ** it to obtain the database schema. At this point the schema may
81788 ** or may not be initialized.
81790 flags = db->openFlags;
81791 rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
81792 if( rc!=SQLITE_OK ){
81793 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
81794 sqlite3_result_error(context, zErr, -1);
81795 sqlite3_free(zErr);
81796 return;
81798 assert( pVfs );
81799 flags |= SQLITE_OPEN_MAIN_DB;
81800 rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
81801 sqlite3_free( zPath );
81802 db->nDb++;
81803 if( rc==SQLITE_CONSTRAINT ){
81804 rc = SQLITE_ERROR;
81805 zErrDyn = sqlite3MPrintf(db, "database is already attached");
81806 }else if( rc==SQLITE_OK ){
81807 Pager *pPager;
81808 aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
81809 if( !aNew->pSchema ){
81810 rc = SQLITE_NOMEM;
81811 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
81812 zErrDyn = sqlite3MPrintf(db,
81813 "attached databases must use the same text encoding as main database");
81814 rc = SQLITE_ERROR;
81816 pPager = sqlite3BtreePager(aNew->pBt);
81817 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
81818 sqlite3BtreeSecureDelete(aNew->pBt,
81819 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
81820 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
81821 sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
81822 #endif
81824 aNew->safety_level = 3;
81825 aNew->zName = sqlite3DbStrDup(db, zName);
81826 if( rc==SQLITE_OK && aNew->zName==0 ){
81827 rc = SQLITE_NOMEM;
81831 #ifdef SQLITE_HAS_CODEC
81832 if( rc==SQLITE_OK ){
81833 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
81834 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
81835 int nKey;
81836 char *zKey;
81837 int t = sqlite3_value_type(argv[2]);
81838 switch( t ){
81839 case SQLITE_INTEGER:
81840 case SQLITE_FLOAT:
81841 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
81842 rc = SQLITE_ERROR;
81843 break;
81845 case SQLITE_TEXT:
81846 case SQLITE_BLOB:
81847 nKey = sqlite3_value_bytes(argv[2]);
81848 zKey = (char *)sqlite3_value_blob(argv[2]);
81849 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
81850 break;
81852 case SQLITE_NULL:
81853 /* No key specified. Use the key from the main database */
81854 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
81855 if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
81856 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
81858 break;
81861 #endif
81863 /* If the file was opened successfully, read the schema for the new database.
81864 ** If this fails, or if opening the file failed, then close the file and
81865 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
81866 ** we found it.
81868 if( rc==SQLITE_OK ){
81869 sqlite3BtreeEnterAll(db);
81870 rc = sqlite3Init(db, &zErrDyn);
81871 sqlite3BtreeLeaveAll(db);
81873 if( rc ){
81874 int iDb = db->nDb - 1;
81875 assert( iDb>=2 );
81876 if( db->aDb[iDb].pBt ){
81877 sqlite3BtreeClose(db->aDb[iDb].pBt);
81878 db->aDb[iDb].pBt = 0;
81879 db->aDb[iDb].pSchema = 0;
81881 sqlite3ResetAllSchemasOfConnection(db);
81882 db->nDb = iDb;
81883 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
81884 db->mallocFailed = 1;
81885 sqlite3DbFree(db, zErrDyn);
81886 zErrDyn = sqlite3MPrintf(db, "out of memory");
81887 }else if( zErrDyn==0 ){
81888 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
81890 goto attach_error;
81893 return;
81895 attach_error:
81896 /* Return an error if we get here */
81897 if( zErrDyn ){
81898 sqlite3_result_error(context, zErrDyn, -1);
81899 sqlite3DbFree(db, zErrDyn);
81901 if( rc ) sqlite3_result_error_code(context, rc);
81905 ** An SQL user-function registered to do the work of an DETACH statement. The
81906 ** three arguments to the function come directly from a detach statement:
81908 ** DETACH DATABASE x
81910 ** SELECT sqlite_detach(x)
81912 static void detachFunc(
81913 sqlite3_context *context,
81914 int NotUsed,
81915 sqlite3_value **argv
81917 const char *zName = (const char *)sqlite3_value_text(argv[0]);
81918 sqlite3 *db = sqlite3_context_db_handle(context);
81919 int i;
81920 Db *pDb = 0;
81921 char zErr[128];
81923 UNUSED_PARAMETER(NotUsed);
81925 if( zName==0 ) zName = "";
81926 for(i=0; i<db->nDb; i++){
81927 pDb = &db->aDb[i];
81928 if( pDb->pBt==0 ) continue;
81929 if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
81932 if( i>=db->nDb ){
81933 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
81934 goto detach_error;
81936 if( i<2 ){
81937 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
81938 goto detach_error;
81940 if( !db->autoCommit ){
81941 sqlite3_snprintf(sizeof(zErr), zErr,
81942 "cannot DETACH database within transaction");
81943 goto detach_error;
81945 if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
81946 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
81947 goto detach_error;
81950 sqlite3BtreeClose(pDb->pBt);
81951 pDb->pBt = 0;
81952 pDb->pSchema = 0;
81953 sqlite3ResetAllSchemasOfConnection(db);
81954 return;
81956 detach_error:
81957 sqlite3_result_error(context, zErr, -1);
81961 ** This procedure generates VDBE code for a single invocation of either the
81962 ** sqlite_detach() or sqlite_attach() SQL user functions.
81964 static void codeAttach(
81965 Parse *pParse, /* The parser context */
81966 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
81967 FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
81968 Expr *pAuthArg, /* Expression to pass to authorization callback */
81969 Expr *pFilename, /* Name of database file */
81970 Expr *pDbname, /* Name of the database to use internally */
81971 Expr *pKey /* Database key for encryption extension */
81973 int rc;
81974 NameContext sName;
81975 Vdbe *v;
81976 sqlite3* db = pParse->db;
81977 int regArgs;
81979 memset(&sName, 0, sizeof(NameContext));
81980 sName.pParse = pParse;
81982 if(
81983 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
81984 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
81985 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
81987 pParse->nErr++;
81988 goto attach_end;
81991 #ifndef SQLITE_OMIT_AUTHORIZATION
81992 if( pAuthArg ){
81993 char *zAuthArg;
81994 if( pAuthArg->op==TK_STRING ){
81995 zAuthArg = pAuthArg->u.zToken;
81996 }else{
81997 zAuthArg = 0;
81999 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
82000 if(rc!=SQLITE_OK ){
82001 goto attach_end;
82004 #endif /* SQLITE_OMIT_AUTHORIZATION */
82007 v = sqlite3GetVdbe(pParse);
82008 regArgs = sqlite3GetTempRange(pParse, 4);
82009 sqlite3ExprCode(pParse, pFilename, regArgs);
82010 sqlite3ExprCode(pParse, pDbname, regArgs+1);
82011 sqlite3ExprCode(pParse, pKey, regArgs+2);
82013 assert( v || db->mallocFailed );
82014 if( v ){
82015 sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
82016 assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
82017 sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
82018 sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
82020 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
82021 ** statement only). For DETACH, set it to false (expire all existing
82022 ** statements).
82024 sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
82027 attach_end:
82028 sqlite3ExprDelete(db, pFilename);
82029 sqlite3ExprDelete(db, pDbname);
82030 sqlite3ExprDelete(db, pKey);
82034 ** Called by the parser to compile a DETACH statement.
82036 ** DETACH pDbname
82038 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
82039 static const FuncDef detach_func = {
82040 1, /* nArg */
82041 SQLITE_UTF8, /* iPrefEnc */
82042 0, /* flags */
82043 0, /* pUserData */
82044 0, /* pNext */
82045 detachFunc, /* xFunc */
82046 0, /* xStep */
82047 0, /* xFinalize */
82048 "sqlite_detach", /* zName */
82049 0, /* pHash */
82050 0 /* pDestructor */
82052 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
82056 ** Called by the parser to compile an ATTACH statement.
82058 ** ATTACH p AS pDbname KEY pKey
82060 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
82061 static const FuncDef attach_func = {
82062 3, /* nArg */
82063 SQLITE_UTF8, /* iPrefEnc */
82064 0, /* flags */
82065 0, /* pUserData */
82066 0, /* pNext */
82067 attachFunc, /* xFunc */
82068 0, /* xStep */
82069 0, /* xFinalize */
82070 "sqlite_attach", /* zName */
82071 0, /* pHash */
82072 0 /* pDestructor */
82074 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
82076 #endif /* SQLITE_OMIT_ATTACH */
82079 ** Initialize a DbFixer structure. This routine must be called prior
82080 ** to passing the structure to one of the sqliteFixAAAA() routines below.
82082 ** The return value indicates whether or not fixation is required. TRUE
82083 ** means we do need to fix the database references, FALSE means we do not.
82085 SQLITE_PRIVATE int sqlite3FixInit(
82086 DbFixer *pFix, /* The fixer to be initialized */
82087 Parse *pParse, /* Error messages will be written here */
82088 int iDb, /* This is the database that must be used */
82089 const char *zType, /* "view", "trigger", or "index" */
82090 const Token *pName /* Name of the view, trigger, or index */
82092 sqlite3 *db;
82094 if( NEVER(iDb<0) || iDb==1 ) return 0;
82095 db = pParse->db;
82096 assert( db->nDb>iDb );
82097 pFix->pParse = pParse;
82098 pFix->zDb = db->aDb[iDb].zName;
82099 pFix->pSchema = db->aDb[iDb].pSchema;
82100 pFix->zType = zType;
82101 pFix->pName = pName;
82102 return 1;
82106 ** The following set of routines walk through the parse tree and assign
82107 ** a specific database to all table references where the database name
82108 ** was left unspecified in the original SQL statement. The pFix structure
82109 ** must have been initialized by a prior call to sqlite3FixInit().
82111 ** These routines are used to make sure that an index, trigger, or
82112 ** view in one database does not refer to objects in a different database.
82113 ** (Exception: indices, triggers, and views in the TEMP database are
82114 ** allowed to refer to anything.) If a reference is explicitly made
82115 ** to an object in a different database, an error message is added to
82116 ** pParse->zErrMsg and these routines return non-zero. If everything
82117 ** checks out, these routines return 0.
82119 SQLITE_PRIVATE int sqlite3FixSrcList(
82120 DbFixer *pFix, /* Context of the fixation */
82121 SrcList *pList /* The Source list to check and modify */
82123 int i;
82124 const char *zDb;
82125 struct SrcList_item *pItem;
82127 if( NEVER(pList==0) ) return 0;
82128 zDb = pFix->zDb;
82129 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
82130 if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
82131 sqlite3ErrorMsg(pFix->pParse,
82132 "%s %T cannot reference objects in database %s",
82133 pFix->zType, pFix->pName, pItem->zDatabase);
82134 return 1;
82136 sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
82137 pItem->zDatabase = 0;
82138 pItem->pSchema = pFix->pSchema;
82139 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
82140 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
82141 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
82142 #endif
82144 return 0;
82146 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
82147 SQLITE_PRIVATE int sqlite3FixSelect(
82148 DbFixer *pFix, /* Context of the fixation */
82149 Select *pSelect /* The SELECT statement to be fixed to one database */
82151 while( pSelect ){
82152 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
82153 return 1;
82155 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
82156 return 1;
82158 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
82159 return 1;
82161 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
82162 return 1;
82164 pSelect = pSelect->pPrior;
82166 return 0;
82168 SQLITE_PRIVATE int sqlite3FixExpr(
82169 DbFixer *pFix, /* Context of the fixation */
82170 Expr *pExpr /* The expression to be fixed to one database */
82172 while( pExpr ){
82173 if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
82174 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
82175 if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
82176 }else{
82177 if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
82179 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
82180 return 1;
82182 pExpr = pExpr->pLeft;
82184 return 0;
82186 SQLITE_PRIVATE int sqlite3FixExprList(
82187 DbFixer *pFix, /* Context of the fixation */
82188 ExprList *pList /* The expression to be fixed to one database */
82190 int i;
82191 struct ExprList_item *pItem;
82192 if( pList==0 ) return 0;
82193 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
82194 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
82195 return 1;
82198 return 0;
82200 #endif
82202 #ifndef SQLITE_OMIT_TRIGGER
82203 SQLITE_PRIVATE int sqlite3FixTriggerStep(
82204 DbFixer *pFix, /* Context of the fixation */
82205 TriggerStep *pStep /* The trigger step be fixed to one database */
82207 while( pStep ){
82208 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
82209 return 1;
82211 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
82212 return 1;
82214 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
82215 return 1;
82217 pStep = pStep->pNext;
82219 return 0;
82221 #endif
82223 /************** End of attach.c **********************************************/
82224 /************** Begin file auth.c ********************************************/
82226 ** 2003 January 11
82228 ** The author disclaims copyright to this source code. In place of
82229 ** a legal notice, here is a blessing:
82231 ** May you do good and not evil.
82232 ** May you find forgiveness for yourself and forgive others.
82233 ** May you share freely, never taking more than you give.
82235 *************************************************************************
82236 ** This file contains code used to implement the sqlite3_set_authorizer()
82237 ** API. This facility is an optional feature of the library. Embedded
82238 ** systems that do not need this facility may omit it by recompiling
82239 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
82243 ** All of the code in this file may be omitted by defining a single
82244 ** macro.
82246 #ifndef SQLITE_OMIT_AUTHORIZATION
82249 ** Set or clear the access authorization function.
82251 ** The access authorization function is be called during the compilation
82252 ** phase to verify that the user has read and/or write access permission on
82253 ** various fields of the database. The first argument to the auth function
82254 ** is a copy of the 3rd argument to this routine. The second argument
82255 ** to the auth function is one of these constants:
82257 ** SQLITE_CREATE_INDEX
82258 ** SQLITE_CREATE_TABLE
82259 ** SQLITE_CREATE_TEMP_INDEX
82260 ** SQLITE_CREATE_TEMP_TABLE
82261 ** SQLITE_CREATE_TEMP_TRIGGER
82262 ** SQLITE_CREATE_TEMP_VIEW
82263 ** SQLITE_CREATE_TRIGGER
82264 ** SQLITE_CREATE_VIEW
82265 ** SQLITE_DELETE
82266 ** SQLITE_DROP_INDEX
82267 ** SQLITE_DROP_TABLE
82268 ** SQLITE_DROP_TEMP_INDEX
82269 ** SQLITE_DROP_TEMP_TABLE
82270 ** SQLITE_DROP_TEMP_TRIGGER
82271 ** SQLITE_DROP_TEMP_VIEW
82272 ** SQLITE_DROP_TRIGGER
82273 ** SQLITE_DROP_VIEW
82274 ** SQLITE_INSERT
82275 ** SQLITE_PRAGMA
82276 ** SQLITE_READ
82277 ** SQLITE_SELECT
82278 ** SQLITE_TRANSACTION
82279 ** SQLITE_UPDATE
82281 ** The third and fourth arguments to the auth function are the name of
82282 ** the table and the column that are being accessed. The auth function
82283 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
82284 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
82285 ** means that the SQL statement will never-run - the sqlite3_exec() call
82286 ** will return with an error. SQLITE_IGNORE means that the SQL statement
82287 ** should run but attempts to read the specified column will return NULL
82288 ** and attempts to write the column will be ignored.
82290 ** Setting the auth function to NULL disables this hook. The default
82291 ** setting of the auth function is NULL.
82293 SQLITE_API int sqlite3_set_authorizer(
82294 sqlite3 *db,
82295 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
82296 void *pArg
82298 sqlite3_mutex_enter(db->mutex);
82299 db->xAuth = xAuth;
82300 db->pAuthArg = pArg;
82301 sqlite3ExpirePreparedStatements(db);
82302 sqlite3_mutex_leave(db->mutex);
82303 return SQLITE_OK;
82307 ** Write an error message into pParse->zErrMsg that explains that the
82308 ** user-supplied authorization function returned an illegal value.
82310 static void sqliteAuthBadReturnCode(Parse *pParse){
82311 sqlite3ErrorMsg(pParse, "authorizer malfunction");
82312 pParse->rc = SQLITE_ERROR;
82316 ** Invoke the authorization callback for permission to read column zCol from
82317 ** table zTab in database zDb. This function assumes that an authorization
82318 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
82320 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
82321 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
82322 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
82324 SQLITE_PRIVATE int sqlite3AuthReadCol(
82325 Parse *pParse, /* The parser context */
82326 const char *zTab, /* Table name */
82327 const char *zCol, /* Column name */
82328 int iDb /* Index of containing database. */
82330 sqlite3 *db = pParse->db; /* Database handle */
82331 char *zDb = db->aDb[iDb].zName; /* Name of attached database */
82332 int rc; /* Auth callback return code */
82334 rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
82335 if( rc==SQLITE_DENY ){
82336 if( db->nDb>2 || iDb!=0 ){
82337 sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
82338 }else{
82339 sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
82341 pParse->rc = SQLITE_AUTH;
82342 }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
82343 sqliteAuthBadReturnCode(pParse);
82345 return rc;
82349 ** The pExpr should be a TK_COLUMN expression. The table referred to
82350 ** is in pTabList or else it is the NEW or OLD table of a trigger.
82351 ** Check to see if it is OK to read this particular column.
82353 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
82354 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
82355 ** then generate an error.
82357 SQLITE_PRIVATE void sqlite3AuthRead(
82358 Parse *pParse, /* The parser context */
82359 Expr *pExpr, /* The expression to check authorization on */
82360 Schema *pSchema, /* The schema of the expression */
82361 SrcList *pTabList /* All table that pExpr might refer to */
82363 sqlite3 *db = pParse->db;
82364 Table *pTab = 0; /* The table being read */
82365 const char *zCol; /* Name of the column of the table */
82366 int iSrc; /* Index in pTabList->a[] of table being read */
82367 int iDb; /* The index of the database the expression refers to */
82368 int iCol; /* Index of column in table */
82370 if( db->xAuth==0 ) return;
82371 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
82372 if( iDb<0 ){
82373 /* An attempt to read a column out of a subquery or other
82374 ** temporary table. */
82375 return;
82378 assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
82379 if( pExpr->op==TK_TRIGGER ){
82380 pTab = pParse->pTriggerTab;
82381 }else{
82382 assert( pTabList );
82383 for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
82384 if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
82385 pTab = pTabList->a[iSrc].pTab;
82386 break;
82390 iCol = pExpr->iColumn;
82391 if( NEVER(pTab==0) ) return;
82393 if( iCol>=0 ){
82394 assert( iCol<pTab->nCol );
82395 zCol = pTab->aCol[iCol].zName;
82396 }else if( pTab->iPKey>=0 ){
82397 assert( pTab->iPKey<pTab->nCol );
82398 zCol = pTab->aCol[pTab->iPKey].zName;
82399 }else{
82400 zCol = "ROWID";
82402 assert( iDb>=0 && iDb<db->nDb );
82403 if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
82404 pExpr->op = TK_NULL;
82409 ** Do an authorization check using the code and arguments given. Return
82410 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
82411 ** is returned, then the error count and error message in pParse are
82412 ** modified appropriately.
82414 SQLITE_PRIVATE int sqlite3AuthCheck(
82415 Parse *pParse,
82416 int code,
82417 const char *zArg1,
82418 const char *zArg2,
82419 const char *zArg3
82421 sqlite3 *db = pParse->db;
82422 int rc;
82424 /* Don't do any authorization checks if the database is initialising
82425 ** or if the parser is being invoked from within sqlite3_declare_vtab.
82427 if( db->init.busy || IN_DECLARE_VTAB ){
82428 return SQLITE_OK;
82431 if( db->xAuth==0 ){
82432 return SQLITE_OK;
82434 rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
82435 if( rc==SQLITE_DENY ){
82436 sqlite3ErrorMsg(pParse, "not authorized");
82437 pParse->rc = SQLITE_AUTH;
82438 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
82439 rc = SQLITE_DENY;
82440 sqliteAuthBadReturnCode(pParse);
82442 return rc;
82446 ** Push an authorization context. After this routine is called, the
82447 ** zArg3 argument to authorization callbacks will be zContext until
82448 ** popped. Or if pParse==0, this routine is a no-op.
82450 SQLITE_PRIVATE void sqlite3AuthContextPush(
82451 Parse *pParse,
82452 AuthContext *pContext,
82453 const char *zContext
82455 assert( pParse );
82456 pContext->pParse = pParse;
82457 pContext->zAuthContext = pParse->zAuthContext;
82458 pParse->zAuthContext = zContext;
82462 ** Pop an authorization context that was previously pushed
82463 ** by sqlite3AuthContextPush
82465 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
82466 if( pContext->pParse ){
82467 pContext->pParse->zAuthContext = pContext->zAuthContext;
82468 pContext->pParse = 0;
82472 #endif /* SQLITE_OMIT_AUTHORIZATION */
82474 /************** End of auth.c ************************************************/
82475 /************** Begin file build.c *******************************************/
82477 ** 2001 September 15
82479 ** The author disclaims copyright to this source code. In place of
82480 ** a legal notice, here is a blessing:
82482 ** May you do good and not evil.
82483 ** May you find forgiveness for yourself and forgive others.
82484 ** May you share freely, never taking more than you give.
82486 *************************************************************************
82487 ** This file contains C code routines that are called by the SQLite parser
82488 ** when syntax rules are reduced. The routines in this file handle the
82489 ** following kinds of SQL syntax:
82491 ** CREATE TABLE
82492 ** DROP TABLE
82493 ** CREATE INDEX
82494 ** DROP INDEX
82495 ** creating ID lists
82496 ** BEGIN TRANSACTION
82497 ** COMMIT
82498 ** ROLLBACK
82502 ** This routine is called when a new SQL statement is beginning to
82503 ** be parsed. Initialize the pParse structure as needed.
82505 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
82506 pParse->explain = (u8)explainFlag;
82507 pParse->nVar = 0;
82510 #ifndef SQLITE_OMIT_SHARED_CACHE
82512 ** The TableLock structure is only used by the sqlite3TableLock() and
82513 ** codeTableLocks() functions.
82515 struct TableLock {
82516 int iDb; /* The database containing the table to be locked */
82517 int iTab; /* The root page of the table to be locked */
82518 u8 isWriteLock; /* True for write lock. False for a read lock */
82519 const char *zName; /* Name of the table */
82523 ** Record the fact that we want to lock a table at run-time.
82525 ** The table to be locked has root page iTab and is found in database iDb.
82526 ** A read or a write lock can be taken depending on isWritelock.
82528 ** This routine just records the fact that the lock is desired. The
82529 ** code to make the lock occur is generated by a later call to
82530 ** codeTableLocks() which occurs during sqlite3FinishCoding().
82532 SQLITE_PRIVATE void sqlite3TableLock(
82533 Parse *pParse, /* Parsing context */
82534 int iDb, /* Index of the database containing the table to lock */
82535 int iTab, /* Root page number of the table to be locked */
82536 u8 isWriteLock, /* True for a write lock */
82537 const char *zName /* Name of the table to be locked */
82539 Parse *pToplevel = sqlite3ParseToplevel(pParse);
82540 int i;
82541 int nBytes;
82542 TableLock *p;
82543 assert( iDb>=0 );
82545 for(i=0; i<pToplevel->nTableLock; i++){
82546 p = &pToplevel->aTableLock[i];
82547 if( p->iDb==iDb && p->iTab==iTab ){
82548 p->isWriteLock = (p->isWriteLock || isWriteLock);
82549 return;
82553 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
82554 pToplevel->aTableLock =
82555 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
82556 if( pToplevel->aTableLock ){
82557 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
82558 p->iDb = iDb;
82559 p->iTab = iTab;
82560 p->isWriteLock = isWriteLock;
82561 p->zName = zName;
82562 }else{
82563 pToplevel->nTableLock = 0;
82564 pToplevel->db->mallocFailed = 1;
82569 ** Code an OP_TableLock instruction for each table locked by the
82570 ** statement (configured by calls to sqlite3TableLock()).
82572 static void codeTableLocks(Parse *pParse){
82573 int i;
82574 Vdbe *pVdbe;
82576 pVdbe = sqlite3GetVdbe(pParse);
82577 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
82579 for(i=0; i<pParse->nTableLock; i++){
82580 TableLock *p = &pParse->aTableLock[i];
82581 int p1 = p->iDb;
82582 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
82583 p->zName, P4_STATIC);
82586 #else
82587 #define codeTableLocks(x)
82588 #endif
82591 ** This routine is called after a single SQL statement has been
82592 ** parsed and a VDBE program to execute that statement has been
82593 ** prepared. This routine puts the finishing touches on the
82594 ** VDBE program and resets the pParse structure for the next
82595 ** parse.
82597 ** Note that if an error occurred, it might be the case that
82598 ** no VDBE code was generated.
82600 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
82601 sqlite3 *db;
82602 Vdbe *v;
82604 assert( pParse->pToplevel==0 );
82605 db = pParse->db;
82606 if( db->mallocFailed ) return;
82607 if( pParse->nested ) return;
82608 if( pParse->nErr ) return;
82610 /* Begin by generating some termination code at the end of the
82611 ** vdbe program
82613 v = sqlite3GetVdbe(pParse);
82614 assert( !pParse->isMultiWrite
82615 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
82616 if( v ){
82617 sqlite3VdbeAddOp0(v, OP_Halt);
82619 /* The cookie mask contains one bit for each database file open.
82620 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
82621 ** set for each database that is used. Generate code to start a
82622 ** transaction on each used database and to verify the schema cookie
82623 ** on each used database.
82625 if( pParse->cookieGoto>0 ){
82626 yDbMask mask;
82627 int iDb;
82628 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
82629 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
82630 if( (mask & pParse->cookieMask)==0 ) continue;
82631 sqlite3VdbeUsesBtree(v, iDb);
82632 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
82633 if( db->init.busy==0 ){
82634 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82635 sqlite3VdbeAddOp3(v, OP_VerifyCookie,
82636 iDb, pParse->cookieValue[iDb],
82637 db->aDb[iDb].pSchema->iGeneration);
82640 #ifndef SQLITE_OMIT_VIRTUALTABLE
82642 int i;
82643 for(i=0; i<pParse->nVtabLock; i++){
82644 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
82645 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
82647 pParse->nVtabLock = 0;
82649 #endif
82651 /* Once all the cookies have been verified and transactions opened,
82652 ** obtain the required table-locks. This is a no-op unless the
82653 ** shared-cache feature is enabled.
82655 codeTableLocks(pParse);
82657 /* Initialize any AUTOINCREMENT data structures required.
82659 sqlite3AutoincrementBegin(pParse);
82661 /* Finally, jump back to the beginning of the executable code. */
82662 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
82667 /* Get the VDBE program ready for execution
82669 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
82670 #ifdef SQLITE_DEBUG
82671 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
82672 sqlite3VdbeTrace(v, trace);
82673 #endif
82674 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
82675 /* A minimum of one cursor is required if autoincrement is used
82676 * See ticket [a696379c1f08866] */
82677 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
82678 sqlite3VdbeMakeReady(v, pParse);
82679 pParse->rc = SQLITE_DONE;
82680 pParse->colNamesSet = 0;
82681 }else{
82682 pParse->rc = SQLITE_ERROR;
82684 pParse->nTab = 0;
82685 pParse->nMem = 0;
82686 pParse->nSet = 0;
82687 pParse->nVar = 0;
82688 pParse->cookieMask = 0;
82689 pParse->cookieGoto = 0;
82693 ** Run the parser and code generator recursively in order to generate
82694 ** code for the SQL statement given onto the end of the pParse context
82695 ** currently under construction. When the parser is run recursively
82696 ** this way, the final OP_Halt is not appended and other initialization
82697 ** and finalization steps are omitted because those are handling by the
82698 ** outermost parser.
82700 ** Not everything is nestable. This facility is designed to permit
82701 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
82702 ** care if you decide to try to use this routine for some other purposes.
82704 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
82705 va_list ap;
82706 char *zSql;
82707 char *zErrMsg = 0;
82708 sqlite3 *db = pParse->db;
82709 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
82710 char saveBuf[SAVE_SZ];
82712 if( pParse->nErr ) return;
82713 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
82714 va_start(ap, zFormat);
82715 zSql = sqlite3VMPrintf(db, zFormat, ap);
82716 va_end(ap);
82717 if( zSql==0 ){
82718 return; /* A malloc must have failed */
82720 pParse->nested++;
82721 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
82722 memset(&pParse->nVar, 0, SAVE_SZ);
82723 sqlite3RunParser(pParse, zSql, &zErrMsg);
82724 sqlite3DbFree(db, zErrMsg);
82725 sqlite3DbFree(db, zSql);
82726 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
82727 pParse->nested--;
82731 ** Locate the in-memory structure that describes a particular database
82732 ** table given the name of that table and (optionally) the name of the
82733 ** database containing the table. Return NULL if not found.
82735 ** If zDatabase is 0, all databases are searched for the table and the
82736 ** first matching table is returned. (No checking for duplicate table
82737 ** names is done.) The search order is TEMP first, then MAIN, then any
82738 ** auxiliary databases added using the ATTACH command.
82740 ** See also sqlite3LocateTable().
82742 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
82743 Table *p = 0;
82744 int i;
82745 int nName;
82746 assert( zName!=0 );
82747 nName = sqlite3Strlen30(zName);
82748 /* All mutexes are required for schema access. Make sure we hold them. */
82749 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
82750 for(i=OMIT_TEMPDB; i<db->nDb; i++){
82751 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
82752 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
82753 assert( sqlite3SchemaMutexHeld(db, j, 0) );
82754 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
82755 if( p ) break;
82757 return p;
82761 ** Locate the in-memory structure that describes a particular database
82762 ** table given the name of that table and (optionally) the name of the
82763 ** database containing the table. Return NULL if not found. Also leave an
82764 ** error message in pParse->zErrMsg.
82766 ** The difference between this routine and sqlite3FindTable() is that this
82767 ** routine leaves an error message in pParse->zErrMsg where
82768 ** sqlite3FindTable() does not.
82770 SQLITE_PRIVATE Table *sqlite3LocateTable(
82771 Parse *pParse, /* context in which to report errors */
82772 int isView, /* True if looking for a VIEW rather than a TABLE */
82773 const char *zName, /* Name of the table we are looking for */
82774 const char *zDbase /* Name of the database. Might be NULL */
82776 Table *p;
82778 /* Read the database schema. If an error occurs, leave an error message
82779 ** and code in pParse and return NULL. */
82780 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82781 return 0;
82784 p = sqlite3FindTable(pParse->db, zName, zDbase);
82785 if( p==0 ){
82786 const char *zMsg = isView ? "no such view" : "no such table";
82787 if( zDbase ){
82788 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
82789 }else{
82790 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
82792 pParse->checkSchema = 1;
82794 return p;
82798 ** Locate the table identified by *p.
82800 ** This is a wrapper around sqlite3LocateTable(). The difference between
82801 ** sqlite3LocateTable() and this function is that this function restricts
82802 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
82803 ** non-NULL if it is part of a view or trigger program definition. See
82804 ** sqlite3FixSrcList() for details.
82806 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
82807 Parse *pParse,
82808 int isView,
82809 struct SrcList_item *p
82811 const char *zDb;
82812 assert( p->pSchema==0 || p->zDatabase==0 );
82813 if( p->pSchema ){
82814 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
82815 zDb = pParse->db->aDb[iDb].zName;
82816 }else{
82817 zDb = p->zDatabase;
82819 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
82823 ** Locate the in-memory structure that describes
82824 ** a particular index given the name of that index
82825 ** and the name of the database that contains the index.
82826 ** Return NULL if not found.
82828 ** If zDatabase is 0, all databases are searched for the
82829 ** table and the first matching index is returned. (No checking
82830 ** for duplicate index names is done.) The search order is
82831 ** TEMP first, then MAIN, then any auxiliary databases added
82832 ** using the ATTACH command.
82834 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
82835 Index *p = 0;
82836 int i;
82837 int nName = sqlite3Strlen30(zName);
82838 /* All mutexes are required for schema access. Make sure we hold them. */
82839 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
82840 for(i=OMIT_TEMPDB; i<db->nDb; i++){
82841 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
82842 Schema *pSchema = db->aDb[j].pSchema;
82843 assert( pSchema );
82844 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
82845 assert( sqlite3SchemaMutexHeld(db, j, 0) );
82846 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
82847 if( p ) break;
82849 return p;
82853 ** Reclaim the memory used by an index
82855 static void freeIndex(sqlite3 *db, Index *p){
82856 #ifndef SQLITE_OMIT_ANALYZE
82857 sqlite3DeleteIndexSamples(db, p);
82858 #endif
82859 sqlite3ExprDelete(db, p->pPartIdxWhere);
82860 sqlite3DbFree(db, p->zColAff);
82861 sqlite3DbFree(db, p);
82865 ** For the index called zIdxName which is found in the database iDb,
82866 ** unlike that index from its Table then remove the index from
82867 ** the index hash table and free all memory structures associated
82868 ** with the index.
82870 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
82871 Index *pIndex;
82872 int len;
82873 Hash *pHash;
82875 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82876 pHash = &db->aDb[iDb].pSchema->idxHash;
82877 len = sqlite3Strlen30(zIdxName);
82878 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
82879 if( ALWAYS(pIndex) ){
82880 if( pIndex->pTable->pIndex==pIndex ){
82881 pIndex->pTable->pIndex = pIndex->pNext;
82882 }else{
82883 Index *p;
82884 /* Justification of ALWAYS(); The index must be on the list of
82885 ** indices. */
82886 p = pIndex->pTable->pIndex;
82887 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
82888 if( ALWAYS(p && p->pNext==pIndex) ){
82889 p->pNext = pIndex->pNext;
82892 freeIndex(db, pIndex);
82894 db->flags |= SQLITE_InternChanges;
82898 ** Look through the list of open database files in db->aDb[] and if
82899 ** any have been closed, remove them from the list. Reallocate the
82900 ** db->aDb[] structure to a smaller size, if possible.
82902 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
82903 ** are never candidates for being collapsed.
82905 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
82906 int i, j;
82907 for(i=j=2; i<db->nDb; i++){
82908 struct Db *pDb = &db->aDb[i];
82909 if( pDb->pBt==0 ){
82910 sqlite3DbFree(db, pDb->zName);
82911 pDb->zName = 0;
82912 continue;
82914 if( j<i ){
82915 db->aDb[j] = db->aDb[i];
82917 j++;
82919 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
82920 db->nDb = j;
82921 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
82922 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
82923 sqlite3DbFree(db, db->aDb);
82924 db->aDb = db->aDbStatic;
82929 ** Reset the schema for the database at index iDb. Also reset the
82930 ** TEMP schema.
82932 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
82933 Db *pDb;
82934 assert( iDb<db->nDb );
82936 /* Case 1: Reset the single schema identified by iDb */
82937 pDb = &db->aDb[iDb];
82938 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82939 assert( pDb->pSchema!=0 );
82940 sqlite3SchemaClear(pDb->pSchema);
82942 /* If any database other than TEMP is reset, then also reset TEMP
82943 ** since TEMP might be holding triggers that reference tables in the
82944 ** other database.
82946 if( iDb!=1 ){
82947 pDb = &db->aDb[1];
82948 assert( pDb->pSchema!=0 );
82949 sqlite3SchemaClear(pDb->pSchema);
82951 return;
82955 ** Erase all schema information from all attached databases (including
82956 ** "main" and "temp") for a single database connection.
82958 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
82959 int i;
82960 sqlite3BtreeEnterAll(db);
82961 for(i=0; i<db->nDb; i++){
82962 Db *pDb = &db->aDb[i];
82963 if( pDb->pSchema ){
82964 sqlite3SchemaClear(pDb->pSchema);
82967 db->flags &= ~SQLITE_InternChanges;
82968 sqlite3VtabUnlockList(db);
82969 sqlite3BtreeLeaveAll(db);
82970 sqlite3CollapseDatabaseArray(db);
82974 ** This routine is called when a commit occurs.
82976 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
82977 db->flags &= ~SQLITE_InternChanges;
82981 ** Delete memory allocated for the column names of a table or view (the
82982 ** Table.aCol[] array).
82984 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
82985 int i;
82986 Column *pCol;
82987 assert( pTable!=0 );
82988 if( (pCol = pTable->aCol)!=0 ){
82989 for(i=0; i<pTable->nCol; i++, pCol++){
82990 sqlite3DbFree(db, pCol->zName);
82991 sqlite3ExprDelete(db, pCol->pDflt);
82992 sqlite3DbFree(db, pCol->zDflt);
82993 sqlite3DbFree(db, pCol->zType);
82994 sqlite3DbFree(db, pCol->zColl);
82996 sqlite3DbFree(db, pTable->aCol);
83001 ** Remove the memory data structures associated with the given
83002 ** Table. No changes are made to disk by this routine.
83004 ** This routine just deletes the data structure. It does not unlink
83005 ** the table data structure from the hash table. But it does destroy
83006 ** memory structures of the indices and foreign keys associated with
83007 ** the table.
83009 ** The db parameter is optional. It is needed if the Table object
83010 ** contains lookaside memory. (Table objects in the schema do not use
83011 ** lookaside memory, but some ephemeral Table objects do.) Or the
83012 ** db parameter can be used with db->pnBytesFreed to measure the memory
83013 ** used by the Table object.
83015 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
83016 Index *pIndex, *pNext;
83017 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
83019 assert( !pTable || pTable->nRef>0 );
83021 /* Do not delete the table until the reference count reaches zero. */
83022 if( !pTable ) return;
83023 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
83025 /* Record the number of outstanding lookaside allocations in schema Tables
83026 ** prior to doing any free() operations. Since schema Tables do not use
83027 ** lookaside, this number should not change. */
83028 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
83029 db->lookaside.nOut : 0 );
83031 /* Delete all indices associated with this table. */
83032 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
83033 pNext = pIndex->pNext;
83034 assert( pIndex->pSchema==pTable->pSchema );
83035 if( !db || db->pnBytesFreed==0 ){
83036 char *zName = pIndex->zName;
83037 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
83038 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
83040 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
83041 assert( pOld==pIndex || pOld==0 );
83043 freeIndex(db, pIndex);
83046 /* Delete any foreign keys attached to this table. */
83047 sqlite3FkDelete(db, pTable);
83049 /* Delete the Table structure itself.
83051 sqliteDeleteColumnNames(db, pTable);
83052 sqlite3DbFree(db, pTable->zName);
83053 sqlite3DbFree(db, pTable->zColAff);
83054 sqlite3SelectDelete(db, pTable->pSelect);
83055 #ifndef SQLITE_OMIT_CHECK
83056 sqlite3ExprListDelete(db, pTable->pCheck);
83057 #endif
83058 #ifndef SQLITE_OMIT_VIRTUALTABLE
83059 sqlite3VtabClear(db, pTable);
83060 #endif
83061 sqlite3DbFree(db, pTable);
83063 /* Verify that no lookaside memory was used by schema tables */
83064 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
83068 ** Unlink the given table from the hash tables and the delete the
83069 ** table structure with all its indices and foreign keys.
83071 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
83072 Table *p;
83073 Db *pDb;
83075 assert( db!=0 );
83076 assert( iDb>=0 && iDb<db->nDb );
83077 assert( zTabName );
83078 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83079 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
83080 pDb = &db->aDb[iDb];
83081 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
83082 sqlite3Strlen30(zTabName),0);
83083 sqlite3DeleteTable(db, p);
83084 db->flags |= SQLITE_InternChanges;
83088 ** Given a token, return a string that consists of the text of that
83089 ** token. Space to hold the returned string
83090 ** is obtained from sqliteMalloc() and must be freed by the calling
83091 ** function.
83093 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
83094 ** surround the body of the token are removed.
83096 ** Tokens are often just pointers into the original SQL text and so
83097 ** are not \000 terminated and are not persistent. The returned string
83098 ** is \000 terminated and is persistent.
83100 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
83101 char *zName;
83102 if( pName ){
83103 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
83104 sqlite3Dequote(zName);
83105 }else{
83106 zName = 0;
83108 return zName;
83112 ** Open the sqlite_master table stored in database number iDb for
83113 ** writing. The table is opened using cursor 0.
83115 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
83116 Vdbe *v = sqlite3GetVdbe(p);
83117 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
83118 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
83119 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
83120 if( p->nTab==0 ){
83121 p->nTab = 1;
83126 ** Parameter zName points to a nul-terminated buffer containing the name
83127 ** of a database ("main", "temp" or the name of an attached db). This
83128 ** function returns the index of the named database in db->aDb[], or
83129 ** -1 if the named db cannot be found.
83131 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
83132 int i = -1; /* Database number */
83133 if( zName ){
83134 Db *pDb;
83135 int n = sqlite3Strlen30(zName);
83136 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
83137 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
83138 0==sqlite3StrICmp(pDb->zName, zName) ){
83139 break;
83143 return i;
83147 ** The token *pName contains the name of a database (either "main" or
83148 ** "temp" or the name of an attached db). This routine returns the
83149 ** index of the named database in db->aDb[], or -1 if the named db
83150 ** does not exist.
83152 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
83153 int i; /* Database number */
83154 char *zName; /* Name we are searching for */
83155 zName = sqlite3NameFromToken(db, pName);
83156 i = sqlite3FindDbName(db, zName);
83157 sqlite3DbFree(db, zName);
83158 return i;
83161 /* The table or view or trigger name is passed to this routine via tokens
83162 ** pName1 and pName2. If the table name was fully qualified, for example:
83164 ** CREATE TABLE xxx.yyy (...);
83166 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
83167 ** the table name is not fully qualified, i.e.:
83169 ** CREATE TABLE yyy(...);
83171 ** Then pName1 is set to "yyy" and pName2 is "".
83173 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
83174 ** pName2) that stores the unqualified table name. The index of the
83175 ** database "xxx" is returned.
83177 SQLITE_PRIVATE int sqlite3TwoPartName(
83178 Parse *pParse, /* Parsing and code generating context */
83179 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
83180 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
83181 Token **pUnqual /* Write the unqualified object name here */
83183 int iDb; /* Database holding the object */
83184 sqlite3 *db = pParse->db;
83186 if( ALWAYS(pName2!=0) && pName2->n>0 ){
83187 if( db->init.busy ) {
83188 sqlite3ErrorMsg(pParse, "corrupt database");
83189 pParse->nErr++;
83190 return -1;
83192 *pUnqual = pName2;
83193 iDb = sqlite3FindDb(db, pName1);
83194 if( iDb<0 ){
83195 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
83196 pParse->nErr++;
83197 return -1;
83199 }else{
83200 assert( db->init.iDb==0 || db->init.busy );
83201 iDb = db->init.iDb;
83202 *pUnqual = pName1;
83204 return iDb;
83208 ** This routine is used to check if the UTF-8 string zName is a legal
83209 ** unqualified name for a new schema object (table, index, view or
83210 ** trigger). All names are legal except those that begin with the string
83211 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
83212 ** is reserved for internal use.
83214 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
83215 if( !pParse->db->init.busy && pParse->nested==0
83216 && (pParse->db->flags & SQLITE_WriteSchema)==0
83217 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
83218 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
83219 return SQLITE_ERROR;
83221 return SQLITE_OK;
83225 ** Begin constructing a new table representation in memory. This is
83226 ** the first of several action routines that get called in response
83227 ** to a CREATE TABLE statement. In particular, this routine is called
83228 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
83229 ** flag is true if the table should be stored in the auxiliary database
83230 ** file instead of in the main database file. This is normally the case
83231 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
83232 ** CREATE and TABLE.
83234 ** The new table record is initialized and put in pParse->pNewTable.
83235 ** As more of the CREATE TABLE statement is parsed, additional action
83236 ** routines will be called to add more information to this record.
83237 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
83238 ** is called to complete the construction of the new table record.
83240 SQLITE_PRIVATE void sqlite3StartTable(
83241 Parse *pParse, /* Parser context */
83242 Token *pName1, /* First part of the name of the table or view */
83243 Token *pName2, /* Second part of the name of the table or view */
83244 int isTemp, /* True if this is a TEMP table */
83245 int isView, /* True if this is a VIEW */
83246 int isVirtual, /* True if this is a VIRTUAL table */
83247 int noErr /* Do nothing if table already exists */
83249 Table *pTable;
83250 char *zName = 0; /* The name of the new table */
83251 sqlite3 *db = pParse->db;
83252 Vdbe *v;
83253 int iDb; /* Database number to create the table in */
83254 Token *pName; /* Unqualified name of the table to create */
83256 /* The table or view name to create is passed to this routine via tokens
83257 ** pName1 and pName2. If the table name was fully qualified, for example:
83259 ** CREATE TABLE xxx.yyy (...);
83261 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
83262 ** the table name is not fully qualified, i.e.:
83264 ** CREATE TABLE yyy(...);
83266 ** Then pName1 is set to "yyy" and pName2 is "".
83268 ** The call below sets the pName pointer to point at the token (pName1 or
83269 ** pName2) that stores the unqualified table name. The variable iDb is
83270 ** set to the index of the database that the table or view is to be
83271 ** created in.
83273 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83274 if( iDb<0 ) return;
83275 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
83276 /* If creating a temp table, the name may not be qualified. Unless
83277 ** the database name is "temp" anyway. */
83278 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
83279 return;
83281 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
83283 pParse->sNameToken = *pName;
83284 zName = sqlite3NameFromToken(db, pName);
83285 if( zName==0 ) return;
83286 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83287 goto begin_table_error;
83289 if( db->init.iDb==1 ) isTemp = 1;
83290 #ifndef SQLITE_OMIT_AUTHORIZATION
83291 assert( (isTemp & 1)==isTemp );
83293 int code;
83294 char *zDb = db->aDb[iDb].zName;
83295 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
83296 goto begin_table_error;
83298 if( isView ){
83299 if( !OMIT_TEMPDB && isTemp ){
83300 code = SQLITE_CREATE_TEMP_VIEW;
83301 }else{
83302 code = SQLITE_CREATE_VIEW;
83304 }else{
83305 if( !OMIT_TEMPDB && isTemp ){
83306 code = SQLITE_CREATE_TEMP_TABLE;
83307 }else{
83308 code = SQLITE_CREATE_TABLE;
83311 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
83312 goto begin_table_error;
83315 #endif
83317 /* Make sure the new table name does not collide with an existing
83318 ** index or table name in the same database. Issue an error message if
83319 ** it does. The exception is if the statement being parsed was passed
83320 ** to an sqlite3_declare_vtab() call. In that case only the column names
83321 ** and types will be used, so there is no need to test for namespace
83322 ** collisions.
83324 if( !IN_DECLARE_VTAB ){
83325 char *zDb = db->aDb[iDb].zName;
83326 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83327 goto begin_table_error;
83329 pTable = sqlite3FindTable(db, zName, zDb);
83330 if( pTable ){
83331 if( !noErr ){
83332 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
83333 }else{
83334 assert( !db->init.busy );
83335 sqlite3CodeVerifySchema(pParse, iDb);
83337 goto begin_table_error;
83339 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
83340 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
83341 goto begin_table_error;
83345 pTable = sqlite3DbMallocZero(db, sizeof(Table));
83346 if( pTable==0 ){
83347 db->mallocFailed = 1;
83348 pParse->rc = SQLITE_NOMEM;
83349 pParse->nErr++;
83350 goto begin_table_error;
83352 pTable->zName = zName;
83353 pTable->iPKey = -1;
83354 pTable->pSchema = db->aDb[iDb].pSchema;
83355 pTable->nRef = 1;
83356 pTable->nRowEst = 1000000;
83357 assert( pParse->pNewTable==0 );
83358 pParse->pNewTable = pTable;
83360 /* If this is the magic sqlite_sequence table used by autoincrement,
83361 ** then record a pointer to this table in the main database structure
83362 ** so that INSERT can find the table easily.
83364 #ifndef SQLITE_OMIT_AUTOINCREMENT
83365 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
83366 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83367 pTable->pSchema->pSeqTab = pTable;
83369 #endif
83371 /* Begin generating the code that will insert the table record into
83372 ** the SQLITE_MASTER table. Note in particular that we must go ahead
83373 ** and allocate the record number for the table entry now. Before any
83374 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
83375 ** indices to be created and the table record must come before the
83376 ** indices. Hence, the record number for the table must be allocated
83377 ** now.
83379 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
83380 int j1;
83381 int fileFormat;
83382 int reg1, reg2, reg3;
83383 sqlite3BeginWriteOperation(pParse, 0, iDb);
83385 #ifndef SQLITE_OMIT_VIRTUALTABLE
83386 if( isVirtual ){
83387 sqlite3VdbeAddOp0(v, OP_VBegin);
83389 #endif
83391 /* If the file format and encoding in the database have not been set,
83392 ** set them now.
83394 reg1 = pParse->regRowid = ++pParse->nMem;
83395 reg2 = pParse->regRoot = ++pParse->nMem;
83396 reg3 = ++pParse->nMem;
83397 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
83398 sqlite3VdbeUsesBtree(v, iDb);
83399 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
83400 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
83401 1 : SQLITE_MAX_FILE_FORMAT;
83402 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
83403 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
83404 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
83405 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
83406 sqlite3VdbeJumpHere(v, j1);
83408 /* This just creates a place-holder record in the sqlite_master table.
83409 ** The record created does not contain anything yet. It will be replaced
83410 ** by the real entry in code generated at sqlite3EndTable().
83412 ** The rowid for the new entry is left in register pParse->regRowid.
83413 ** The root page number of the new table is left in reg pParse->regRoot.
83414 ** The rowid and root page number values are needed by the code that
83415 ** sqlite3EndTable will generate.
83417 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
83418 if( isView || isVirtual ){
83419 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
83420 }else
83421 #endif
83423 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
83425 sqlite3OpenMasterTable(pParse, iDb);
83426 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
83427 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
83428 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
83429 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
83430 sqlite3VdbeAddOp0(v, OP_Close);
83433 /* Normal (non-error) return. */
83434 return;
83436 /* If an error occurs, we jump here */
83437 begin_table_error:
83438 sqlite3DbFree(db, zName);
83439 return;
83443 ** This macro is used to compare two strings in a case-insensitive manner.
83444 ** It is slightly faster than calling sqlite3StrICmp() directly, but
83445 ** produces larger code.
83447 ** WARNING: This macro is not compatible with the strcmp() family. It
83448 ** returns true if the two strings are equal, otherwise false.
83450 #define STRICMP(x, y) (\
83451 sqlite3UpperToLower[*(unsigned char *)(x)]== \
83452 sqlite3UpperToLower[*(unsigned char *)(y)] \
83453 && sqlite3StrICmp((x)+1,(y)+1)==0 )
83456 ** Add a new column to the table currently being constructed.
83458 ** The parser calls this routine once for each column declaration
83459 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
83460 ** first to get things going. Then this routine is called for each
83461 ** column.
83463 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
83464 Table *p;
83465 int i;
83466 char *z;
83467 Column *pCol;
83468 sqlite3 *db = pParse->db;
83469 if( (p = pParse->pNewTable)==0 ) return;
83470 #if SQLITE_MAX_COLUMN
83471 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
83472 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
83473 return;
83475 #endif
83476 z = sqlite3NameFromToken(db, pName);
83477 if( z==0 ) return;
83478 for(i=0; i<p->nCol; i++){
83479 if( STRICMP(z, p->aCol[i].zName) ){
83480 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
83481 sqlite3DbFree(db, z);
83482 return;
83485 if( (p->nCol & 0x7)==0 ){
83486 Column *aNew;
83487 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
83488 if( aNew==0 ){
83489 sqlite3DbFree(db, z);
83490 return;
83492 p->aCol = aNew;
83494 pCol = &p->aCol[p->nCol];
83495 memset(pCol, 0, sizeof(p->aCol[0]));
83496 pCol->zName = z;
83498 /* If there is no type specified, columns have the default affinity
83499 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
83500 ** be called next to set pCol->affinity correctly.
83502 pCol->affinity = SQLITE_AFF_NONE;
83503 p->nCol++;
83507 ** This routine is called by the parser while in the middle of
83508 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
83509 ** been seen on a column. This routine sets the notNull flag on
83510 ** the column currently under construction.
83512 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
83513 Table *p;
83514 p = pParse->pNewTable;
83515 if( p==0 || NEVER(p->nCol<1) ) return;
83516 p->aCol[p->nCol-1].notNull = (u8)onError;
83520 ** Scan the column type name zType (length nType) and return the
83521 ** associated affinity type.
83523 ** This routine does a case-independent search of zType for the
83524 ** substrings in the following table. If one of the substrings is
83525 ** found, the corresponding affinity is returned. If zType contains
83526 ** more than one of the substrings, entries toward the top of
83527 ** the table take priority. For example, if zType is 'BLOBINT',
83528 ** SQLITE_AFF_INTEGER is returned.
83530 ** Substring | Affinity
83531 ** --------------------------------
83532 ** 'INT' | SQLITE_AFF_INTEGER
83533 ** 'CHAR' | SQLITE_AFF_TEXT
83534 ** 'CLOB' | SQLITE_AFF_TEXT
83535 ** 'TEXT' | SQLITE_AFF_TEXT
83536 ** 'BLOB' | SQLITE_AFF_NONE
83537 ** 'REAL' | SQLITE_AFF_REAL
83538 ** 'FLOA' | SQLITE_AFF_REAL
83539 ** 'DOUB' | SQLITE_AFF_REAL
83541 ** If none of the substrings in the above table are found,
83542 ** SQLITE_AFF_NUMERIC is returned.
83544 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
83545 u32 h = 0;
83546 char aff = SQLITE_AFF_NUMERIC;
83548 if( zIn ) while( zIn[0] ){
83549 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
83550 zIn++;
83551 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
83552 aff = SQLITE_AFF_TEXT;
83553 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
83554 aff = SQLITE_AFF_TEXT;
83555 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
83556 aff = SQLITE_AFF_TEXT;
83557 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
83558 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
83559 aff = SQLITE_AFF_NONE;
83560 #ifndef SQLITE_OMIT_FLOATING_POINT
83561 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
83562 && aff==SQLITE_AFF_NUMERIC ){
83563 aff = SQLITE_AFF_REAL;
83564 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
83565 && aff==SQLITE_AFF_NUMERIC ){
83566 aff = SQLITE_AFF_REAL;
83567 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
83568 && aff==SQLITE_AFF_NUMERIC ){
83569 aff = SQLITE_AFF_REAL;
83570 #endif
83571 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
83572 aff = SQLITE_AFF_INTEGER;
83573 break;
83577 return aff;
83581 ** This routine is called by the parser while in the middle of
83582 ** parsing a CREATE TABLE statement. The pFirst token is the first
83583 ** token in the sequence of tokens that describe the type of the
83584 ** column currently under construction. pLast is the last token
83585 ** in the sequence. Use this information to construct a string
83586 ** that contains the typename of the column and store that string
83587 ** in zType.
83589 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
83590 Table *p;
83591 Column *pCol;
83593 p = pParse->pNewTable;
83594 if( p==0 || NEVER(p->nCol<1) ) return;
83595 pCol = &p->aCol[p->nCol-1];
83596 assert( pCol->zType==0 );
83597 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
83598 pCol->affinity = sqlite3AffinityType(pCol->zType);
83602 ** The expression is the default value for the most recently added column
83603 ** of the table currently under construction.
83605 ** Default value expressions must be constant. Raise an exception if this
83606 ** is not the case.
83608 ** This routine is called by the parser while in the middle of
83609 ** parsing a CREATE TABLE statement.
83611 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
83612 Table *p;
83613 Column *pCol;
83614 sqlite3 *db = pParse->db;
83615 p = pParse->pNewTable;
83616 if( p!=0 ){
83617 pCol = &(p->aCol[p->nCol-1]);
83618 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
83619 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
83620 pCol->zName);
83621 }else{
83622 /* A copy of pExpr is used instead of the original, as pExpr contains
83623 ** tokens that point to volatile memory. The 'span' of the expression
83624 ** is required by pragma table_info.
83626 sqlite3ExprDelete(db, pCol->pDflt);
83627 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
83628 sqlite3DbFree(db, pCol->zDflt);
83629 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
83630 (int)(pSpan->zEnd - pSpan->zStart));
83633 sqlite3ExprDelete(db, pSpan->pExpr);
83637 ** Designate the PRIMARY KEY for the table. pList is a list of names
83638 ** of columns that form the primary key. If pList is NULL, then the
83639 ** most recently added column of the table is the primary key.
83641 ** A table can have at most one primary key. If the table already has
83642 ** a primary key (and this is the second primary key) then create an
83643 ** error.
83645 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
83646 ** then we will try to use that column as the rowid. Set the Table.iPKey
83647 ** field of the table under construction to be the index of the
83648 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
83649 ** no INTEGER PRIMARY KEY.
83651 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
83652 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
83654 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
83655 Parse *pParse, /* Parsing context */
83656 ExprList *pList, /* List of field names to be indexed */
83657 int onError, /* What to do with a uniqueness conflict */
83658 int autoInc, /* True if the AUTOINCREMENT keyword is present */
83659 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
83661 Table *pTab = pParse->pNewTable;
83662 char *zType = 0;
83663 int iCol = -1, i;
83664 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
83665 if( pTab->tabFlags & TF_HasPrimaryKey ){
83666 sqlite3ErrorMsg(pParse,
83667 "table \"%s\" has more than one primary key", pTab->zName);
83668 goto primary_key_exit;
83670 pTab->tabFlags |= TF_HasPrimaryKey;
83671 if( pList==0 ){
83672 iCol = pTab->nCol - 1;
83673 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
83674 }else{
83675 for(i=0; i<pList->nExpr; i++){
83676 for(iCol=0; iCol<pTab->nCol; iCol++){
83677 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
83678 break;
83681 if( iCol<pTab->nCol ){
83682 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
83685 if( pList->nExpr>1 ) iCol = -1;
83687 if( iCol>=0 && iCol<pTab->nCol ){
83688 zType = pTab->aCol[iCol].zType;
83690 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
83691 && sortOrder==SQLITE_SO_ASC ){
83692 pTab->iPKey = iCol;
83693 pTab->keyConf = (u8)onError;
83694 assert( autoInc==0 || autoInc==1 );
83695 pTab->tabFlags |= autoInc*TF_Autoincrement;
83696 }else if( autoInc ){
83697 #ifndef SQLITE_OMIT_AUTOINCREMENT
83698 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
83699 "INTEGER PRIMARY KEY");
83700 #endif
83701 }else{
83702 Index *p;
83703 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
83704 0, sortOrder, 0);
83705 if( p ){
83706 p->autoIndex = 2;
83708 pList = 0;
83711 primary_key_exit:
83712 sqlite3ExprListDelete(pParse->db, pList);
83713 return;
83717 ** Add a new CHECK constraint to the table currently under construction.
83719 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
83720 Parse *pParse, /* Parsing context */
83721 Expr *pCheckExpr /* The check expression */
83723 #ifndef SQLITE_OMIT_CHECK
83724 Table *pTab = pParse->pNewTable;
83725 if( pTab && !IN_DECLARE_VTAB ){
83726 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
83727 if( pParse->constraintName.n ){
83728 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
83730 }else
83731 #endif
83733 sqlite3ExprDelete(pParse->db, pCheckExpr);
83738 ** Set the collation function of the most recently parsed table column
83739 ** to the CollSeq given.
83741 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
83742 Table *p;
83743 int i;
83744 char *zColl; /* Dequoted name of collation sequence */
83745 sqlite3 *db;
83747 if( (p = pParse->pNewTable)==0 ) return;
83748 i = p->nCol-1;
83749 db = pParse->db;
83750 zColl = sqlite3NameFromToken(db, pToken);
83751 if( !zColl ) return;
83753 if( sqlite3LocateCollSeq(pParse, zColl) ){
83754 Index *pIdx;
83755 sqlite3DbFree(db, p->aCol[i].zColl);
83756 p->aCol[i].zColl = zColl;
83758 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
83759 ** then an index may have been created on this column before the
83760 ** collation type was added. Correct this if it is the case.
83762 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
83763 assert( pIdx->nColumn==1 );
83764 if( pIdx->aiColumn[0]==i ){
83765 pIdx->azColl[0] = p->aCol[i].zColl;
83768 }else{
83769 sqlite3DbFree(db, zColl);
83774 ** This function returns the collation sequence for database native text
83775 ** encoding identified by the string zName, length nName.
83777 ** If the requested collation sequence is not available, or not available
83778 ** in the database native encoding, the collation factory is invoked to
83779 ** request it. If the collation factory does not supply such a sequence,
83780 ** and the sequence is available in another text encoding, then that is
83781 ** returned instead.
83783 ** If no versions of the requested collations sequence are available, or
83784 ** another error occurs, NULL is returned and an error message written into
83785 ** pParse.
83787 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
83788 ** invokes the collation factory if the named collation cannot be found
83789 ** and generates an error message.
83791 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
83793 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
83794 sqlite3 *db = pParse->db;
83795 u8 enc = ENC(db);
83796 u8 initbusy = db->init.busy;
83797 CollSeq *pColl;
83799 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
83800 if( !initbusy && (!pColl || !pColl->xCmp) ){
83801 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
83804 return pColl;
83809 ** Generate code that will increment the schema cookie.
83811 ** The schema cookie is used to determine when the schema for the
83812 ** database changes. After each schema change, the cookie value
83813 ** changes. When a process first reads the schema it records the
83814 ** cookie. Thereafter, whenever it goes to access the database,
83815 ** it checks the cookie to make sure the schema has not changed
83816 ** since it was last read.
83818 ** This plan is not completely bullet-proof. It is possible for
83819 ** the schema to change multiple times and for the cookie to be
83820 ** set back to prior value. But schema changes are infrequent
83821 ** and the probability of hitting the same cookie value is only
83822 ** 1 chance in 2^32. So we're safe enough.
83824 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
83825 int r1 = sqlite3GetTempReg(pParse);
83826 sqlite3 *db = pParse->db;
83827 Vdbe *v = pParse->pVdbe;
83828 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83829 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
83830 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
83831 sqlite3ReleaseTempReg(pParse, r1);
83835 ** Measure the number of characters needed to output the given
83836 ** identifier. The number returned includes any quotes used
83837 ** but does not include the null terminator.
83839 ** The estimate is conservative. It might be larger that what is
83840 ** really needed.
83842 static int identLength(const char *z){
83843 int n;
83844 for(n=0; *z; n++, z++){
83845 if( *z=='"' ){ n++; }
83847 return n + 2;
83851 ** The first parameter is a pointer to an output buffer. The second
83852 ** parameter is a pointer to an integer that contains the offset at
83853 ** which to write into the output buffer. This function copies the
83854 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
83855 ** to the specified offset in the buffer and updates *pIdx to refer
83856 ** to the first byte after the last byte written before returning.
83858 ** If the string zSignedIdent consists entirely of alpha-numeric
83859 ** characters, does not begin with a digit and is not an SQL keyword,
83860 ** then it is copied to the output buffer exactly as it is. Otherwise,
83861 ** it is quoted using double-quotes.
83863 static void identPut(char *z, int *pIdx, char *zSignedIdent){
83864 unsigned char *zIdent = (unsigned char*)zSignedIdent;
83865 int i, j, needQuote;
83866 i = *pIdx;
83868 for(j=0; zIdent[j]; j++){
83869 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
83871 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
83872 if( !needQuote ){
83873 needQuote = zIdent[j];
83876 if( needQuote ) z[i++] = '"';
83877 for(j=0; zIdent[j]; j++){
83878 z[i++] = zIdent[j];
83879 if( zIdent[j]=='"' ) z[i++] = '"';
83881 if( needQuote ) z[i++] = '"';
83882 z[i] = 0;
83883 *pIdx = i;
83887 ** Generate a CREATE TABLE statement appropriate for the given
83888 ** table. Memory to hold the text of the statement is obtained
83889 ** from sqliteMalloc() and must be freed by the calling function.
83891 static char *createTableStmt(sqlite3 *db, Table *p){
83892 int i, k, n;
83893 char *zStmt;
83894 char *zSep, *zSep2, *zEnd;
83895 Column *pCol;
83896 n = 0;
83897 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
83898 n += identLength(pCol->zName) + 5;
83900 n += identLength(p->zName);
83901 if( n<50 ){
83902 zSep = "";
83903 zSep2 = ",";
83904 zEnd = ")";
83905 }else{
83906 zSep = "\n ";
83907 zSep2 = ",\n ";
83908 zEnd = "\n)";
83910 n += 35 + 6*p->nCol;
83911 zStmt = sqlite3DbMallocRaw(0, n);
83912 if( zStmt==0 ){
83913 db->mallocFailed = 1;
83914 return 0;
83916 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
83917 k = sqlite3Strlen30(zStmt);
83918 identPut(zStmt, &k, p->zName);
83919 zStmt[k++] = '(';
83920 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
83921 static const char * const azType[] = {
83922 /* SQLITE_AFF_TEXT */ " TEXT",
83923 /* SQLITE_AFF_NONE */ "",
83924 /* SQLITE_AFF_NUMERIC */ " NUM",
83925 /* SQLITE_AFF_INTEGER */ " INT",
83926 /* SQLITE_AFF_REAL */ " REAL"
83928 int len;
83929 const char *zType;
83931 sqlite3_snprintf(n-k, &zStmt[k], zSep);
83932 k += sqlite3Strlen30(&zStmt[k]);
83933 zSep = zSep2;
83934 identPut(zStmt, &k, pCol->zName);
83935 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
83936 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
83937 testcase( pCol->affinity==SQLITE_AFF_TEXT );
83938 testcase( pCol->affinity==SQLITE_AFF_NONE );
83939 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
83940 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
83941 testcase( pCol->affinity==SQLITE_AFF_REAL );
83943 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
83944 len = sqlite3Strlen30(zType);
83945 assert( pCol->affinity==SQLITE_AFF_NONE
83946 || pCol->affinity==sqlite3AffinityType(zType) );
83947 memcpy(&zStmt[k], zType, len);
83948 k += len;
83949 assert( k<=n );
83951 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
83952 return zStmt;
83956 ** This routine is called to report the final ")" that terminates
83957 ** a CREATE TABLE statement.
83959 ** The table structure that other action routines have been building
83960 ** is added to the internal hash tables, assuming no errors have
83961 ** occurred.
83963 ** An entry for the table is made in the master table on disk, unless
83964 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
83965 ** it means we are reading the sqlite_master table because we just
83966 ** connected to the database or because the sqlite_master table has
83967 ** recently changed, so the entry for this table already exists in
83968 ** the sqlite_master table. We do not want to create it again.
83970 ** If the pSelect argument is not NULL, it means that this routine
83971 ** was called to create a table generated from a
83972 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
83973 ** the new table will match the result set of the SELECT.
83975 SQLITE_PRIVATE void sqlite3EndTable(
83976 Parse *pParse, /* Parse context */
83977 Token *pCons, /* The ',' token after the last column defn. */
83978 Token *pEnd, /* The final ')' token in the CREATE TABLE */
83979 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
83981 Table *p;
83982 sqlite3 *db = pParse->db;
83983 int iDb;
83985 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
83986 return;
83988 p = pParse->pNewTable;
83989 if( p==0 ) return;
83991 assert( !db->init.busy || !pSelect );
83993 iDb = sqlite3SchemaToIndex(db, p->pSchema);
83995 #ifndef SQLITE_OMIT_CHECK
83996 /* Resolve names in all CHECK constraint expressions.
83998 if( p->pCheck ){
83999 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
84001 #endif /* !defined(SQLITE_OMIT_CHECK) */
84003 /* If the db->init.busy is 1 it means we are reading the SQL off the
84004 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
84005 ** So do not write to the disk again. Extract the root page number
84006 ** for the table from the db->init.newTnum field. (The page number
84007 ** should have been put there by the sqliteOpenCb routine.)
84009 if( db->init.busy ){
84010 p->tnum = db->init.newTnum;
84013 /* If not initializing, then create a record for the new table
84014 ** in the SQLITE_MASTER table of the database.
84016 ** If this is a TEMPORARY table, write the entry into the auxiliary
84017 ** file instead of into the main database file.
84019 if( !db->init.busy ){
84020 int n;
84021 Vdbe *v;
84022 char *zType; /* "view" or "table" */
84023 char *zType2; /* "VIEW" or "TABLE" */
84024 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
84026 v = sqlite3GetVdbe(pParse);
84027 if( NEVER(v==0) ) return;
84029 sqlite3VdbeAddOp1(v, OP_Close, 0);
84032 ** Initialize zType for the new view or table.
84034 if( p->pSelect==0 ){
84035 /* A regular table */
84036 zType = "table";
84037 zType2 = "TABLE";
84038 #ifndef SQLITE_OMIT_VIEW
84039 }else{
84040 /* A view */
84041 zType = "view";
84042 zType2 = "VIEW";
84043 #endif
84046 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
84047 ** statement to populate the new table. The root-page number for the
84048 ** new table is in register pParse->regRoot.
84050 ** Once the SELECT has been coded by sqlite3Select(), it is in a
84051 ** suitable state to query for the column names and types to be used
84052 ** by the new table.
84054 ** A shared-cache write-lock is not required to write to the new table,
84055 ** as a schema-lock must have already been obtained to create it. Since
84056 ** a schema-lock excludes all other database users, the write-lock would
84057 ** be redundant.
84059 if( pSelect ){
84060 SelectDest dest;
84061 Table *pSelTab;
84063 assert(pParse->nTab==1);
84064 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
84065 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
84066 pParse->nTab = 2;
84067 sqlite3SelectDestInit(&dest, SRT_Table, 1);
84068 sqlite3Select(pParse, pSelect, &dest);
84069 sqlite3VdbeAddOp1(v, OP_Close, 1);
84070 if( pParse->nErr==0 ){
84071 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
84072 if( pSelTab==0 ) return;
84073 assert( p->aCol==0 );
84074 p->nCol = pSelTab->nCol;
84075 p->aCol = pSelTab->aCol;
84076 pSelTab->nCol = 0;
84077 pSelTab->aCol = 0;
84078 sqlite3DeleteTable(db, pSelTab);
84082 /* Compute the complete text of the CREATE statement */
84083 if( pSelect ){
84084 zStmt = createTableStmt(db, p);
84085 }else{
84086 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
84087 zStmt = sqlite3MPrintf(db,
84088 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
84092 /* A slot for the record has already been allocated in the
84093 ** SQLITE_MASTER table. We just need to update that slot with all
84094 ** the information we've collected.
84096 sqlite3NestedParse(pParse,
84097 "UPDATE %Q.%s "
84098 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
84099 "WHERE rowid=#%d",
84100 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
84101 zType,
84102 p->zName,
84103 p->zName,
84104 pParse->regRoot,
84105 zStmt,
84106 pParse->regRowid
84108 sqlite3DbFree(db, zStmt);
84109 sqlite3ChangeCookie(pParse, iDb);
84111 #ifndef SQLITE_OMIT_AUTOINCREMENT
84112 /* Check to see if we need to create an sqlite_sequence table for
84113 ** keeping track of autoincrement keys.
84115 if( p->tabFlags & TF_Autoincrement ){
84116 Db *pDb = &db->aDb[iDb];
84117 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84118 if( pDb->pSchema->pSeqTab==0 ){
84119 sqlite3NestedParse(pParse,
84120 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
84121 pDb->zName
84125 #endif
84127 /* Reparse everything to update our internal data structures */
84128 sqlite3VdbeAddParseSchemaOp(v, iDb,
84129 sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
84133 /* Add the table to the in-memory representation of the database.
84135 if( db->init.busy ){
84136 Table *pOld;
84137 Schema *pSchema = p->pSchema;
84138 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84139 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
84140 sqlite3Strlen30(p->zName),p);
84141 if( pOld ){
84142 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
84143 db->mallocFailed = 1;
84144 return;
84146 pParse->pNewTable = 0;
84147 db->flags |= SQLITE_InternChanges;
84149 #ifndef SQLITE_OMIT_ALTERTABLE
84150 if( !p->pSelect ){
84151 const char *zName = (const char *)pParse->sNameToken.z;
84152 int nName;
84153 assert( !pSelect && pCons && pEnd );
84154 if( pCons->z==0 ){
84155 pCons = pEnd;
84157 nName = (int)((const char *)pCons->z - zName);
84158 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
84160 #endif
84164 #ifndef SQLITE_OMIT_VIEW
84166 ** The parser calls this routine in order to create a new VIEW
84168 SQLITE_PRIVATE void sqlite3CreateView(
84169 Parse *pParse, /* The parsing context */
84170 Token *pBegin, /* The CREATE token that begins the statement */
84171 Token *pName1, /* The token that holds the name of the view */
84172 Token *pName2, /* The token that holds the name of the view */
84173 Select *pSelect, /* A SELECT statement that will become the new view */
84174 int isTemp, /* TRUE for a TEMPORARY view */
84175 int noErr /* Suppress error messages if VIEW already exists */
84177 Table *p;
84178 int n;
84179 const char *z;
84180 Token sEnd;
84181 DbFixer sFix;
84182 Token *pName = 0;
84183 int iDb;
84184 sqlite3 *db = pParse->db;
84186 if( pParse->nVar>0 ){
84187 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
84188 sqlite3SelectDelete(db, pSelect);
84189 return;
84191 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
84192 p = pParse->pNewTable;
84193 if( p==0 || pParse->nErr ){
84194 sqlite3SelectDelete(db, pSelect);
84195 return;
84197 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
84198 iDb = sqlite3SchemaToIndex(db, p->pSchema);
84199 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
84200 && sqlite3FixSelect(&sFix, pSelect)
84202 sqlite3SelectDelete(db, pSelect);
84203 return;
84206 /* Make a copy of the entire SELECT statement that defines the view.
84207 ** This will force all the Expr.token.z values to be dynamically
84208 ** allocated rather than point to the input string - which means that
84209 ** they will persist after the current sqlite3_exec() call returns.
84211 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
84212 sqlite3SelectDelete(db, pSelect);
84213 if( db->mallocFailed ){
84214 return;
84216 if( !db->init.busy ){
84217 sqlite3ViewGetColumnNames(pParse, p);
84220 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
84221 ** the end.
84223 sEnd = pParse->sLastToken;
84224 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
84225 sEnd.z += sEnd.n;
84227 sEnd.n = 0;
84228 n = (int)(sEnd.z - pBegin->z);
84229 z = pBegin->z;
84230 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
84231 sEnd.z = &z[n-1];
84232 sEnd.n = 1;
84234 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
84235 sqlite3EndTable(pParse, 0, &sEnd, 0);
84236 return;
84238 #endif /* SQLITE_OMIT_VIEW */
84240 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
84242 ** The Table structure pTable is really a VIEW. Fill in the names of
84243 ** the columns of the view in the pTable structure. Return the number
84244 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
84246 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
84247 Table *pSelTab; /* A fake table from which we get the result set */
84248 Select *pSel; /* Copy of the SELECT that implements the view */
84249 int nErr = 0; /* Number of errors encountered */
84250 int n; /* Temporarily holds the number of cursors assigned */
84251 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
84252 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
84254 assert( pTable );
84256 #ifndef SQLITE_OMIT_VIRTUALTABLE
84257 if( sqlite3VtabCallConnect(pParse, pTable) ){
84258 return SQLITE_ERROR;
84260 if( IsVirtual(pTable) ) return 0;
84261 #endif
84263 #ifndef SQLITE_OMIT_VIEW
84264 /* A positive nCol means the columns names for this view are
84265 ** already known.
84267 if( pTable->nCol>0 ) return 0;
84269 /* A negative nCol is a special marker meaning that we are currently
84270 ** trying to compute the column names. If we enter this routine with
84271 ** a negative nCol, it means two or more views form a loop, like this:
84273 ** CREATE VIEW one AS SELECT * FROM two;
84274 ** CREATE VIEW two AS SELECT * FROM one;
84276 ** Actually, the error above is now caught prior to reaching this point.
84277 ** But the following test is still important as it does come up
84278 ** in the following:
84280 ** CREATE TABLE main.ex1(a);
84281 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
84282 ** SELECT * FROM temp.ex1;
84284 if( pTable->nCol<0 ){
84285 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
84286 return 1;
84288 assert( pTable->nCol>=0 );
84290 /* If we get this far, it means we need to compute the table names.
84291 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
84292 ** "*" elements in the results set of the view and will assign cursors
84293 ** to the elements of the FROM clause. But we do not want these changes
84294 ** to be permanent. So the computation is done on a copy of the SELECT
84295 ** statement that defines the view.
84297 assert( pTable->pSelect );
84298 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
84299 if( pSel ){
84300 u8 enableLookaside = db->lookaside.bEnabled;
84301 n = pParse->nTab;
84302 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
84303 pTable->nCol = -1;
84304 db->lookaside.bEnabled = 0;
84305 #ifndef SQLITE_OMIT_AUTHORIZATION
84306 xAuth = db->xAuth;
84307 db->xAuth = 0;
84308 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
84309 db->xAuth = xAuth;
84310 #else
84311 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
84312 #endif
84313 db->lookaside.bEnabled = enableLookaside;
84314 pParse->nTab = n;
84315 if( pSelTab ){
84316 assert( pTable->aCol==0 );
84317 pTable->nCol = pSelTab->nCol;
84318 pTable->aCol = pSelTab->aCol;
84319 pSelTab->nCol = 0;
84320 pSelTab->aCol = 0;
84321 sqlite3DeleteTable(db, pSelTab);
84322 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
84323 pTable->pSchema->flags |= DB_UnresetViews;
84324 }else{
84325 pTable->nCol = 0;
84326 nErr++;
84328 sqlite3SelectDelete(db, pSel);
84329 } else {
84330 nErr++;
84332 #endif /* SQLITE_OMIT_VIEW */
84333 return nErr;
84335 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
84337 #ifndef SQLITE_OMIT_VIEW
84339 ** Clear the column names from every VIEW in database idx.
84341 static void sqliteViewResetAll(sqlite3 *db, int idx){
84342 HashElem *i;
84343 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
84344 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
84345 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
84346 Table *pTab = sqliteHashData(i);
84347 if( pTab->pSelect ){
84348 sqliteDeleteColumnNames(db, pTab);
84349 pTab->aCol = 0;
84350 pTab->nCol = 0;
84353 DbClearProperty(db, idx, DB_UnresetViews);
84355 #else
84356 # define sqliteViewResetAll(A,B)
84357 #endif /* SQLITE_OMIT_VIEW */
84360 ** This function is called by the VDBE to adjust the internal schema
84361 ** used by SQLite when the btree layer moves a table root page. The
84362 ** root-page of a table or index in database iDb has changed from iFrom
84363 ** to iTo.
84365 ** Ticket #1728: The symbol table might still contain information
84366 ** on tables and/or indices that are the process of being deleted.
84367 ** If you are unlucky, one of those deleted indices or tables might
84368 ** have the same rootpage number as the real table or index that is
84369 ** being moved. So we cannot stop searching after the first match
84370 ** because the first match might be for one of the deleted indices
84371 ** or tables and not the table/index that is actually being moved.
84372 ** We must continue looping until all tables and indices with
84373 ** rootpage==iFrom have been converted to have a rootpage of iTo
84374 ** in order to be certain that we got the right one.
84376 #ifndef SQLITE_OMIT_AUTOVACUUM
84377 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
84378 HashElem *pElem;
84379 Hash *pHash;
84380 Db *pDb;
84382 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84383 pDb = &db->aDb[iDb];
84384 pHash = &pDb->pSchema->tblHash;
84385 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
84386 Table *pTab = sqliteHashData(pElem);
84387 if( pTab->tnum==iFrom ){
84388 pTab->tnum = iTo;
84391 pHash = &pDb->pSchema->idxHash;
84392 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
84393 Index *pIdx = sqliteHashData(pElem);
84394 if( pIdx->tnum==iFrom ){
84395 pIdx->tnum = iTo;
84399 #endif
84402 ** Write code to erase the table with root-page iTable from database iDb.
84403 ** Also write code to modify the sqlite_master table and internal schema
84404 ** if a root-page of another table is moved by the btree-layer whilst
84405 ** erasing iTable (this can happen with an auto-vacuum database).
84407 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
84408 Vdbe *v = sqlite3GetVdbe(pParse);
84409 int r1 = sqlite3GetTempReg(pParse);
84410 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
84411 sqlite3MayAbort(pParse);
84412 #ifndef SQLITE_OMIT_AUTOVACUUM
84413 /* OP_Destroy stores an in integer r1. If this integer
84414 ** is non-zero, then it is the root page number of a table moved to
84415 ** location iTable. The following code modifies the sqlite_master table to
84416 ** reflect this.
84418 ** The "#NNN" in the SQL is a special constant that means whatever value
84419 ** is in register NNN. See grammar rules associated with the TK_REGISTER
84420 ** token for additional information.
84422 sqlite3NestedParse(pParse,
84423 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
84424 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
84425 #endif
84426 sqlite3ReleaseTempReg(pParse, r1);
84430 ** Write VDBE code to erase table pTab and all associated indices on disk.
84431 ** Code to update the sqlite_master tables and internal schema definitions
84432 ** in case a root-page belonging to another table is moved by the btree layer
84433 ** is also added (this can happen with an auto-vacuum database).
84435 static void destroyTable(Parse *pParse, Table *pTab){
84436 #ifdef SQLITE_OMIT_AUTOVACUUM
84437 Index *pIdx;
84438 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84439 destroyRootPage(pParse, pTab->tnum, iDb);
84440 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84441 destroyRootPage(pParse, pIdx->tnum, iDb);
84443 #else
84444 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
84445 ** is not defined), then it is important to call OP_Destroy on the
84446 ** table and index root-pages in order, starting with the numerically
84447 ** largest root-page number. This guarantees that none of the root-pages
84448 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
84449 ** following were coded:
84451 ** OP_Destroy 4 0
84452 ** ...
84453 ** OP_Destroy 5 0
84455 ** and root page 5 happened to be the largest root-page number in the
84456 ** database, then root page 5 would be moved to page 4 by the
84457 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
84458 ** a free-list page.
84460 int iTab = pTab->tnum;
84461 int iDestroyed = 0;
84463 while( 1 ){
84464 Index *pIdx;
84465 int iLargest = 0;
84467 if( iDestroyed==0 || iTab<iDestroyed ){
84468 iLargest = iTab;
84470 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84471 int iIdx = pIdx->tnum;
84472 assert( pIdx->pSchema==pTab->pSchema );
84473 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
84474 iLargest = iIdx;
84477 if( iLargest==0 ){
84478 return;
84479 }else{
84480 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84481 assert( iDb>=0 && iDb<pParse->db->nDb );
84482 destroyRootPage(pParse, iLargest, iDb);
84483 iDestroyed = iLargest;
84486 #endif
84490 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
84491 ** after a DROP INDEX or DROP TABLE command.
84493 static void sqlite3ClearStatTables(
84494 Parse *pParse, /* The parsing context */
84495 int iDb, /* The database number */
84496 const char *zType, /* "idx" or "tbl" */
84497 const char *zName /* Name of index or table */
84499 int i;
84500 const char *zDbName = pParse->db->aDb[iDb].zName;
84501 for(i=1; i<=3; i++){
84502 char zTab[24];
84503 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
84504 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
84505 sqlite3NestedParse(pParse,
84506 "DELETE FROM %Q.%s WHERE %s=%Q",
84507 zDbName, zTab, zType, zName
84514 ** Generate code to drop a table.
84516 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
84517 Vdbe *v;
84518 sqlite3 *db = pParse->db;
84519 Trigger *pTrigger;
84520 Db *pDb = &db->aDb[iDb];
84522 v = sqlite3GetVdbe(pParse);
84523 assert( v!=0 );
84524 sqlite3BeginWriteOperation(pParse, 1, iDb);
84526 #ifndef SQLITE_OMIT_VIRTUALTABLE
84527 if( IsVirtual(pTab) ){
84528 sqlite3VdbeAddOp0(v, OP_VBegin);
84530 #endif
84532 /* Drop all triggers associated with the table being dropped. Code
84533 ** is generated to remove entries from sqlite_master and/or
84534 ** sqlite_temp_master if required.
84536 pTrigger = sqlite3TriggerList(pParse, pTab);
84537 while( pTrigger ){
84538 assert( pTrigger->pSchema==pTab->pSchema ||
84539 pTrigger->pSchema==db->aDb[1].pSchema );
84540 sqlite3DropTriggerPtr(pParse, pTrigger);
84541 pTrigger = pTrigger->pNext;
84544 #ifndef SQLITE_OMIT_AUTOINCREMENT
84545 /* Remove any entries of the sqlite_sequence table associated with
84546 ** the table being dropped. This is done before the table is dropped
84547 ** at the btree level, in case the sqlite_sequence table needs to
84548 ** move as a result of the drop (can happen in auto-vacuum mode).
84550 if( pTab->tabFlags & TF_Autoincrement ){
84551 sqlite3NestedParse(pParse,
84552 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
84553 pDb->zName, pTab->zName
84556 #endif
84558 /* Drop all SQLITE_MASTER table and index entries that refer to the
84559 ** table. The program name loops through the master table and deletes
84560 ** every row that refers to a table of the same name as the one being
84561 ** dropped. Triggers are handled separately because a trigger can be
84562 ** created in the temp database that refers to a table in another
84563 ** database.
84565 sqlite3NestedParse(pParse,
84566 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
84567 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
84568 if( !isView && !IsVirtual(pTab) ){
84569 destroyTable(pParse, pTab);
84572 /* Remove the table entry from SQLite's internal schema and modify
84573 ** the schema cookie.
84575 if( IsVirtual(pTab) ){
84576 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
84578 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
84579 sqlite3ChangeCookie(pParse, iDb);
84580 sqliteViewResetAll(db, iDb);
84584 ** This routine is called to do the work of a DROP TABLE statement.
84585 ** pName is the name of the table to be dropped.
84587 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
84588 Table *pTab;
84589 Vdbe *v;
84590 sqlite3 *db = pParse->db;
84591 int iDb;
84593 if( db->mallocFailed ){
84594 goto exit_drop_table;
84596 assert( pParse->nErr==0 );
84597 assert( pName->nSrc==1 );
84598 if( noErr ) db->suppressErr++;
84599 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
84600 if( noErr ) db->suppressErr--;
84602 if( pTab==0 ){
84603 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
84604 goto exit_drop_table;
84606 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84607 assert( iDb>=0 && iDb<db->nDb );
84609 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
84610 ** it is initialized.
84612 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
84613 goto exit_drop_table;
84615 #ifndef SQLITE_OMIT_AUTHORIZATION
84617 int code;
84618 const char *zTab = SCHEMA_TABLE(iDb);
84619 const char *zDb = db->aDb[iDb].zName;
84620 const char *zArg2 = 0;
84621 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
84622 goto exit_drop_table;
84624 if( isView ){
84625 if( !OMIT_TEMPDB && iDb==1 ){
84626 code = SQLITE_DROP_TEMP_VIEW;
84627 }else{
84628 code = SQLITE_DROP_VIEW;
84630 #ifndef SQLITE_OMIT_VIRTUALTABLE
84631 }else if( IsVirtual(pTab) ){
84632 code = SQLITE_DROP_VTABLE;
84633 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
84634 #endif
84635 }else{
84636 if( !OMIT_TEMPDB && iDb==1 ){
84637 code = SQLITE_DROP_TEMP_TABLE;
84638 }else{
84639 code = SQLITE_DROP_TABLE;
84642 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
84643 goto exit_drop_table;
84645 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
84646 goto exit_drop_table;
84649 #endif
84650 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
84651 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
84652 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
84653 goto exit_drop_table;
84656 #ifndef SQLITE_OMIT_VIEW
84657 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
84658 ** on a table.
84660 if( isView && pTab->pSelect==0 ){
84661 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
84662 goto exit_drop_table;
84664 if( !isView && pTab->pSelect ){
84665 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
84666 goto exit_drop_table;
84668 #endif
84670 /* Generate code to remove the table from the master table
84671 ** on disk.
84673 v = sqlite3GetVdbe(pParse);
84674 if( v ){
84675 sqlite3BeginWriteOperation(pParse, 1, iDb);
84676 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
84677 sqlite3FkDropTable(pParse, pName, pTab);
84678 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
84681 exit_drop_table:
84682 sqlite3SrcListDelete(db, pName);
84686 ** This routine is called to create a new foreign key on the table
84687 ** currently under construction. pFromCol determines which columns
84688 ** in the current table point to the foreign key. If pFromCol==0 then
84689 ** connect the key to the last column inserted. pTo is the name of
84690 ** the table referred to. pToCol is a list of tables in the other
84691 ** pTo table that the foreign key points to. flags contains all
84692 ** information about the conflict resolution algorithms specified
84693 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
84695 ** An FKey structure is created and added to the table currently
84696 ** under construction in the pParse->pNewTable field.
84698 ** The foreign key is set for IMMEDIATE processing. A subsequent call
84699 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
84701 SQLITE_PRIVATE void sqlite3CreateForeignKey(
84702 Parse *pParse, /* Parsing context */
84703 ExprList *pFromCol, /* Columns in this table that point to other table */
84704 Token *pTo, /* Name of the other table */
84705 ExprList *pToCol, /* Columns in the other table */
84706 int flags /* Conflict resolution algorithms. */
84708 sqlite3 *db = pParse->db;
84709 #ifndef SQLITE_OMIT_FOREIGN_KEY
84710 FKey *pFKey = 0;
84711 FKey *pNextTo;
84712 Table *p = pParse->pNewTable;
84713 int nByte;
84714 int i;
84715 int nCol;
84716 char *z;
84718 assert( pTo!=0 );
84719 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
84720 if( pFromCol==0 ){
84721 int iCol = p->nCol-1;
84722 if( NEVER(iCol<0) ) goto fk_end;
84723 if( pToCol && pToCol->nExpr!=1 ){
84724 sqlite3ErrorMsg(pParse, "foreign key on %s"
84725 " should reference only one column of table %T",
84726 p->aCol[iCol].zName, pTo);
84727 goto fk_end;
84729 nCol = 1;
84730 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
84731 sqlite3ErrorMsg(pParse,
84732 "number of columns in foreign key does not match the number of "
84733 "columns in the referenced table");
84734 goto fk_end;
84735 }else{
84736 nCol = pFromCol->nExpr;
84738 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
84739 if( pToCol ){
84740 for(i=0; i<pToCol->nExpr; i++){
84741 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
84744 pFKey = sqlite3DbMallocZero(db, nByte );
84745 if( pFKey==0 ){
84746 goto fk_end;
84748 pFKey->pFrom = p;
84749 pFKey->pNextFrom = p->pFKey;
84750 z = (char*)&pFKey->aCol[nCol];
84751 pFKey->zTo = z;
84752 memcpy(z, pTo->z, pTo->n);
84753 z[pTo->n] = 0;
84754 sqlite3Dequote(z);
84755 z += pTo->n+1;
84756 pFKey->nCol = nCol;
84757 if( pFromCol==0 ){
84758 pFKey->aCol[0].iFrom = p->nCol-1;
84759 }else{
84760 for(i=0; i<nCol; i++){
84761 int j;
84762 for(j=0; j<p->nCol; j++){
84763 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
84764 pFKey->aCol[i].iFrom = j;
84765 break;
84768 if( j>=p->nCol ){
84769 sqlite3ErrorMsg(pParse,
84770 "unknown column \"%s\" in foreign key definition",
84771 pFromCol->a[i].zName);
84772 goto fk_end;
84776 if( pToCol ){
84777 for(i=0; i<nCol; i++){
84778 int n = sqlite3Strlen30(pToCol->a[i].zName);
84779 pFKey->aCol[i].zCol = z;
84780 memcpy(z, pToCol->a[i].zName, n);
84781 z[n] = 0;
84782 z += n+1;
84785 pFKey->isDeferred = 0;
84786 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
84787 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
84789 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
84790 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
84791 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
84793 if( pNextTo==pFKey ){
84794 db->mallocFailed = 1;
84795 goto fk_end;
84797 if( pNextTo ){
84798 assert( pNextTo->pPrevTo==0 );
84799 pFKey->pNextTo = pNextTo;
84800 pNextTo->pPrevTo = pFKey;
84803 /* Link the foreign key to the table as the last step.
84805 p->pFKey = pFKey;
84806 pFKey = 0;
84808 fk_end:
84809 sqlite3DbFree(db, pFKey);
84810 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
84811 sqlite3ExprListDelete(db, pFromCol);
84812 sqlite3ExprListDelete(db, pToCol);
84816 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
84817 ** clause is seen as part of a foreign key definition. The isDeferred
84818 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
84819 ** The behavior of the most recently created foreign key is adjusted
84820 ** accordingly.
84822 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
84823 #ifndef SQLITE_OMIT_FOREIGN_KEY
84824 Table *pTab;
84825 FKey *pFKey;
84826 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
84827 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
84828 pFKey->isDeferred = (u8)isDeferred;
84829 #endif
84833 ** Generate code that will erase and refill index *pIdx. This is
84834 ** used to initialize a newly created index or to recompute the
84835 ** content of an index in response to a REINDEX command.
84837 ** if memRootPage is not negative, it means that the index is newly
84838 ** created. The register specified by memRootPage contains the
84839 ** root page number of the index. If memRootPage is negative, then
84840 ** the index already exists and must be cleared before being refilled and
84841 ** the root page number of the index is taken from pIndex->tnum.
84843 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
84844 Table *pTab = pIndex->pTable; /* The table that is indexed */
84845 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
84846 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
84847 int iSorter; /* Cursor opened by OpenSorter (if in use) */
84848 int addr1; /* Address of top of loop */
84849 int addr2; /* Address to jump to for next iteration */
84850 int tnum; /* Root page of index */
84851 int iPartIdxLabel; /* Jump to this label to skip a row */
84852 Vdbe *v; /* Generate code into this virtual machine */
84853 KeyInfo *pKey; /* KeyInfo for index */
84854 int regRecord; /* Register holding assemblied index record */
84855 sqlite3 *db = pParse->db; /* The database connection */
84856 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
84858 #ifndef SQLITE_OMIT_AUTHORIZATION
84859 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
84860 db->aDb[iDb].zName ) ){
84861 return;
84863 #endif
84865 /* Require a write-lock on the table to perform this operation */
84866 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
84868 v = sqlite3GetVdbe(pParse);
84869 if( v==0 ) return;
84870 if( memRootPage>=0 ){
84871 tnum = memRootPage;
84872 }else{
84873 tnum = pIndex->tnum;
84874 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
84876 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
84877 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
84878 (char *)pKey, P4_KEYINFO_HANDOFF);
84879 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
84881 /* Open the sorter cursor if we are to use one. */
84882 iSorter = pParse->nTab++;
84883 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
84885 /* Open the table. Loop through all rows of the table, inserting index
84886 ** records into the sorter. */
84887 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
84888 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
84889 regRecord = sqlite3GetTempReg(pParse);
84891 sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel);
84892 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
84893 sqlite3VdbeResolveLabel(v, iPartIdxLabel);
84894 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
84895 sqlite3VdbeJumpHere(v, addr1);
84896 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
84897 if( pIndex->onError!=OE_None ){
84898 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
84899 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
84900 addr2 = sqlite3VdbeCurrentAddr(v);
84901 sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
84902 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
84903 OE_Abort, "indexed columns are not unique", P4_STATIC
84905 }else{
84906 addr2 = sqlite3VdbeCurrentAddr(v);
84908 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
84909 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
84910 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
84911 sqlite3ReleaseTempReg(pParse, regRecord);
84912 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
84913 sqlite3VdbeJumpHere(v, addr1);
84915 sqlite3VdbeAddOp1(v, OP_Close, iTab);
84916 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
84917 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
84921 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
84922 ** and pTblList is the name of the table that is to be indexed. Both will
84923 ** be NULL for a primary key or an index that is created to satisfy a
84924 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
84925 ** as the table to be indexed. pParse->pNewTable is a table that is
84926 ** currently being constructed by a CREATE TABLE statement.
84928 ** pList is a list of columns to be indexed. pList will be NULL if this
84929 ** is a primary key or unique-constraint on the most recent column added
84930 ** to the table currently under construction.
84932 ** If the index is created successfully, return a pointer to the new Index
84933 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
84934 ** as the tables primary key (Index.autoIndex==2).
84936 SQLITE_PRIVATE Index *sqlite3CreateIndex(
84937 Parse *pParse, /* All information about this parse */
84938 Token *pName1, /* First part of index name. May be NULL */
84939 Token *pName2, /* Second part of index name. May be NULL */
84940 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
84941 ExprList *pList, /* A list of columns to be indexed */
84942 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
84943 Token *pStart, /* The CREATE token that begins this statement */
84944 Expr *pPIWhere, /* WHERE clause for partial indices */
84945 int sortOrder, /* Sort order of primary key when pList==NULL */
84946 int ifNotExist /* Omit error if index already exists */
84948 Index *pRet = 0; /* Pointer to return */
84949 Table *pTab = 0; /* Table to be indexed */
84950 Index *pIndex = 0; /* The index to be created */
84951 char *zName = 0; /* Name of the index */
84952 int nName; /* Number of characters in zName */
84953 int i, j;
84954 Token nullId; /* Fake token for an empty ID list */
84955 DbFixer sFix; /* For assigning database names to pTable */
84956 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
84957 sqlite3 *db = pParse->db;
84958 Db *pDb; /* The specific table containing the indexed database */
84959 int iDb; /* Index of the database that is being written */
84960 Token *pName = 0; /* Unqualified name of the index to create */
84961 struct ExprList_item *pListItem; /* For looping over pList */
84962 int nCol;
84963 int nExtra = 0;
84964 char *zExtra;
84966 assert( pParse->nErr==0 ); /* Never called with prior errors */
84967 if( db->mallocFailed || IN_DECLARE_VTAB ){
84968 goto exit_create_index;
84970 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84971 goto exit_create_index;
84975 ** Find the table that is to be indexed. Return early if not found.
84977 if( pTblName!=0 ){
84979 /* Use the two-part index name to determine the database
84980 ** to search for the table. 'Fix' the table name to this db
84981 ** before looking up the table.
84983 assert( pName1 && pName2 );
84984 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
84985 if( iDb<0 ) goto exit_create_index;
84986 assert( pName && pName->z );
84988 #ifndef SQLITE_OMIT_TEMPDB
84989 /* If the index name was unqualified, check if the table
84990 ** is a temp table. If so, set the database to 1. Do not do this
84991 ** if initialising a database schema.
84993 if( !db->init.busy ){
84994 pTab = sqlite3SrcListLookup(pParse, pTblName);
84995 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
84996 iDb = 1;
84999 #endif
85001 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
85002 sqlite3FixSrcList(&sFix, pTblName)
85004 /* Because the parser constructs pTblName from a single identifier,
85005 ** sqlite3FixSrcList can never fail. */
85006 assert(0);
85008 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
85009 assert( db->mallocFailed==0 || pTab==0 );
85010 if( pTab==0 ) goto exit_create_index;
85011 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
85012 sqlite3ErrorMsg(pParse,
85013 "cannot create a TEMP index on non-TEMP table \"%s\"",
85014 pTab->zName);
85015 goto exit_create_index;
85017 }else{
85018 assert( pName==0 );
85019 assert( pStart==0 );
85020 pTab = pParse->pNewTable;
85021 if( !pTab ) goto exit_create_index;
85022 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85024 pDb = &db->aDb[iDb];
85026 assert( pTab!=0 );
85027 assert( pParse->nErr==0 );
85028 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
85029 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
85030 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
85031 goto exit_create_index;
85033 #ifndef SQLITE_OMIT_VIEW
85034 if( pTab->pSelect ){
85035 sqlite3ErrorMsg(pParse, "views may not be indexed");
85036 goto exit_create_index;
85038 #endif
85039 #ifndef SQLITE_OMIT_VIRTUALTABLE
85040 if( IsVirtual(pTab) ){
85041 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
85042 goto exit_create_index;
85044 #endif
85047 ** Find the name of the index. Make sure there is not already another
85048 ** index or table with the same name.
85050 ** Exception: If we are reading the names of permanent indices from the
85051 ** sqlite_master table (because some other process changed the schema) and
85052 ** one of the index names collides with the name of a temporary table or
85053 ** index, then we will continue to process this index.
85055 ** If pName==0 it means that we are
85056 ** dealing with a primary key or UNIQUE constraint. We have to invent our
85057 ** own name.
85059 if( pName ){
85060 zName = sqlite3NameFromToken(db, pName);
85061 if( zName==0 ) goto exit_create_index;
85062 assert( pName->z!=0 );
85063 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
85064 goto exit_create_index;
85066 if( !db->init.busy ){
85067 if( sqlite3FindTable(db, zName, 0)!=0 ){
85068 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
85069 goto exit_create_index;
85072 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
85073 if( !ifNotExist ){
85074 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
85075 }else{
85076 assert( !db->init.busy );
85077 sqlite3CodeVerifySchema(pParse, iDb);
85079 goto exit_create_index;
85081 }else{
85082 int n;
85083 Index *pLoop;
85084 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
85085 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
85086 if( zName==0 ){
85087 goto exit_create_index;
85091 /* Check for authorization to create an index.
85093 #ifndef SQLITE_OMIT_AUTHORIZATION
85095 const char *zDb = pDb->zName;
85096 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
85097 goto exit_create_index;
85099 i = SQLITE_CREATE_INDEX;
85100 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
85101 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
85102 goto exit_create_index;
85105 #endif
85107 /* If pList==0, it means this routine was called to make a primary
85108 ** key out of the last column added to the table under construction.
85109 ** So create a fake list to simulate this.
85111 if( pList==0 ){
85112 nullId.z = pTab->aCol[pTab->nCol-1].zName;
85113 nullId.n = sqlite3Strlen30((char*)nullId.z);
85114 pList = sqlite3ExprListAppend(pParse, 0, 0);
85115 if( pList==0 ) goto exit_create_index;
85116 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
85117 pList->a[0].sortOrder = (u8)sortOrder;
85120 /* Figure out how many bytes of space are required to store explicitly
85121 ** specified collation sequence names.
85123 for(i=0; i<pList->nExpr; i++){
85124 Expr *pExpr = pList->a[i].pExpr;
85125 if( pExpr ){
85126 assert( pExpr->op==TK_COLLATE );
85127 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
85132 ** Allocate the index structure.
85134 nName = sqlite3Strlen30(zName);
85135 nCol = pList->nExpr;
85136 pIndex = sqlite3DbMallocZero(db,
85137 ROUND8(sizeof(Index)) + /* Index structure */
85138 ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
85139 sizeof(char *)*nCol + /* Index.azColl */
85140 sizeof(int)*nCol + /* Index.aiColumn */
85141 sizeof(u8)*nCol + /* Index.aSortOrder */
85142 nName + 1 + /* Index.zName */
85143 nExtra /* Collation sequence names */
85145 if( db->mallocFailed ){
85146 goto exit_create_index;
85148 zExtra = (char*)pIndex;
85149 pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
85150 pIndex->azColl = (char**)
85151 ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
85152 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
85153 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
85154 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
85155 pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
85156 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
85157 zExtra = (char *)(&pIndex->zName[nName+1]);
85158 memcpy(pIndex->zName, zName, nName+1);
85159 pIndex->pTable = pTab;
85160 pIndex->nColumn = pList->nExpr;
85161 pIndex->onError = (u8)onError;
85162 pIndex->uniqNotNull = onError==OE_Abort;
85163 pIndex->autoIndex = (u8)(pName==0);
85164 pIndex->pSchema = db->aDb[iDb].pSchema;
85165 if( pPIWhere ){
85166 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
85167 pIndex->pPartIdxWhere = pPIWhere;
85168 pPIWhere = 0;
85170 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
85172 /* Check to see if we should honor DESC requests on index columns
85174 if( pDb->pSchema->file_format>=4 ){
85175 sortOrderMask = -1; /* Honor DESC */
85176 }else{
85177 sortOrderMask = 0; /* Ignore DESC */
85180 /* Scan the names of the columns of the table to be indexed and
85181 ** load the column indices into the Index structure. Report an error
85182 ** if any column is not found.
85184 ** TODO: Add a test to make sure that the same column is not named
85185 ** more than once within the same index. Only the first instance of
85186 ** the column will ever be used by the optimizer. Note that using the
85187 ** same column more than once cannot be an error because that would
85188 ** break backwards compatibility - it needs to be a warning.
85190 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
85191 const char *zColName = pListItem->zName;
85192 Column *pTabCol;
85193 int requestedSortOrder;
85194 char *zColl; /* Collation sequence name */
85196 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
85197 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
85199 if( j>=pTab->nCol ){
85200 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
85201 pTab->zName, zColName);
85202 pParse->checkSchema = 1;
85203 goto exit_create_index;
85205 pIndex->aiColumn[i] = j;
85206 if( pListItem->pExpr ){
85207 int nColl;
85208 assert( pListItem->pExpr->op==TK_COLLATE );
85209 zColl = pListItem->pExpr->u.zToken;
85210 nColl = sqlite3Strlen30(zColl) + 1;
85211 assert( nExtra>=nColl );
85212 memcpy(zExtra, zColl, nColl);
85213 zColl = zExtra;
85214 zExtra += nColl;
85215 nExtra -= nColl;
85216 }else{
85217 zColl = pTab->aCol[j].zColl;
85218 if( !zColl ) zColl = "BINARY";
85220 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
85221 goto exit_create_index;
85223 pIndex->azColl[i] = zColl;
85224 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
85225 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
85226 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
85228 sqlite3DefaultRowEst(pIndex);
85230 if( pTab==pParse->pNewTable ){
85231 /* This routine has been called to create an automatic index as a
85232 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
85233 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
85234 ** i.e. one of:
85236 ** CREATE TABLE t(x PRIMARY KEY, y);
85237 ** CREATE TABLE t(x, y, UNIQUE(x, y));
85239 ** Either way, check to see if the table already has such an index. If
85240 ** so, don't bother creating this one. This only applies to
85241 ** automatically created indices. Users can do as they wish with
85242 ** explicit indices.
85244 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
85245 ** (and thus suppressing the second one) even if they have different
85246 ** sort orders.
85248 ** If there are different collating sequences or if the columns of
85249 ** the constraint occur in different orders, then the constraints are
85250 ** considered distinct and both result in separate indices.
85252 Index *pIdx;
85253 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85254 int k;
85255 assert( pIdx->onError!=OE_None );
85256 assert( pIdx->autoIndex );
85257 assert( pIndex->onError!=OE_None );
85259 if( pIdx->nColumn!=pIndex->nColumn ) continue;
85260 for(k=0; k<pIdx->nColumn; k++){
85261 const char *z1;
85262 const char *z2;
85263 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
85264 z1 = pIdx->azColl[k];
85265 z2 = pIndex->azColl[k];
85266 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
85268 if( k==pIdx->nColumn ){
85269 if( pIdx->onError!=pIndex->onError ){
85270 /* This constraint creates the same index as a previous
85271 ** constraint specified somewhere in the CREATE TABLE statement.
85272 ** However the ON CONFLICT clauses are different. If both this
85273 ** constraint and the previous equivalent constraint have explicit
85274 ** ON CONFLICT clauses this is an error. Otherwise, use the
85275 ** explicitly specified behavior for the index.
85277 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
85278 sqlite3ErrorMsg(pParse,
85279 "conflicting ON CONFLICT clauses specified", 0);
85281 if( pIdx->onError==OE_Default ){
85282 pIdx->onError = pIndex->onError;
85285 goto exit_create_index;
85290 /* Link the new Index structure to its table and to the other
85291 ** in-memory database structures.
85293 if( db->init.busy ){
85294 Index *p;
85295 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
85296 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
85297 pIndex->zName, sqlite3Strlen30(pIndex->zName),
85298 pIndex);
85299 if( p ){
85300 assert( p==pIndex ); /* Malloc must have failed */
85301 db->mallocFailed = 1;
85302 goto exit_create_index;
85304 db->flags |= SQLITE_InternChanges;
85305 if( pTblName!=0 ){
85306 pIndex->tnum = db->init.newTnum;
85310 /* If the db->init.busy is 0 then create the index on disk. This
85311 ** involves writing the index into the master table and filling in the
85312 ** index with the current table contents.
85314 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
85315 ** command. db->init.busy is 1 when a database is opened and
85316 ** CREATE INDEX statements are read out of the master table. In
85317 ** the latter case the index already exists on disk, which is why
85318 ** we don't want to recreate it.
85320 ** If pTblName==0 it means this index is generated as a primary key
85321 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
85322 ** has just been created, it contains no data and the index initialization
85323 ** step can be skipped.
85325 else if( pParse->nErr==0 ){
85326 Vdbe *v;
85327 char *zStmt;
85328 int iMem = ++pParse->nMem;
85330 v = sqlite3GetVdbe(pParse);
85331 if( v==0 ) goto exit_create_index;
85334 /* Create the rootpage for the index
85336 sqlite3BeginWriteOperation(pParse, 1, iDb);
85337 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
85339 /* Gather the complete text of the CREATE INDEX statement into
85340 ** the zStmt variable
85342 if( pStart ){
85343 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
85344 if( pName->z[n-1]==';' ) n--;
85345 /* A named index with an explicit CREATE INDEX statement */
85346 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
85347 onError==OE_None ? "" : " UNIQUE", n, pName->z);
85348 }else{
85349 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
85350 /* zStmt = sqlite3MPrintf(""); */
85351 zStmt = 0;
85354 /* Add an entry in sqlite_master for this index
85356 sqlite3NestedParse(pParse,
85357 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
85358 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
85359 pIndex->zName,
85360 pTab->zName,
85361 iMem,
85362 zStmt
85364 sqlite3DbFree(db, zStmt);
85366 /* Fill the index with data and reparse the schema. Code an OP_Expire
85367 ** to invalidate all pre-compiled statements.
85369 if( pTblName ){
85370 sqlite3RefillIndex(pParse, pIndex, iMem);
85371 sqlite3ChangeCookie(pParse, iDb);
85372 sqlite3VdbeAddParseSchemaOp(v, iDb,
85373 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
85374 sqlite3VdbeAddOp1(v, OP_Expire, 0);
85378 /* When adding an index to the list of indices for a table, make
85379 ** sure all indices labeled OE_Replace come after all those labeled
85380 ** OE_Ignore. This is necessary for the correct constraint check
85381 ** processing (in sqlite3GenerateConstraintChecks()) as part of
85382 ** UPDATE and INSERT statements.
85384 if( db->init.busy || pTblName==0 ){
85385 if( onError!=OE_Replace || pTab->pIndex==0
85386 || pTab->pIndex->onError==OE_Replace){
85387 pIndex->pNext = pTab->pIndex;
85388 pTab->pIndex = pIndex;
85389 }else{
85390 Index *pOther = pTab->pIndex;
85391 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
85392 pOther = pOther->pNext;
85394 pIndex->pNext = pOther->pNext;
85395 pOther->pNext = pIndex;
85397 pRet = pIndex;
85398 pIndex = 0;
85401 /* Clean up before exiting */
85402 exit_create_index:
85403 if( pIndex ) freeIndex(db, pIndex);
85404 sqlite3ExprDelete(db, pPIWhere);
85405 sqlite3ExprListDelete(db, pList);
85406 sqlite3SrcListDelete(db, pTblName);
85407 sqlite3DbFree(db, zName);
85408 return pRet;
85412 ** Fill the Index.aiRowEst[] array with default information - information
85413 ** to be used when we have not run the ANALYZE command.
85415 ** aiRowEst[0] is suppose to contain the number of elements in the index.
85416 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
85417 ** number of rows in the table that match any particular value of the
85418 ** first column of the index. aiRowEst[2] is an estimate of the number
85419 ** of rows that match any particular combiniation of the first 2 columns
85420 ** of the index. And so forth. It must always be the case that
85422 ** aiRowEst[N]<=aiRowEst[N-1]
85423 ** aiRowEst[N]>=1
85425 ** Apart from that, we have little to go on besides intuition as to
85426 ** how aiRowEst[] should be initialized. The numbers generated here
85427 ** are based on typical values found in actual indices.
85429 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
85430 tRowcnt *a = pIdx->aiRowEst;
85431 int i;
85432 tRowcnt n;
85433 assert( a!=0 );
85434 a[0] = pIdx->pTable->nRowEst;
85435 if( a[0]<10 ) a[0] = 10;
85436 n = 10;
85437 for(i=1; i<=pIdx->nColumn; i++){
85438 a[i] = n;
85439 if( n>5 ) n--;
85441 if( pIdx->onError!=OE_None ){
85442 a[pIdx->nColumn] = 1;
85447 ** This routine will drop an existing named index. This routine
85448 ** implements the DROP INDEX statement.
85450 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
85451 Index *pIndex;
85452 Vdbe *v;
85453 sqlite3 *db = pParse->db;
85454 int iDb;
85456 assert( pParse->nErr==0 ); /* Never called with prior errors */
85457 if( db->mallocFailed ){
85458 goto exit_drop_index;
85460 assert( pName->nSrc==1 );
85461 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85462 goto exit_drop_index;
85464 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
85465 if( pIndex==0 ){
85466 if( !ifExists ){
85467 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
85468 }else{
85469 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
85471 pParse->checkSchema = 1;
85472 goto exit_drop_index;
85474 if( pIndex->autoIndex ){
85475 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
85476 "or PRIMARY KEY constraint cannot be dropped", 0);
85477 goto exit_drop_index;
85479 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
85480 #ifndef SQLITE_OMIT_AUTHORIZATION
85482 int code = SQLITE_DROP_INDEX;
85483 Table *pTab = pIndex->pTable;
85484 const char *zDb = db->aDb[iDb].zName;
85485 const char *zTab = SCHEMA_TABLE(iDb);
85486 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
85487 goto exit_drop_index;
85489 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
85490 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
85491 goto exit_drop_index;
85494 #endif
85496 /* Generate code to remove the index and from the master table */
85497 v = sqlite3GetVdbe(pParse);
85498 if( v ){
85499 sqlite3BeginWriteOperation(pParse, 1, iDb);
85500 sqlite3NestedParse(pParse,
85501 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
85502 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
85504 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
85505 sqlite3ChangeCookie(pParse, iDb);
85506 destroyRootPage(pParse, pIndex->tnum, iDb);
85507 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
85510 exit_drop_index:
85511 sqlite3SrcListDelete(db, pName);
85515 ** pArray is a pointer to an array of objects. Each object in the
85516 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
85517 ** to extend the array so that there is space for a new object at the end.
85519 ** When this function is called, *pnEntry contains the current size of
85520 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
85521 ** in total).
85523 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
85524 ** space allocated for the new object is zeroed, *pnEntry updated to
85525 ** reflect the new size of the array and a pointer to the new allocation
85526 ** returned. *pIdx is set to the index of the new array entry in this case.
85528 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
85529 ** unchanged and a copy of pArray returned.
85531 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
85532 sqlite3 *db, /* Connection to notify of malloc failures */
85533 void *pArray, /* Array of objects. Might be reallocated */
85534 int szEntry, /* Size of each object in the array */
85535 int *pnEntry, /* Number of objects currently in use */
85536 int *pIdx /* Write the index of a new slot here */
85538 char *z;
85539 int n = *pnEntry;
85540 if( (n & (n-1))==0 ){
85541 int sz = (n==0) ? 1 : 2*n;
85542 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
85543 if( pNew==0 ){
85544 *pIdx = -1;
85545 return pArray;
85547 pArray = pNew;
85549 z = (char*)pArray;
85550 memset(&z[n * szEntry], 0, szEntry);
85551 *pIdx = n;
85552 ++*pnEntry;
85553 return pArray;
85557 ** Append a new element to the given IdList. Create a new IdList if
85558 ** need be.
85560 ** A new IdList is returned, or NULL if malloc() fails.
85562 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
85563 int i;
85564 if( pList==0 ){
85565 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
85566 if( pList==0 ) return 0;
85568 pList->a = sqlite3ArrayAllocate(
85570 pList->a,
85571 sizeof(pList->a[0]),
85572 &pList->nId,
85575 if( i<0 ){
85576 sqlite3IdListDelete(db, pList);
85577 return 0;
85579 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
85580 return pList;
85584 ** Delete an IdList.
85586 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
85587 int i;
85588 if( pList==0 ) return;
85589 for(i=0; i<pList->nId; i++){
85590 sqlite3DbFree(db, pList->a[i].zName);
85592 sqlite3DbFree(db, pList->a);
85593 sqlite3DbFree(db, pList);
85597 ** Return the index in pList of the identifier named zId. Return -1
85598 ** if not found.
85600 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
85601 int i;
85602 if( pList==0 ) return -1;
85603 for(i=0; i<pList->nId; i++){
85604 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
85606 return -1;
85610 ** Expand the space allocated for the given SrcList object by
85611 ** creating nExtra new slots beginning at iStart. iStart is zero based.
85612 ** New slots are zeroed.
85614 ** For example, suppose a SrcList initially contains two entries: A,B.
85615 ** To append 3 new entries onto the end, do this:
85617 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
85619 ** After the call above it would contain: A, B, nil, nil, nil.
85620 ** If the iStart argument had been 1 instead of 2, then the result
85621 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
85622 ** the iStart value would be 0. The result then would
85623 ** be: nil, nil, nil, A, B.
85625 ** If a memory allocation fails the SrcList is unchanged. The
85626 ** db->mallocFailed flag will be set to true.
85628 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
85629 sqlite3 *db, /* Database connection to notify of OOM errors */
85630 SrcList *pSrc, /* The SrcList to be enlarged */
85631 int nExtra, /* Number of new slots to add to pSrc->a[] */
85632 int iStart /* Index in pSrc->a[] of first new slot */
85634 int i;
85636 /* Sanity checking on calling parameters */
85637 assert( iStart>=0 );
85638 assert( nExtra>=1 );
85639 assert( pSrc!=0 );
85640 assert( iStart<=pSrc->nSrc );
85642 /* Allocate additional space if needed */
85643 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
85644 SrcList *pNew;
85645 int nAlloc = pSrc->nSrc+nExtra;
85646 int nGot;
85647 pNew = sqlite3DbRealloc(db, pSrc,
85648 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
85649 if( pNew==0 ){
85650 assert( db->mallocFailed );
85651 return pSrc;
85653 pSrc = pNew;
85654 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
85655 pSrc->nAlloc = (u8)nGot;
85658 /* Move existing slots that come after the newly inserted slots
85659 ** out of the way */
85660 for(i=pSrc->nSrc-1; i>=iStart; i--){
85661 pSrc->a[i+nExtra] = pSrc->a[i];
85663 pSrc->nSrc += (i8)nExtra;
85665 /* Zero the newly allocated slots */
85666 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
85667 for(i=iStart; i<iStart+nExtra; i++){
85668 pSrc->a[i].iCursor = -1;
85671 /* Return a pointer to the enlarged SrcList */
85672 return pSrc;
85677 ** Append a new table name to the given SrcList. Create a new SrcList if
85678 ** need be. A new entry is created in the SrcList even if pTable is NULL.
85680 ** A SrcList is returned, or NULL if there is an OOM error. The returned
85681 ** SrcList might be the same as the SrcList that was input or it might be
85682 ** a new one. If an OOM error does occurs, then the prior value of pList
85683 ** that is input to this routine is automatically freed.
85685 ** If pDatabase is not null, it means that the table has an optional
85686 ** database name prefix. Like this: "database.table". The pDatabase
85687 ** points to the table name and the pTable points to the database name.
85688 ** The SrcList.a[].zName field is filled with the table name which might
85689 ** come from pTable (if pDatabase is NULL) or from pDatabase.
85690 ** SrcList.a[].zDatabase is filled with the database name from pTable,
85691 ** or with NULL if no database is specified.
85693 ** In other words, if call like this:
85695 ** sqlite3SrcListAppend(D,A,B,0);
85697 ** Then B is a table name and the database name is unspecified. If called
85698 ** like this:
85700 ** sqlite3SrcListAppend(D,A,B,C);
85702 ** Then C is the table name and B is the database name. If C is defined
85703 ** then so is B. In other words, we never have a case where:
85705 ** sqlite3SrcListAppend(D,A,0,C);
85707 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
85708 ** before being added to the SrcList.
85710 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
85711 sqlite3 *db, /* Connection to notify of malloc failures */
85712 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
85713 Token *pTable, /* Table to append */
85714 Token *pDatabase /* Database of the table */
85716 struct SrcList_item *pItem;
85717 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
85718 if( pList==0 ){
85719 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
85720 if( pList==0 ) return 0;
85721 pList->nAlloc = 1;
85723 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
85724 if( db->mallocFailed ){
85725 sqlite3SrcListDelete(db, pList);
85726 return 0;
85728 pItem = &pList->a[pList->nSrc-1];
85729 if( pDatabase && pDatabase->z==0 ){
85730 pDatabase = 0;
85732 if( pDatabase ){
85733 Token *pTemp = pDatabase;
85734 pDatabase = pTable;
85735 pTable = pTemp;
85737 pItem->zName = sqlite3NameFromToken(db, pTable);
85738 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
85739 return pList;
85743 ** Assign VdbeCursor index numbers to all tables in a SrcList
85745 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
85746 int i;
85747 struct SrcList_item *pItem;
85748 assert(pList || pParse->db->mallocFailed );
85749 if( pList ){
85750 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
85751 if( pItem->iCursor>=0 ) break;
85752 pItem->iCursor = pParse->nTab++;
85753 if( pItem->pSelect ){
85754 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
85761 ** Delete an entire SrcList including all its substructure.
85763 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
85764 int i;
85765 struct SrcList_item *pItem;
85766 if( pList==0 ) return;
85767 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
85768 sqlite3DbFree(db, pItem->zDatabase);
85769 sqlite3DbFree(db, pItem->zName);
85770 sqlite3DbFree(db, pItem->zAlias);
85771 sqlite3DbFree(db, pItem->zIndex);
85772 sqlite3DeleteTable(db, pItem->pTab);
85773 sqlite3SelectDelete(db, pItem->pSelect);
85774 sqlite3ExprDelete(db, pItem->pOn);
85775 sqlite3IdListDelete(db, pItem->pUsing);
85777 sqlite3DbFree(db, pList);
85781 ** This routine is called by the parser to add a new term to the
85782 ** end of a growing FROM clause. The "p" parameter is the part of
85783 ** the FROM clause that has already been constructed. "p" is NULL
85784 ** if this is the first term of the FROM clause. pTable and pDatabase
85785 ** are the name of the table and database named in the FROM clause term.
85786 ** pDatabase is NULL if the database name qualifier is missing - the
85787 ** usual case. If the term has a alias, then pAlias points to the
85788 ** alias token. If the term is a subquery, then pSubquery is the
85789 ** SELECT statement that the subquery encodes. The pTable and
85790 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
85791 ** parameters are the content of the ON and USING clauses.
85793 ** Return a new SrcList which encodes is the FROM with the new
85794 ** term added.
85796 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
85797 Parse *pParse, /* Parsing context */
85798 SrcList *p, /* The left part of the FROM clause already seen */
85799 Token *pTable, /* Name of the table to add to the FROM clause */
85800 Token *pDatabase, /* Name of the database containing pTable */
85801 Token *pAlias, /* The right-hand side of the AS subexpression */
85802 Select *pSubquery, /* A subquery used in place of a table name */
85803 Expr *pOn, /* The ON clause of a join */
85804 IdList *pUsing /* The USING clause of a join */
85806 struct SrcList_item *pItem;
85807 sqlite3 *db = pParse->db;
85808 if( !p && (pOn || pUsing) ){
85809 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
85810 (pOn ? "ON" : "USING")
85812 goto append_from_error;
85814 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
85815 if( p==0 || NEVER(p->nSrc==0) ){
85816 goto append_from_error;
85818 pItem = &p->a[p->nSrc-1];
85819 assert( pAlias!=0 );
85820 if( pAlias->n ){
85821 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
85823 pItem->pSelect = pSubquery;
85824 pItem->pOn = pOn;
85825 pItem->pUsing = pUsing;
85826 return p;
85828 append_from_error:
85829 assert( p==0 );
85830 sqlite3ExprDelete(db, pOn);
85831 sqlite3IdListDelete(db, pUsing);
85832 sqlite3SelectDelete(db, pSubquery);
85833 return 0;
85837 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
85838 ** element of the source-list passed as the second argument.
85840 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
85841 assert( pIndexedBy!=0 );
85842 if( p && ALWAYS(p->nSrc>0) ){
85843 struct SrcList_item *pItem = &p->a[p->nSrc-1];
85844 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
85845 if( pIndexedBy->n==1 && !pIndexedBy->z ){
85846 /* A "NOT INDEXED" clause was supplied. See parse.y
85847 ** construct "indexed_opt" for details. */
85848 pItem->notIndexed = 1;
85849 }else{
85850 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
85856 ** When building up a FROM clause in the parser, the join operator
85857 ** is initially attached to the left operand. But the code generator
85858 ** expects the join operator to be on the right operand. This routine
85859 ** Shifts all join operators from left to right for an entire FROM
85860 ** clause.
85862 ** Example: Suppose the join is like this:
85864 ** A natural cross join B
85866 ** The operator is "natural cross join". The A and B operands are stored
85867 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
85868 ** operator with A. This routine shifts that operator over to B.
85870 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
85871 if( p ){
85872 int i;
85873 assert( p->a || p->nSrc==0 );
85874 for(i=p->nSrc-1; i>0; i--){
85875 p->a[i].jointype = p->a[i-1].jointype;
85877 p->a[0].jointype = 0;
85882 ** Begin a transaction
85884 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
85885 sqlite3 *db;
85886 Vdbe *v;
85887 int i;
85889 assert( pParse!=0 );
85890 db = pParse->db;
85891 assert( db!=0 );
85892 /* if( db->aDb[0].pBt==0 ) return; */
85893 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
85894 return;
85896 v = sqlite3GetVdbe(pParse);
85897 if( !v ) return;
85898 if( type!=TK_DEFERRED ){
85899 for(i=0; i<db->nDb; i++){
85900 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
85901 sqlite3VdbeUsesBtree(v, i);
85904 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
85908 ** Commit a transaction
85910 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
85911 Vdbe *v;
85913 assert( pParse!=0 );
85914 assert( pParse->db!=0 );
85915 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
85916 return;
85918 v = sqlite3GetVdbe(pParse);
85919 if( v ){
85920 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
85925 ** Rollback a transaction
85927 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
85928 Vdbe *v;
85930 assert( pParse!=0 );
85931 assert( pParse->db!=0 );
85932 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
85933 return;
85935 v = sqlite3GetVdbe(pParse);
85936 if( v ){
85937 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
85942 ** This function is called by the parser when it parses a command to create,
85943 ** release or rollback an SQL savepoint.
85945 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
85946 char *zName = sqlite3NameFromToken(pParse->db, pName);
85947 if( zName ){
85948 Vdbe *v = sqlite3GetVdbe(pParse);
85949 #ifndef SQLITE_OMIT_AUTHORIZATION
85950 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
85951 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
85952 #endif
85953 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
85954 sqlite3DbFree(pParse->db, zName);
85955 return;
85957 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
85962 ** Make sure the TEMP database is open and available for use. Return
85963 ** the number of errors. Leave any error messages in the pParse structure.
85965 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
85966 sqlite3 *db = pParse->db;
85967 if( db->aDb[1].pBt==0 && !pParse->explain ){
85968 int rc;
85969 Btree *pBt;
85970 static const int flags =
85971 SQLITE_OPEN_READWRITE |
85972 SQLITE_OPEN_CREATE |
85973 SQLITE_OPEN_EXCLUSIVE |
85974 SQLITE_OPEN_DELETEONCLOSE |
85975 SQLITE_OPEN_TEMP_DB;
85977 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
85978 if( rc!=SQLITE_OK ){
85979 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
85980 "file for storing temporary tables");
85981 pParse->rc = rc;
85982 return 1;
85984 db->aDb[1].pBt = pBt;
85985 assert( db->aDb[1].pSchema );
85986 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
85987 db->mallocFailed = 1;
85988 return 1;
85991 return 0;
85995 ** Generate VDBE code that will verify the schema cookie and start
85996 ** a read-transaction for all named database files.
85998 ** It is important that all schema cookies be verified and all
85999 ** read transactions be started before anything else happens in
86000 ** the VDBE program. But this routine can be called after much other
86001 ** code has been generated. So here is what we do:
86003 ** The first time this routine is called, we code an OP_Goto that
86004 ** will jump to a subroutine at the end of the program. Then we
86005 ** record every database that needs its schema verified in the
86006 ** pParse->cookieMask field. Later, after all other code has been
86007 ** generated, the subroutine that does the cookie verifications and
86008 ** starts the transactions will be coded and the OP_Goto P2 value
86009 ** will be made to point to that subroutine. The generation of the
86010 ** cookie verification subroutine code happens in sqlite3FinishCoding().
86012 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
86013 ** schema on any databases. This can be used to position the OP_Goto
86014 ** early in the code, before we know if any database tables will be used.
86016 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
86017 Parse *pToplevel = sqlite3ParseToplevel(pParse);
86019 #ifndef SQLITE_OMIT_TRIGGER
86020 if( pToplevel!=pParse ){
86021 /* This branch is taken if a trigger is currently being coded. In this
86022 ** case, set cookieGoto to a non-zero value to show that this function
86023 ** has been called. This is used by the sqlite3ExprCodeConstants()
86024 ** function. */
86025 pParse->cookieGoto = -1;
86027 #endif
86028 if( pToplevel->cookieGoto==0 ){
86029 Vdbe *v = sqlite3GetVdbe(pToplevel);
86030 if( v==0 ) return; /* This only happens if there was a prior error */
86031 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
86033 if( iDb>=0 ){
86034 sqlite3 *db = pToplevel->db;
86035 yDbMask mask;
86037 assert( iDb<db->nDb );
86038 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
86039 assert( iDb<SQLITE_MAX_ATTACHED+2 );
86040 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
86041 mask = ((yDbMask)1)<<iDb;
86042 if( (pToplevel->cookieMask & mask)==0 ){
86043 pToplevel->cookieMask |= mask;
86044 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
86045 if( !OMIT_TEMPDB && iDb==1 ){
86046 sqlite3OpenTempDatabase(pToplevel);
86053 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
86054 ** attached database. Otherwise, invoke it for the database named zDb only.
86056 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
86057 sqlite3 *db = pParse->db;
86058 int i;
86059 for(i=0; i<db->nDb; i++){
86060 Db *pDb = &db->aDb[i];
86061 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
86062 sqlite3CodeVerifySchema(pParse, i);
86068 ** Generate VDBE code that prepares for doing an operation that
86069 ** might change the database.
86071 ** This routine starts a new transaction if we are not already within
86072 ** a transaction. If we are already within a transaction, then a checkpoint
86073 ** is set if the setStatement parameter is true. A checkpoint should
86074 ** be set for operations that might fail (due to a constraint) part of
86075 ** the way through and which will need to undo some writes without having to
86076 ** rollback the whole transaction. For operations where all constraints
86077 ** can be checked before any changes are made to the database, it is never
86078 ** necessary to undo a write and the checkpoint should not be set.
86080 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
86081 Parse *pToplevel = sqlite3ParseToplevel(pParse);
86082 sqlite3CodeVerifySchema(pParse, iDb);
86083 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
86084 pToplevel->isMultiWrite |= setStatement;
86088 ** Indicate that the statement currently under construction might write
86089 ** more than one entry (example: deleting one row then inserting another,
86090 ** inserting multiple rows in a table, or inserting a row and index entries.)
86091 ** If an abort occurs after some of these writes have completed, then it will
86092 ** be necessary to undo the completed writes.
86094 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
86095 Parse *pToplevel = sqlite3ParseToplevel(pParse);
86096 pToplevel->isMultiWrite = 1;
86100 ** The code generator calls this routine if is discovers that it is
86101 ** possible to abort a statement prior to completion. In order to
86102 ** perform this abort without corrupting the database, we need to make
86103 ** sure that the statement is protected by a statement transaction.
86105 ** Technically, we only need to set the mayAbort flag if the
86106 ** isMultiWrite flag was previously set. There is a time dependency
86107 ** such that the abort must occur after the multiwrite. This makes
86108 ** some statements involving the REPLACE conflict resolution algorithm
86109 ** go a little faster. But taking advantage of this time dependency
86110 ** makes it more difficult to prove that the code is correct (in
86111 ** particular, it prevents us from writing an effective
86112 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
86113 ** to take the safe route and skip the optimization.
86115 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
86116 Parse *pToplevel = sqlite3ParseToplevel(pParse);
86117 pToplevel->mayAbort = 1;
86121 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
86122 ** error. The onError parameter determines which (if any) of the statement
86123 ** and/or current transaction is rolled back.
86125 SQLITE_PRIVATE void sqlite3HaltConstraint(
86126 Parse *pParse, /* Parsing context */
86127 int errCode, /* extended error code */
86128 int onError, /* Constraint type */
86129 char *p4, /* Error message */
86130 int p4type /* P4_STATIC or P4_TRANSIENT */
86132 Vdbe *v = sqlite3GetVdbe(pParse);
86133 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
86134 if( onError==OE_Abort ){
86135 sqlite3MayAbort(pParse);
86137 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
86141 ** Check to see if pIndex uses the collating sequence pColl. Return
86142 ** true if it does and false if it does not.
86144 #ifndef SQLITE_OMIT_REINDEX
86145 static int collationMatch(const char *zColl, Index *pIndex){
86146 int i;
86147 assert( zColl!=0 );
86148 for(i=0; i<pIndex->nColumn; i++){
86149 const char *z = pIndex->azColl[i];
86150 assert( z!=0 );
86151 if( 0==sqlite3StrICmp(z, zColl) ){
86152 return 1;
86155 return 0;
86157 #endif
86160 ** Recompute all indices of pTab that use the collating sequence pColl.
86161 ** If pColl==0 then recompute all indices of pTab.
86163 #ifndef SQLITE_OMIT_REINDEX
86164 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
86165 Index *pIndex; /* An index associated with pTab */
86167 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
86168 if( zColl==0 || collationMatch(zColl, pIndex) ){
86169 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
86170 sqlite3BeginWriteOperation(pParse, 0, iDb);
86171 sqlite3RefillIndex(pParse, pIndex, -1);
86175 #endif
86178 ** Recompute all indices of all tables in all databases where the
86179 ** indices use the collating sequence pColl. If pColl==0 then recompute
86180 ** all indices everywhere.
86182 #ifndef SQLITE_OMIT_REINDEX
86183 static void reindexDatabases(Parse *pParse, char const *zColl){
86184 Db *pDb; /* A single database */
86185 int iDb; /* The database index number */
86186 sqlite3 *db = pParse->db; /* The database connection */
86187 HashElem *k; /* For looping over tables in pDb */
86188 Table *pTab; /* A table in the database */
86190 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
86191 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
86192 assert( pDb!=0 );
86193 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
86194 pTab = (Table*)sqliteHashData(k);
86195 reindexTable(pParse, pTab, zColl);
86199 #endif
86202 ** Generate code for the REINDEX command.
86204 ** REINDEX -- 1
86205 ** REINDEX <collation> -- 2
86206 ** REINDEX ?<database>.?<tablename> -- 3
86207 ** REINDEX ?<database>.?<indexname> -- 4
86209 ** Form 1 causes all indices in all attached databases to be rebuilt.
86210 ** Form 2 rebuilds all indices in all databases that use the named
86211 ** collating function. Forms 3 and 4 rebuild the named index or all
86212 ** indices associated with the named table.
86214 #ifndef SQLITE_OMIT_REINDEX
86215 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
86216 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
86217 char *z; /* Name of a table or index */
86218 const char *zDb; /* Name of the database */
86219 Table *pTab; /* A table in the database */
86220 Index *pIndex; /* An index associated with pTab */
86221 int iDb; /* The database index number */
86222 sqlite3 *db = pParse->db; /* The database connection */
86223 Token *pObjName; /* Name of the table or index to be reindexed */
86225 /* Read the database schema. If an error occurs, leave an error message
86226 ** and code in pParse and return NULL. */
86227 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
86228 return;
86231 if( pName1==0 ){
86232 reindexDatabases(pParse, 0);
86233 return;
86234 }else if( NEVER(pName2==0) || pName2->z==0 ){
86235 char *zColl;
86236 assert( pName1->z );
86237 zColl = sqlite3NameFromToken(pParse->db, pName1);
86238 if( !zColl ) return;
86239 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
86240 if( pColl ){
86241 reindexDatabases(pParse, zColl);
86242 sqlite3DbFree(db, zColl);
86243 return;
86245 sqlite3DbFree(db, zColl);
86247 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
86248 if( iDb<0 ) return;
86249 z = sqlite3NameFromToken(db, pObjName);
86250 if( z==0 ) return;
86251 zDb = db->aDb[iDb].zName;
86252 pTab = sqlite3FindTable(db, z, zDb);
86253 if( pTab ){
86254 reindexTable(pParse, pTab, 0);
86255 sqlite3DbFree(db, z);
86256 return;
86258 pIndex = sqlite3FindIndex(db, z, zDb);
86259 sqlite3DbFree(db, z);
86260 if( pIndex ){
86261 sqlite3BeginWriteOperation(pParse, 0, iDb);
86262 sqlite3RefillIndex(pParse, pIndex, -1);
86263 return;
86265 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
86267 #endif
86270 ** Return a dynamicly allocated KeyInfo structure that can be used
86271 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
86273 ** If successful, a pointer to the new structure is returned. In this case
86274 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
86275 ** pointer. If an error occurs (out of memory or missing collation
86276 ** sequence), NULL is returned and the state of pParse updated to reflect
86277 ** the error.
86279 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
86280 int i;
86281 int nCol = pIdx->nColumn;
86282 KeyInfo *pKey;
86284 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol);
86285 if( pKey ){
86286 for(i=0; i<nCol; i++){
86287 char *zColl = pIdx->azColl[i];
86288 assert( zColl );
86289 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
86290 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
86294 if( pParse->nErr ){
86295 sqlite3DbFree(pParse->db, pKey);
86296 pKey = 0;
86298 return pKey;
86301 /************** End of build.c ***********************************************/
86302 /************** Begin file callback.c ****************************************/
86304 ** 2005 May 23
86306 ** The author disclaims copyright to this source code. In place of
86307 ** a legal notice, here is a blessing:
86309 ** May you do good and not evil.
86310 ** May you find forgiveness for yourself and forgive others.
86311 ** May you share freely, never taking more than you give.
86313 *************************************************************************
86315 ** This file contains functions used to access the internal hash tables
86316 ** of user defined functions and collation sequences.
86321 ** Invoke the 'collation needed' callback to request a collation sequence
86322 ** in the encoding enc of name zName, length nName.
86324 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
86325 assert( !db->xCollNeeded || !db->xCollNeeded16 );
86326 if( db->xCollNeeded ){
86327 char *zExternal = sqlite3DbStrDup(db, zName);
86328 if( !zExternal ) return;
86329 db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
86330 sqlite3DbFree(db, zExternal);
86332 #ifndef SQLITE_OMIT_UTF16
86333 if( db->xCollNeeded16 ){
86334 char const *zExternal;
86335 sqlite3_value *pTmp = sqlite3ValueNew(db);
86336 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
86337 zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
86338 if( zExternal ){
86339 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
86341 sqlite3ValueFree(pTmp);
86343 #endif
86347 ** This routine is called if the collation factory fails to deliver a
86348 ** collation function in the best encoding but there may be other versions
86349 ** of this collation function (for other text encodings) available. Use one
86350 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
86351 ** possible.
86353 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
86354 CollSeq *pColl2;
86355 char *z = pColl->zName;
86356 int i;
86357 static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
86358 for(i=0; i<3; i++){
86359 pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
86360 if( pColl2->xCmp!=0 ){
86361 memcpy(pColl, pColl2, sizeof(CollSeq));
86362 pColl->xDel = 0; /* Do not copy the destructor */
86363 return SQLITE_OK;
86366 return SQLITE_ERROR;
86370 ** This function is responsible for invoking the collation factory callback
86371 ** or substituting a collation sequence of a different encoding when the
86372 ** requested collation sequence is not available in the desired encoding.
86374 ** If it is not NULL, then pColl must point to the database native encoding
86375 ** collation sequence with name zName, length nName.
86377 ** The return value is either the collation sequence to be used in database
86378 ** db for collation type name zName, length nName, or NULL, if no collation
86379 ** sequence can be found. If no collation is found, leave an error message.
86381 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
86383 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
86384 Parse *pParse, /* Parsing context */
86385 u8 enc, /* The desired encoding for the collating sequence */
86386 CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
86387 const char *zName /* Collating sequence name */
86389 CollSeq *p;
86390 sqlite3 *db = pParse->db;
86392 p = pColl;
86393 if( !p ){
86394 p = sqlite3FindCollSeq(db, enc, zName, 0);
86396 if( !p || !p->xCmp ){
86397 /* No collation sequence of this type for this encoding is registered.
86398 ** Call the collation factory to see if it can supply us with one.
86400 callCollNeeded(db, enc, zName);
86401 p = sqlite3FindCollSeq(db, enc, zName, 0);
86403 if( p && !p->xCmp && synthCollSeq(db, p) ){
86404 p = 0;
86406 assert( !p || p->xCmp );
86407 if( p==0 ){
86408 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
86410 return p;
86414 ** This routine is called on a collation sequence before it is used to
86415 ** check that it is defined. An undefined collation sequence exists when
86416 ** a database is loaded that contains references to collation sequences
86417 ** that have not been defined by sqlite3_create_collation() etc.
86419 ** If required, this routine calls the 'collation needed' callback to
86420 ** request a definition of the collating sequence. If this doesn't work,
86421 ** an equivalent collating sequence that uses a text encoding different
86422 ** from the main database is substituted, if one is available.
86424 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
86425 if( pColl ){
86426 const char *zName = pColl->zName;
86427 sqlite3 *db = pParse->db;
86428 CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
86429 if( !p ){
86430 return SQLITE_ERROR;
86432 assert( p==pColl );
86434 return SQLITE_OK;
86440 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
86441 ** specified by zName and nName is not found and parameter 'create' is
86442 ** true, then create a new entry. Otherwise return NULL.
86444 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
86445 ** array of three CollSeq structures. The first is the collation sequence
86446 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
86448 ** Stored immediately after the three collation sequences is a copy of
86449 ** the collation sequence name. A pointer to this string is stored in
86450 ** each collation sequence structure.
86452 static CollSeq *findCollSeqEntry(
86453 sqlite3 *db, /* Database connection */
86454 const char *zName, /* Name of the collating sequence */
86455 int create /* Create a new entry if true */
86457 CollSeq *pColl;
86458 int nName = sqlite3Strlen30(zName);
86459 pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
86461 if( 0==pColl && create ){
86462 pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
86463 if( pColl ){
86464 CollSeq *pDel = 0;
86465 pColl[0].zName = (char*)&pColl[3];
86466 pColl[0].enc = SQLITE_UTF8;
86467 pColl[1].zName = (char*)&pColl[3];
86468 pColl[1].enc = SQLITE_UTF16LE;
86469 pColl[2].zName = (char*)&pColl[3];
86470 pColl[2].enc = SQLITE_UTF16BE;
86471 memcpy(pColl[0].zName, zName, nName);
86472 pColl[0].zName[nName] = 0;
86473 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
86475 /* If a malloc() failure occurred in sqlite3HashInsert(), it will
86476 ** return the pColl pointer to be deleted (because it wasn't added
86477 ** to the hash table).
86479 assert( pDel==0 || pDel==pColl );
86480 if( pDel!=0 ){
86481 db->mallocFailed = 1;
86482 sqlite3DbFree(db, pDel);
86483 pColl = 0;
86487 return pColl;
86491 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
86492 ** Return the CollSeq* pointer for the collation sequence named zName
86493 ** for the encoding 'enc' from the database 'db'.
86495 ** If the entry specified is not found and 'create' is true, then create a
86496 ** new entry. Otherwise return NULL.
86498 ** A separate function sqlite3LocateCollSeq() is a wrapper around
86499 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
86500 ** if necessary and generates an error message if the collating sequence
86501 ** cannot be found.
86503 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
86505 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
86506 sqlite3 *db,
86507 u8 enc,
86508 const char *zName,
86509 int create
86511 CollSeq *pColl;
86512 if( zName ){
86513 pColl = findCollSeqEntry(db, zName, create);
86514 }else{
86515 pColl = db->pDfltColl;
86517 assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
86518 assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
86519 if( pColl ) pColl += enc-1;
86520 return pColl;
86523 /* During the search for the best function definition, this procedure
86524 ** is called to test how well the function passed as the first argument
86525 ** matches the request for a function with nArg arguments in a system
86526 ** that uses encoding enc. The value returned indicates how well the
86527 ** request is matched. A higher value indicates a better match.
86529 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
86530 ** is also -1. In other words, we are searching for a function that
86531 ** takes a variable number of arguments.
86533 ** If nArg is -2 that means that we are searching for any function
86534 ** regardless of the number of arguments it uses, so return a positive
86535 ** match score for any
86537 ** The returned value is always between 0 and 6, as follows:
86539 ** 0: Not a match.
86540 ** 1: UTF8/16 conversion required and function takes any number of arguments.
86541 ** 2: UTF16 byte order change required and function takes any number of args.
86542 ** 3: encoding matches and function takes any number of arguments
86543 ** 4: UTF8/16 conversion required - argument count matches exactly
86544 ** 5: UTF16 byte order conversion required - argument count matches exactly
86545 ** 6: Perfect match: encoding and argument count match exactly.
86547 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
86548 ** a perfect match and any function with both xStep and xFunc NULL is
86549 ** a non-match.
86551 #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
86552 static int matchQuality(
86553 FuncDef *p, /* The function we are evaluating for match quality */
86554 int nArg, /* Desired number of arguments. (-1)==any */
86555 u8 enc /* Desired text encoding */
86557 int match;
86559 /* nArg of -2 is a special case */
86560 if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
86562 /* Wrong number of arguments means "no match" */
86563 if( p->nArg!=nArg && p->nArg>=0 ) return 0;
86565 /* Give a better score to a function with a specific number of arguments
86566 ** than to function that accepts any number of arguments. */
86567 if( p->nArg==nArg ){
86568 match = 4;
86569 }else{
86570 match = 1;
86573 /* Bonus points if the text encoding matches */
86574 if( enc==p->iPrefEnc ){
86575 match += 2; /* Exact encoding match */
86576 }else if( (enc & p->iPrefEnc & 2)!=0 ){
86577 match += 1; /* Both are UTF16, but with different byte orders */
86580 return match;
86584 ** Search a FuncDefHash for a function with the given name. Return
86585 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
86587 static FuncDef *functionSearch(
86588 FuncDefHash *pHash, /* Hash table to search */
86589 int h, /* Hash of the name */
86590 const char *zFunc, /* Name of function */
86591 int nFunc /* Number of bytes in zFunc */
86593 FuncDef *p;
86594 for(p=pHash->a[h]; p; p=p->pHash){
86595 if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
86596 return p;
86599 return 0;
86603 ** Insert a new FuncDef into a FuncDefHash hash table.
86605 SQLITE_PRIVATE void sqlite3FuncDefInsert(
86606 FuncDefHash *pHash, /* The hash table into which to insert */
86607 FuncDef *pDef /* The function definition to insert */
86609 FuncDef *pOther;
86610 int nName = sqlite3Strlen30(pDef->zName);
86611 u8 c1 = (u8)pDef->zName[0];
86612 int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
86613 pOther = functionSearch(pHash, h, pDef->zName, nName);
86614 if( pOther ){
86615 assert( pOther!=pDef && pOther->pNext!=pDef );
86616 pDef->pNext = pOther->pNext;
86617 pOther->pNext = pDef;
86618 }else{
86619 pDef->pNext = 0;
86620 pDef->pHash = pHash->a[h];
86621 pHash->a[h] = pDef;
86628 ** Locate a user function given a name, a number of arguments and a flag
86629 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
86630 ** pointer to the FuncDef structure that defines that function, or return
86631 ** NULL if the function does not exist.
86633 ** If the createFlag argument is true, then a new (blank) FuncDef
86634 ** structure is created and liked into the "db" structure if a
86635 ** no matching function previously existed.
86637 ** If nArg is -2, then the first valid function found is returned. A
86638 ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
86639 ** case is used to see if zName is a valid function name for some number
86640 ** of arguments. If nArg is -2, then createFlag must be 0.
86642 ** If createFlag is false, then a function with the required name and
86643 ** number of arguments may be returned even if the eTextRep flag does not
86644 ** match that requested.
86646 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
86647 sqlite3 *db, /* An open database */
86648 const char *zName, /* Name of the function. Not null-terminated */
86649 int nName, /* Number of characters in the name */
86650 int nArg, /* Number of arguments. -1 means any number */
86651 u8 enc, /* Preferred text encoding */
86652 u8 createFlag /* Create new entry if true and does not otherwise exist */
86654 FuncDef *p; /* Iterator variable */
86655 FuncDef *pBest = 0; /* Best match found so far */
86656 int bestScore = 0; /* Score of best match */
86657 int h; /* Hash value */
86659 assert( nArg>=(-2) );
86660 assert( nArg>=(-1) || createFlag==0 );
86661 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
86662 h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
86664 /* First search for a match amongst the application-defined functions.
86666 p = functionSearch(&db->aFunc, h, zName, nName);
86667 while( p ){
86668 int score = matchQuality(p, nArg, enc);
86669 if( score>bestScore ){
86670 pBest = p;
86671 bestScore = score;
86673 p = p->pNext;
86676 /* If no match is found, search the built-in functions.
86678 ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
86679 ** functions even if a prior app-defined function was found. And give
86680 ** priority to built-in functions.
86682 ** Except, if createFlag is true, that means that we are trying to
86683 ** install a new function. Whatever FuncDef structure is returned it will
86684 ** have fields overwritten with new information appropriate for the
86685 ** new function. But the FuncDefs for built-in functions are read-only.
86686 ** So we must not search for built-ins when creating a new function.
86688 if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
86689 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
86690 bestScore = 0;
86691 p = functionSearch(pHash, h, zName, nName);
86692 while( p ){
86693 int score = matchQuality(p, nArg, enc);
86694 if( score>bestScore ){
86695 pBest = p;
86696 bestScore = score;
86698 p = p->pNext;
86702 /* If the createFlag parameter is true and the search did not reveal an
86703 ** exact match for the name, number of arguments and encoding, then add a
86704 ** new entry to the hash table and return it.
86706 if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
86707 (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
86708 pBest->zName = (char *)&pBest[1];
86709 pBest->nArg = (u16)nArg;
86710 pBest->iPrefEnc = enc;
86711 memcpy(pBest->zName, zName, nName);
86712 pBest->zName[nName] = 0;
86713 sqlite3FuncDefInsert(&db->aFunc, pBest);
86716 if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
86717 return pBest;
86719 return 0;
86723 ** Free all resources held by the schema structure. The void* argument points
86724 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
86725 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
86726 ** of the schema hash tables).
86728 ** The Schema.cache_size variable is not cleared.
86730 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
86731 Hash temp1;
86732 Hash temp2;
86733 HashElem *pElem;
86734 Schema *pSchema = (Schema *)p;
86736 temp1 = pSchema->tblHash;
86737 temp2 = pSchema->trigHash;
86738 sqlite3HashInit(&pSchema->trigHash);
86739 sqlite3HashClear(&pSchema->idxHash);
86740 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
86741 sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
86743 sqlite3HashClear(&temp2);
86744 sqlite3HashInit(&pSchema->tblHash);
86745 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
86746 Table *pTab = sqliteHashData(pElem);
86747 sqlite3DeleteTable(0, pTab);
86749 sqlite3HashClear(&temp1);
86750 sqlite3HashClear(&pSchema->fkeyHash);
86751 pSchema->pSeqTab = 0;
86752 if( pSchema->flags & DB_SchemaLoaded ){
86753 pSchema->iGeneration++;
86754 pSchema->flags &= ~DB_SchemaLoaded;
86759 ** Find and return the schema associated with a BTree. Create
86760 ** a new one if necessary.
86762 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
86763 Schema * p;
86764 if( pBt ){
86765 p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
86766 }else{
86767 p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
86769 if( !p ){
86770 db->mallocFailed = 1;
86771 }else if ( 0==p->file_format ){
86772 sqlite3HashInit(&p->tblHash);
86773 sqlite3HashInit(&p->idxHash);
86774 sqlite3HashInit(&p->trigHash);
86775 sqlite3HashInit(&p->fkeyHash);
86776 p->enc = SQLITE_UTF8;
86778 return p;
86781 /************** End of callback.c ********************************************/
86782 /************** Begin file delete.c ******************************************/
86784 ** 2001 September 15
86786 ** The author disclaims copyright to this source code. In place of
86787 ** a legal notice, here is a blessing:
86789 ** May you do good and not evil.
86790 ** May you find forgiveness for yourself and forgive others.
86791 ** May you share freely, never taking more than you give.
86793 *************************************************************************
86794 ** This file contains C code routines that are called by the parser
86795 ** in order to generate code for DELETE FROM statements.
86799 ** While a SrcList can in general represent multiple tables and subqueries
86800 ** (as in the FROM clause of a SELECT statement) in this case it contains
86801 ** the name of a single table, as one might find in an INSERT, DELETE,
86802 ** or UPDATE statement. Look up that table in the symbol table and
86803 ** return a pointer. Set an error message and return NULL if the table
86804 ** name is not found or if any other error occurs.
86806 ** The following fields are initialized appropriate in pSrc:
86808 ** pSrc->a[0].pTab Pointer to the Table object
86809 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
86812 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
86813 struct SrcList_item *pItem = pSrc->a;
86814 Table *pTab;
86815 assert( pItem && pSrc->nSrc==1 );
86816 pTab = sqlite3LocateTableItem(pParse, 0, pItem);
86817 sqlite3DeleteTable(pParse->db, pItem->pTab);
86818 pItem->pTab = pTab;
86819 if( pTab ){
86820 pTab->nRef++;
86822 if( sqlite3IndexedByLookup(pParse, pItem) ){
86823 pTab = 0;
86825 return pTab;
86829 ** Check to make sure the given table is writable. If it is not
86830 ** writable, generate an error message and return 1. If it is
86831 ** writable return 0;
86833 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
86834 /* A table is not writable under the following circumstances:
86836 ** 1) It is a virtual table and no implementation of the xUpdate method
86837 ** has been provided, or
86838 ** 2) It is a system table (i.e. sqlite_master), this call is not
86839 ** part of a nested parse and writable_schema pragma has not
86840 ** been specified.
86842 ** In either case leave an error message in pParse and return non-zero.
86844 if( ( IsVirtual(pTab)
86845 && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
86846 || ( (pTab->tabFlags & TF_Readonly)!=0
86847 && (pParse->db->flags & SQLITE_WriteSchema)==0
86848 && pParse->nested==0 )
86850 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
86851 return 1;
86854 #ifndef SQLITE_OMIT_VIEW
86855 if( !viewOk && pTab->pSelect ){
86856 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
86857 return 1;
86859 #endif
86860 return 0;
86864 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
86866 ** Evaluate a view and store its result in an ephemeral table. The
86867 ** pWhere argument is an optional WHERE clause that restricts the
86868 ** set of rows in the view that are to be added to the ephemeral table.
86870 SQLITE_PRIVATE void sqlite3MaterializeView(
86871 Parse *pParse, /* Parsing context */
86872 Table *pView, /* View definition */
86873 Expr *pWhere, /* Optional WHERE clause to be added */
86874 int iCur /* Cursor number for ephemerial table */
86876 SelectDest dest;
86877 Select *pSel;
86878 SrcList *pFrom;
86879 sqlite3 *db = pParse->db;
86880 int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
86882 pWhere = sqlite3ExprDup(db, pWhere, 0);
86883 pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
86885 if( pFrom ){
86886 assert( pFrom->nSrc==1 );
86887 pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
86888 pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
86889 assert( pFrom->a[0].pOn==0 );
86890 assert( pFrom->a[0].pUsing==0 );
86893 pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
86894 if( pSel ) pSel->selFlags |= SF_Materialize;
86896 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
86897 sqlite3Select(pParse, pSel, &dest);
86898 sqlite3SelectDelete(db, pSel);
86900 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
86902 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
86904 ** Generate an expression tree to implement the WHERE, ORDER BY,
86905 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
86907 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
86908 ** \__________________________/
86909 ** pLimitWhere (pInClause)
86911 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
86912 Parse *pParse, /* The parser context */
86913 SrcList *pSrc, /* the FROM clause -- which tables to scan */
86914 Expr *pWhere, /* The WHERE clause. May be null */
86915 ExprList *pOrderBy, /* The ORDER BY clause. May be null */
86916 Expr *pLimit, /* The LIMIT clause. May be null */
86917 Expr *pOffset, /* The OFFSET clause. May be null */
86918 char *zStmtType /* Either DELETE or UPDATE. For error messages. */
86920 Expr *pWhereRowid = NULL; /* WHERE rowid .. */
86921 Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
86922 Expr *pSelectRowid = NULL; /* SELECT rowid ... */
86923 ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
86924 SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
86925 Select *pSelect = NULL; /* Complete SELECT tree */
86927 /* Check that there isn't an ORDER BY without a LIMIT clause.
86929 if( pOrderBy && (pLimit == 0) ) {
86930 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
86931 goto limit_where_cleanup_2;
86934 /* We only need to generate a select expression if there
86935 ** is a limit/offset term to enforce.
86937 if( pLimit == 0 ) {
86938 /* if pLimit is null, pOffset will always be null as well. */
86939 assert( pOffset == 0 );
86940 return pWhere;
86943 /* Generate a select expression tree to enforce the limit/offset
86944 ** term for the DELETE or UPDATE statement. For example:
86945 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
86946 ** becomes:
86947 ** DELETE FROM table_a WHERE rowid IN (
86948 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
86949 ** );
86952 pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
86953 if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
86954 pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
86955 if( pEList == 0 ) goto limit_where_cleanup_2;
86957 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
86958 ** and the SELECT subtree. */
86959 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
86960 if( pSelectSrc == 0 ) {
86961 sqlite3ExprListDelete(pParse->db, pEList);
86962 goto limit_where_cleanup_2;
86965 /* generate the SELECT expression tree. */
86966 pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
86967 pOrderBy,0,pLimit,pOffset);
86968 if( pSelect == 0 ) return 0;
86970 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
86971 pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
86972 if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
86973 pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
86974 if( pInClause == 0 ) goto limit_where_cleanup_1;
86976 pInClause->x.pSelect = pSelect;
86977 pInClause->flags |= EP_xIsSelect;
86978 sqlite3ExprSetHeight(pParse, pInClause);
86979 return pInClause;
86981 /* something went wrong. clean up anything allocated. */
86982 limit_where_cleanup_1:
86983 sqlite3SelectDelete(pParse->db, pSelect);
86984 return 0;
86986 limit_where_cleanup_2:
86987 sqlite3ExprDelete(pParse->db, pWhere);
86988 sqlite3ExprListDelete(pParse->db, pOrderBy);
86989 sqlite3ExprDelete(pParse->db, pLimit);
86990 sqlite3ExprDelete(pParse->db, pOffset);
86991 return 0;
86993 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
86996 ** Generate code for a DELETE FROM statement.
86998 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
86999 ** \________/ \________________/
87000 ** pTabList pWhere
87002 SQLITE_PRIVATE void sqlite3DeleteFrom(
87003 Parse *pParse, /* The parser context */
87004 SrcList *pTabList, /* The table from which we should delete things */
87005 Expr *pWhere /* The WHERE clause. May be null */
87007 Vdbe *v; /* The virtual database engine */
87008 Table *pTab; /* The table from which records will be deleted */
87009 const char *zDb; /* Name of database holding pTab */
87010 int end, addr = 0; /* A couple addresses of generated code */
87011 int i; /* Loop counter */
87012 WhereInfo *pWInfo; /* Information about the WHERE clause */
87013 Index *pIdx; /* For looping over indices of the table */
87014 int iCur; /* VDBE Cursor number for pTab */
87015 sqlite3 *db; /* Main database structure */
87016 AuthContext sContext; /* Authorization context */
87017 NameContext sNC; /* Name context to resolve expressions in */
87018 int iDb; /* Database number */
87019 int memCnt = -1; /* Memory cell used for change counting */
87020 int rcauth; /* Value returned by authorization callback */
87022 #ifndef SQLITE_OMIT_TRIGGER
87023 int isView; /* True if attempting to delete from a view */
87024 Trigger *pTrigger; /* List of table triggers, if required */
87025 #endif
87027 memset(&sContext, 0, sizeof(sContext));
87028 db = pParse->db;
87029 if( pParse->nErr || db->mallocFailed ){
87030 goto delete_from_cleanup;
87032 assert( pTabList->nSrc==1 );
87034 /* Locate the table which we want to delete. This table has to be
87035 ** put in an SrcList structure because some of the subroutines we
87036 ** will be calling are designed to work with multiple tables and expect
87037 ** an SrcList* parameter instead of just a Table* parameter.
87039 pTab = sqlite3SrcListLookup(pParse, pTabList);
87040 if( pTab==0 ) goto delete_from_cleanup;
87042 /* Figure out if we have any triggers and if the table being
87043 ** deleted from is a view
87045 #ifndef SQLITE_OMIT_TRIGGER
87046 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
87047 isView = pTab->pSelect!=0;
87048 #else
87049 # define pTrigger 0
87050 # define isView 0
87051 #endif
87052 #ifdef SQLITE_OMIT_VIEW
87053 # undef isView
87054 # define isView 0
87055 #endif
87057 /* If pTab is really a view, make sure it has been initialized.
87059 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
87060 goto delete_from_cleanup;
87063 if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
87064 goto delete_from_cleanup;
87066 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
87067 assert( iDb<db->nDb );
87068 zDb = db->aDb[iDb].zName;
87069 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
87070 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
87071 if( rcauth==SQLITE_DENY ){
87072 goto delete_from_cleanup;
87074 assert(!isView || pTrigger);
87076 /* Assign cursor number to the table and all its indices.
87078 assert( pTabList->nSrc==1 );
87079 iCur = pTabList->a[0].iCursor = pParse->nTab++;
87080 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
87081 pParse->nTab++;
87084 /* Start the view context
87086 if( isView ){
87087 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
87090 /* Begin generating code.
87092 v = sqlite3GetVdbe(pParse);
87093 if( v==0 ){
87094 goto delete_from_cleanup;
87096 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
87097 sqlite3BeginWriteOperation(pParse, 1, iDb);
87099 /* If we are trying to delete from a view, realize that view into
87100 ** a ephemeral table.
87102 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
87103 if( isView ){
87104 sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
87106 #endif
87108 /* Resolve the column names in the WHERE clause.
87110 memset(&sNC, 0, sizeof(sNC));
87111 sNC.pParse = pParse;
87112 sNC.pSrcList = pTabList;
87113 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
87114 goto delete_from_cleanup;
87117 /* Initialize the counter of the number of rows deleted, if
87118 ** we are counting rows.
87120 if( db->flags & SQLITE_CountRows ){
87121 memCnt = ++pParse->nMem;
87122 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
87125 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
87126 /* Special case: A DELETE without a WHERE clause deletes everything.
87127 ** It is easier just to erase the whole table. Prior to version 3.6.5,
87128 ** this optimization caused the row change count (the value returned by
87129 ** API function sqlite3_count_changes) to be set incorrectly. */
87130 if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
87131 && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
87133 assert( !isView );
87134 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
87135 pTab->zName, P4_STATIC);
87136 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
87137 assert( pIdx->pSchema==pTab->pSchema );
87138 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
87140 }else
87141 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
87142 /* The usual case: There is a WHERE clause so we have to scan through
87143 ** the table and pick which records to delete.
87146 int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
87147 int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
87148 int regRowid; /* Actual register containing rowids */
87150 /* Collect rowids of every row to be deleted.
87152 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
87153 pWInfo = sqlite3WhereBegin(
87154 pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
87156 if( pWInfo==0 ) goto delete_from_cleanup;
87157 regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
87158 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
87159 if( db->flags & SQLITE_CountRows ){
87160 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
87162 sqlite3WhereEnd(pWInfo);
87164 /* Delete every item whose key was written to the list during the
87165 ** database scan. We have to delete items after the scan is complete
87166 ** because deleting an item can change the scan order. */
87167 end = sqlite3VdbeMakeLabel(v);
87169 /* Unless this is a view, open cursors for the table we are
87170 ** deleting from and all its indices. If this is a view, then the
87171 ** only effect this statement has is to fire the INSTEAD OF
87172 ** triggers. */
87173 if( !isView ){
87174 sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
87177 addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
87179 /* Delete the row */
87180 #ifndef SQLITE_OMIT_VIRTUALTABLE
87181 if( IsVirtual(pTab) ){
87182 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
87183 sqlite3VtabMakeWritable(pParse, pTab);
87184 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
87185 sqlite3VdbeChangeP5(v, OE_Abort);
87186 sqlite3MayAbort(pParse);
87187 }else
87188 #endif
87190 int count = (pParse->nested==0); /* True to count changes */
87191 sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
87194 /* End of the delete loop */
87195 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
87196 sqlite3VdbeResolveLabel(v, end);
87198 /* Close the cursors open on the table and its indexes. */
87199 if( !isView && !IsVirtual(pTab) ){
87200 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
87201 sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
87203 sqlite3VdbeAddOp1(v, OP_Close, iCur);
87207 /* Update the sqlite_sequence table by storing the content of the
87208 ** maximum rowid counter values recorded while inserting into
87209 ** autoincrement tables.
87211 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
87212 sqlite3AutoincrementEnd(pParse);
87215 /* Return the number of rows that were deleted. If this routine is
87216 ** generating code because of a call to sqlite3NestedParse(), do not
87217 ** invoke the callback function.
87219 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
87220 sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
87221 sqlite3VdbeSetNumCols(v, 1);
87222 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
87225 delete_from_cleanup:
87226 sqlite3AuthContextPop(&sContext);
87227 sqlite3SrcListDelete(db, pTabList);
87228 sqlite3ExprDelete(db, pWhere);
87229 return;
87231 /* Make sure "isView" and other macros defined above are undefined. Otherwise
87232 ** thely may interfere with compilation of other functions in this file
87233 ** (or in another file, if this file becomes part of the amalgamation). */
87234 #ifdef isView
87235 #undef isView
87236 #endif
87237 #ifdef pTrigger
87238 #undef pTrigger
87239 #endif
87242 ** This routine generates VDBE code that causes a single row of a
87243 ** single table to be deleted.
87245 ** The VDBE must be in a particular state when this routine is called.
87246 ** These are the requirements:
87248 ** 1. A read/write cursor pointing to pTab, the table containing the row
87249 ** to be deleted, must be opened as cursor number $iCur.
87251 ** 2. Read/write cursors for all indices of pTab must be open as
87252 ** cursor number base+i for the i-th index.
87254 ** 3. The record number of the row to be deleted must be stored in
87255 ** memory cell iRowid.
87257 ** This routine generates code to remove both the table record and all
87258 ** index entries that point to that record.
87260 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
87261 Parse *pParse, /* Parsing context */
87262 Table *pTab, /* Table containing the row to be deleted */
87263 int iCur, /* Cursor number for the table */
87264 int iRowid, /* Memory cell that contains the rowid to delete */
87265 int count, /* If non-zero, increment the row change counter */
87266 Trigger *pTrigger, /* List of triggers to (potentially) fire */
87267 int onconf /* Default ON CONFLICT policy for triggers */
87269 Vdbe *v = pParse->pVdbe; /* Vdbe */
87270 int iOld = 0; /* First register in OLD.* array */
87271 int iLabel; /* Label resolved to end of generated code */
87273 /* Vdbe is guaranteed to have been allocated by this stage. */
87274 assert( v );
87276 /* Seek cursor iCur to the row to delete. If this row no longer exists
87277 ** (this can happen if a trigger program has already deleted it), do
87278 ** not attempt to delete it or fire any DELETE triggers. */
87279 iLabel = sqlite3VdbeMakeLabel(v);
87280 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
87282 /* If there are any triggers to fire, allocate a range of registers to
87283 ** use for the old.* references in the triggers. */
87284 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
87285 u32 mask; /* Mask of OLD.* columns in use */
87286 int iCol; /* Iterator used while populating OLD.* */
87288 /* TODO: Could use temporary registers here. Also could attempt to
87289 ** avoid copying the contents of the rowid register. */
87290 mask = sqlite3TriggerColmask(
87291 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
87293 mask |= sqlite3FkOldmask(pParse, pTab);
87294 iOld = pParse->nMem+1;
87295 pParse->nMem += (1 + pTab->nCol);
87297 /* Populate the OLD.* pseudo-table register array. These values will be
87298 ** used by any BEFORE and AFTER triggers that exist. */
87299 sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
87300 for(iCol=0; iCol<pTab->nCol; iCol++){
87301 if( mask==0xffffffff || mask&(1<<iCol) ){
87302 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
87306 /* Invoke BEFORE DELETE trigger programs. */
87307 sqlite3CodeRowTrigger(pParse, pTrigger,
87308 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
87311 /* Seek the cursor to the row to be deleted again. It may be that
87312 ** the BEFORE triggers coded above have already removed the row
87313 ** being deleted. Do not attempt to delete the row a second time, and
87314 ** do not fire AFTER triggers. */
87315 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
87317 /* Do FK processing. This call checks that any FK constraints that
87318 ** refer to this table (i.e. constraints attached to other tables)
87319 ** are not violated by deleting this row. */
87320 sqlite3FkCheck(pParse, pTab, iOld, 0);
87323 /* Delete the index and table entries. Skip this step if pTab is really
87324 ** a view (in which case the only effect of the DELETE statement is to
87325 ** fire the INSTEAD OF triggers). */
87326 if( pTab->pSelect==0 ){
87327 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
87328 sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
87329 if( count ){
87330 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
87334 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
87335 ** handle rows (possibly in other tables) that refer via a foreign key
87336 ** to the row just deleted. */
87337 sqlite3FkActions(pParse, pTab, 0, iOld);
87339 /* Invoke AFTER DELETE trigger programs. */
87340 sqlite3CodeRowTrigger(pParse, pTrigger,
87341 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
87344 /* Jump here if the row had already been deleted before any BEFORE
87345 ** trigger programs were invoked. Or if a trigger program throws a
87346 ** RAISE(IGNORE) exception. */
87347 sqlite3VdbeResolveLabel(v, iLabel);
87351 ** This routine generates VDBE code that causes the deletion of all
87352 ** index entries associated with a single row of a single table.
87354 ** The VDBE must be in a particular state when this routine is called.
87355 ** These are the requirements:
87357 ** 1. A read/write cursor pointing to pTab, the table containing the row
87358 ** to be deleted, must be opened as cursor number "iCur".
87360 ** 2. Read/write cursors for all indices of pTab must be open as
87361 ** cursor number iCur+i for the i-th index.
87363 ** 3. The "iCur" cursor must be pointing to the row that is to be
87364 ** deleted.
87366 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
87367 Parse *pParse, /* Parsing and code generating context */
87368 Table *pTab, /* Table containing the row to be deleted */
87369 int iCur, /* Cursor number for the table */
87370 int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
87372 int i;
87373 Index *pIdx;
87374 int r1;
87375 int iPartIdxLabel;
87376 Vdbe *v = pParse->pVdbe;
87378 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
87379 if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
87380 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel);
87381 sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1);
87382 sqlite3VdbeResolveLabel(v, iPartIdxLabel);
87387 ** Generate code that will assemble an index key and put it in register
87388 ** regOut. The key with be for index pIdx which is an index on pTab.
87389 ** iCur is the index of a cursor open on the pTab table and pointing to
87390 ** the entry that needs indexing.
87392 ** Return a register number which is the first in a block of
87393 ** registers that holds the elements of the index key. The
87394 ** block of registers has already been deallocated by the time
87395 ** this routine returns.
87397 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
87398 ** to that label if pIdx is a partial index that should be skipped.
87399 ** A partial index should be skipped if its WHERE clause evaluates
87400 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
87401 ** will be set to zero which is an empty label that is ignored by
87402 ** sqlite3VdbeResolveLabel().
87404 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
87405 Parse *pParse, /* Parsing context */
87406 Index *pIdx, /* The index for which to generate a key */
87407 int iCur, /* Cursor number for the pIdx->pTable table */
87408 int regOut, /* Write the new index key to this register */
87409 int doMakeRec, /* Run the OP_MakeRecord instruction if true */
87410 int *piPartIdxLabel /* OUT: Jump to this label to skip partial index */
87412 Vdbe *v = pParse->pVdbe;
87413 int j;
87414 Table *pTab = pIdx->pTable;
87415 int regBase;
87416 int nCol;
87418 if( piPartIdxLabel ){
87419 if( pIdx->pPartIdxWhere ){
87420 *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
87421 pParse->iPartIdxTab = iCur;
87422 sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
87423 SQLITE_JUMPIFNULL);
87424 }else{
87425 *piPartIdxLabel = 0;
87428 nCol = pIdx->nColumn;
87429 regBase = sqlite3GetTempRange(pParse, nCol+1);
87430 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
87431 for(j=0; j<nCol; j++){
87432 int idx = pIdx->aiColumn[j];
87433 if( idx==pTab->iPKey ){
87434 sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
87435 }else{
87436 sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
87437 sqlite3ColumnDefault(v, pTab, idx, -1);
87440 if( doMakeRec ){
87441 const char *zAff;
87442 if( pTab->pSelect
87443 || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
87445 zAff = 0;
87446 }else{
87447 zAff = sqlite3IndexAffinityStr(v, pIdx);
87449 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
87450 sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
87452 sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
87453 return regBase;
87456 /************** End of delete.c **********************************************/
87457 /************** Begin file func.c ********************************************/
87459 ** 2002 February 23
87461 ** The author disclaims copyright to this source code. In place of
87462 ** a legal notice, here is a blessing:
87464 ** May you do good and not evil.
87465 ** May you find forgiveness for yourself and forgive others.
87466 ** May you share freely, never taking more than you give.
87468 *************************************************************************
87469 ** This file contains the C functions that implement various SQL
87470 ** functions of SQLite.
87472 ** There is only one exported symbol in this file - the function
87473 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
87474 ** All other code has file scope.
87476 /* #include <stdlib.h> */
87477 /* #include <assert.h> */
87480 ** Return the collating function associated with a function.
87482 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
87483 return context->pColl;
87487 ** Indicate that the accumulator load should be skipped on this
87488 ** iteration of the aggregate loop.
87490 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
87491 context->skipFlag = 1;
87495 ** Implementation of the non-aggregate min() and max() functions
87497 static void minmaxFunc(
87498 sqlite3_context *context,
87499 int argc,
87500 sqlite3_value **argv
87502 int i;
87503 int mask; /* 0 for min() or 0xffffffff for max() */
87504 int iBest;
87505 CollSeq *pColl;
87507 assert( argc>1 );
87508 mask = sqlite3_user_data(context)==0 ? 0 : -1;
87509 pColl = sqlite3GetFuncCollSeq(context);
87510 assert( pColl );
87511 assert( mask==-1 || mask==0 );
87512 iBest = 0;
87513 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87514 for(i=1; i<argc; i++){
87515 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
87516 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
87517 testcase( mask==0 );
87518 iBest = i;
87521 sqlite3_result_value(context, argv[iBest]);
87525 ** Return the type of the argument.
87527 static void typeofFunc(
87528 sqlite3_context *context,
87529 int NotUsed,
87530 sqlite3_value **argv
87532 const char *z = 0;
87533 UNUSED_PARAMETER(NotUsed);
87534 switch( sqlite3_value_type(argv[0]) ){
87535 case SQLITE_INTEGER: z = "integer"; break;
87536 case SQLITE_TEXT: z = "text"; break;
87537 case SQLITE_FLOAT: z = "real"; break;
87538 case SQLITE_BLOB: z = "blob"; break;
87539 default: z = "null"; break;
87541 sqlite3_result_text(context, z, -1, SQLITE_STATIC);
87546 ** Implementation of the length() function
87548 static void lengthFunc(
87549 sqlite3_context *context,
87550 int argc,
87551 sqlite3_value **argv
87553 int len;
87555 assert( argc==1 );
87556 UNUSED_PARAMETER(argc);
87557 switch( sqlite3_value_type(argv[0]) ){
87558 case SQLITE_BLOB:
87559 case SQLITE_INTEGER:
87560 case SQLITE_FLOAT: {
87561 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
87562 break;
87564 case SQLITE_TEXT: {
87565 const unsigned char *z = sqlite3_value_text(argv[0]);
87566 if( z==0 ) return;
87567 len = 0;
87568 while( *z ){
87569 len++;
87570 SQLITE_SKIP_UTF8(z);
87572 sqlite3_result_int(context, len);
87573 break;
87575 default: {
87576 sqlite3_result_null(context);
87577 break;
87583 ** Implementation of the abs() function.
87585 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
87586 ** the numeric argument X.
87588 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87589 assert( argc==1 );
87590 UNUSED_PARAMETER(argc);
87591 switch( sqlite3_value_type(argv[0]) ){
87592 case SQLITE_INTEGER: {
87593 i64 iVal = sqlite3_value_int64(argv[0]);
87594 if( iVal<0 ){
87595 if( (iVal<<1)==0 ){
87596 /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
87597 ** abs(X) throws an integer overflow error since there is no
87598 ** equivalent positive 64-bit two complement value. */
87599 sqlite3_result_error(context, "integer overflow", -1);
87600 return;
87602 iVal = -iVal;
87604 sqlite3_result_int64(context, iVal);
87605 break;
87607 case SQLITE_NULL: {
87608 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
87609 sqlite3_result_null(context);
87610 break;
87612 default: {
87613 /* Because sqlite3_value_double() returns 0.0 if the argument is not
87614 ** something that can be converted into a number, we have:
87615 ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
87616 ** cannot be converted to a numeric value.
87618 double rVal = sqlite3_value_double(argv[0]);
87619 if( rVal<0 ) rVal = -rVal;
87620 sqlite3_result_double(context, rVal);
87621 break;
87627 ** Implementation of the instr() function.
87629 ** instr(haystack,needle) finds the first occurrence of needle
87630 ** in haystack and returns the number of previous characters plus 1,
87631 ** or 0 if needle does not occur within haystack.
87633 ** If both haystack and needle are BLOBs, then the result is one more than
87634 ** the number of bytes in haystack prior to the first occurrence of needle,
87635 ** or 0 if needle never occurs in haystack.
87637 static void instrFunc(
87638 sqlite3_context *context,
87639 int argc,
87640 sqlite3_value **argv
87642 const unsigned char *zHaystack;
87643 const unsigned char *zNeedle;
87644 int nHaystack;
87645 int nNeedle;
87646 int typeHaystack, typeNeedle;
87647 int N = 1;
87648 int isText;
87650 UNUSED_PARAMETER(argc);
87651 typeHaystack = sqlite3_value_type(argv[0]);
87652 typeNeedle = sqlite3_value_type(argv[1]);
87653 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
87654 nHaystack = sqlite3_value_bytes(argv[0]);
87655 nNeedle = sqlite3_value_bytes(argv[1]);
87656 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
87657 zHaystack = sqlite3_value_blob(argv[0]);
87658 zNeedle = sqlite3_value_blob(argv[1]);
87659 isText = 0;
87660 }else{
87661 zHaystack = sqlite3_value_text(argv[0]);
87662 zNeedle = sqlite3_value_text(argv[1]);
87663 isText = 1;
87665 while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
87666 N++;
87668 nHaystack--;
87669 zHaystack++;
87670 }while( isText && (zHaystack[0]&0xc0)==0x80 );
87672 if( nNeedle>nHaystack ) N = 0;
87673 sqlite3_result_int(context, N);
87677 ** Implementation of the substr() function.
87679 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
87680 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
87681 ** of x. If x is text, then we actually count UTF-8 characters.
87682 ** If x is a blob, then we count bytes.
87684 ** If p1 is negative, then we begin abs(p1) from the end of x[].
87686 ** If p2 is negative, return the p2 characters preceding p1.
87688 static void substrFunc(
87689 sqlite3_context *context,
87690 int argc,
87691 sqlite3_value **argv
87693 const unsigned char *z;
87694 const unsigned char *z2;
87695 int len;
87696 int p0type;
87697 i64 p1, p2;
87698 int negP2 = 0;
87700 assert( argc==3 || argc==2 );
87701 if( sqlite3_value_type(argv[1])==SQLITE_NULL
87702 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
87704 return;
87706 p0type = sqlite3_value_type(argv[0]);
87707 p1 = sqlite3_value_int(argv[1]);
87708 if( p0type==SQLITE_BLOB ){
87709 len = sqlite3_value_bytes(argv[0]);
87710 z = sqlite3_value_blob(argv[0]);
87711 if( z==0 ) return;
87712 assert( len==sqlite3_value_bytes(argv[0]) );
87713 }else{
87714 z = sqlite3_value_text(argv[0]);
87715 if( z==0 ) return;
87716 len = 0;
87717 if( p1<0 ){
87718 for(z2=z; *z2; len++){
87719 SQLITE_SKIP_UTF8(z2);
87723 if( argc==3 ){
87724 p2 = sqlite3_value_int(argv[2]);
87725 if( p2<0 ){
87726 p2 = -p2;
87727 negP2 = 1;
87729 }else{
87730 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
87732 if( p1<0 ){
87733 p1 += len;
87734 if( p1<0 ){
87735 p2 += p1;
87736 if( p2<0 ) p2 = 0;
87737 p1 = 0;
87739 }else if( p1>0 ){
87740 p1--;
87741 }else if( p2>0 ){
87742 p2--;
87744 if( negP2 ){
87745 p1 -= p2;
87746 if( p1<0 ){
87747 p2 += p1;
87748 p1 = 0;
87751 assert( p1>=0 && p2>=0 );
87752 if( p0type!=SQLITE_BLOB ){
87753 while( *z && p1 ){
87754 SQLITE_SKIP_UTF8(z);
87755 p1--;
87757 for(z2=z; *z2 && p2; p2--){
87758 SQLITE_SKIP_UTF8(z2);
87760 sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
87761 }else{
87762 if( p1+p2>len ){
87763 p2 = len-p1;
87764 if( p2<0 ) p2 = 0;
87766 sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
87771 ** Implementation of the round() function
87773 #ifndef SQLITE_OMIT_FLOATING_POINT
87774 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87775 int n = 0;
87776 double r;
87777 char *zBuf;
87778 assert( argc==1 || argc==2 );
87779 if( argc==2 ){
87780 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
87781 n = sqlite3_value_int(argv[1]);
87782 if( n>30 ) n = 30;
87783 if( n<0 ) n = 0;
87785 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87786 r = sqlite3_value_double(argv[0]);
87787 /* If Y==0 and X will fit in a 64-bit int,
87788 ** handle the rounding directly,
87789 ** otherwise use printf.
87791 if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
87792 r = (double)((sqlite_int64)(r+0.5));
87793 }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
87794 r = -(double)((sqlite_int64)((-r)+0.5));
87795 }else{
87796 zBuf = sqlite3_mprintf("%.*f",n,r);
87797 if( zBuf==0 ){
87798 sqlite3_result_error_nomem(context);
87799 return;
87801 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
87802 sqlite3_free(zBuf);
87804 sqlite3_result_double(context, r);
87806 #endif
87809 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
87810 ** allocation fails, call sqlite3_result_error_nomem() to notify
87811 ** the database handle that malloc() has failed and return NULL.
87812 ** If nByte is larger than the maximum string or blob length, then
87813 ** raise an SQLITE_TOOBIG exception and return NULL.
87815 static void *contextMalloc(sqlite3_context *context, i64 nByte){
87816 char *z;
87817 sqlite3 *db = sqlite3_context_db_handle(context);
87818 assert( nByte>0 );
87819 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
87820 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
87821 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87822 sqlite3_result_error_toobig(context);
87823 z = 0;
87824 }else{
87825 z = sqlite3Malloc((int)nByte);
87826 if( !z ){
87827 sqlite3_result_error_nomem(context);
87830 return z;
87834 ** Implementation of the upper() and lower() SQL functions.
87836 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87837 char *z1;
87838 const char *z2;
87839 int i, n;
87840 UNUSED_PARAMETER(argc);
87841 z2 = (char*)sqlite3_value_text(argv[0]);
87842 n = sqlite3_value_bytes(argv[0]);
87843 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
87844 assert( z2==(char*)sqlite3_value_text(argv[0]) );
87845 if( z2 ){
87846 z1 = contextMalloc(context, ((i64)n)+1);
87847 if( z1 ){
87848 for(i=0; i<n; i++){
87849 z1[i] = (char)sqlite3Toupper(z2[i]);
87851 sqlite3_result_text(context, z1, n, sqlite3_free);
87855 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87856 char *z1;
87857 const char *z2;
87858 int i, n;
87859 UNUSED_PARAMETER(argc);
87860 z2 = (char*)sqlite3_value_text(argv[0]);
87861 n = sqlite3_value_bytes(argv[0]);
87862 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
87863 assert( z2==(char*)sqlite3_value_text(argv[0]) );
87864 if( z2 ){
87865 z1 = contextMalloc(context, ((i64)n)+1);
87866 if( z1 ){
87867 for(i=0; i<n; i++){
87868 z1[i] = sqlite3Tolower(z2[i]);
87870 sqlite3_result_text(context, z1, n, sqlite3_free);
87876 ** The COALESCE() and IFNULL() functions are implemented as VDBE code so
87877 ** that unused argument values do not have to be computed. However, we
87878 ** still need some kind of function implementation for this routines in
87879 ** the function table. That function implementation will never be called
87880 ** so it doesn't matter what the implementation is. We might as well use
87881 ** the "version()" function as a substitute.
87883 #define ifnullFunc versionFunc /* Substitute function - never called */
87886 ** Implementation of random(). Return a random integer.
87888 static void randomFunc(
87889 sqlite3_context *context,
87890 int NotUsed,
87891 sqlite3_value **NotUsed2
87893 sqlite_int64 r;
87894 UNUSED_PARAMETER2(NotUsed, NotUsed2);
87895 sqlite3_randomness(sizeof(r), &r);
87896 if( r<0 ){
87897 /* We need to prevent a random number of 0x8000000000000000
87898 ** (or -9223372036854775808) since when you do abs() of that
87899 ** number of you get the same value back again. To do this
87900 ** in a way that is testable, mask the sign bit off of negative
87901 ** values, resulting in a positive value. Then take the
87902 ** 2s complement of that positive value. The end result can
87903 ** therefore be no less than -9223372036854775807.
87905 r = -(r & LARGEST_INT64);
87907 sqlite3_result_int64(context, r);
87911 ** Implementation of randomblob(N). Return a random blob
87912 ** that is N bytes long.
87914 static void randomBlob(
87915 sqlite3_context *context,
87916 int argc,
87917 sqlite3_value **argv
87919 int n;
87920 unsigned char *p;
87921 assert( argc==1 );
87922 UNUSED_PARAMETER(argc);
87923 n = sqlite3_value_int(argv[0]);
87924 if( n<1 ){
87925 n = 1;
87927 p = contextMalloc(context, n);
87928 if( p ){
87929 sqlite3_randomness(n, p);
87930 sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
87935 ** Implementation of the last_insert_rowid() SQL function. The return
87936 ** value is the same as the sqlite3_last_insert_rowid() API function.
87938 static void last_insert_rowid(
87939 sqlite3_context *context,
87940 int NotUsed,
87941 sqlite3_value **NotUsed2
87943 sqlite3 *db = sqlite3_context_db_handle(context);
87944 UNUSED_PARAMETER2(NotUsed, NotUsed2);
87945 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
87946 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
87947 ** function. */
87948 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
87952 ** Implementation of the changes() SQL function.
87954 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
87955 ** around the sqlite3_changes() C/C++ function and hence follows the same
87956 ** rules for counting changes.
87958 static void changes(
87959 sqlite3_context *context,
87960 int NotUsed,
87961 sqlite3_value **NotUsed2
87963 sqlite3 *db = sqlite3_context_db_handle(context);
87964 UNUSED_PARAMETER2(NotUsed, NotUsed2);
87965 sqlite3_result_int(context, sqlite3_changes(db));
87969 ** Implementation of the total_changes() SQL function. The return value is
87970 ** the same as the sqlite3_total_changes() API function.
87972 static void total_changes(
87973 sqlite3_context *context,
87974 int NotUsed,
87975 sqlite3_value **NotUsed2
87977 sqlite3 *db = sqlite3_context_db_handle(context);
87978 UNUSED_PARAMETER2(NotUsed, NotUsed2);
87979 /* IMP: R-52756-41993 This function is a wrapper around the
87980 ** sqlite3_total_changes() C/C++ interface. */
87981 sqlite3_result_int(context, sqlite3_total_changes(db));
87985 ** A structure defining how to do GLOB-style comparisons.
87987 struct compareInfo {
87988 u8 matchAll;
87989 u8 matchOne;
87990 u8 matchSet;
87991 u8 noCase;
87995 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
87996 ** character is exactly one byte in size. Also, all characters are
87997 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
87998 ** whereas only characters less than 0x80 do in ASCII.
88000 #if defined(SQLITE_EBCDIC)
88001 # define sqlite3Utf8Read(A) (*((*A)++))
88002 # define GlogUpperToLower(A) A = sqlite3UpperToLower[A]
88003 #else
88004 # define GlogUpperToLower(A) if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
88005 #endif
88007 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
88008 /* The correct SQL-92 behavior is for the LIKE operator to ignore
88009 ** case. Thus 'a' LIKE 'A' would be true. */
88010 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
88011 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
88012 ** is case sensitive causing 'a' LIKE 'A' to be false */
88013 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
88016 ** Compare two UTF-8 strings for equality where the first string can
88017 ** potentially be a "glob" expression. Return true (1) if they
88018 ** are the same and false (0) if they are different.
88020 ** Globbing rules:
88022 ** '*' Matches any sequence of zero or more characters.
88024 ** '?' Matches exactly one character.
88026 ** [...] Matches one character from the enclosed list of
88027 ** characters.
88029 ** [^...] Matches one character not in the enclosed list.
88031 ** With the [...] and [^...] matching, a ']' character can be included
88032 ** in the list by making it the first character after '[' or '^'. A
88033 ** range of characters can be specified using '-'. Example:
88034 ** "[a-z]" matches any single lower-case letter. To match a '-', make
88035 ** it the last character in the list.
88037 ** This routine is usually quick, but can be N**2 in the worst case.
88039 ** Hints: to match '*' or '?', put them in "[]". Like this:
88041 ** abc[*]xyz Matches "abc*xyz" only
88043 static int patternCompare(
88044 const u8 *zPattern, /* The glob pattern */
88045 const u8 *zString, /* The string to compare against the glob */
88046 const struct compareInfo *pInfo, /* Information about how to do the compare */
88047 u32 esc /* The escape character */
88049 u32 c, c2;
88050 int invert;
88051 int seen;
88052 u8 matchOne = pInfo->matchOne;
88053 u8 matchAll = pInfo->matchAll;
88054 u8 matchSet = pInfo->matchSet;
88055 u8 noCase = pInfo->noCase;
88056 int prevEscape = 0; /* True if the previous character was 'escape' */
88058 while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
88059 if( c==matchAll && !prevEscape ){
88060 while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
88061 || c == matchOne ){
88062 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
88063 return 0;
88066 if( c==0 ){
88067 return 1;
88068 }else if( c==esc ){
88069 c = sqlite3Utf8Read(&zPattern);
88070 if( c==0 ){
88071 return 0;
88073 }else if( c==matchSet ){
88074 assert( esc==0 ); /* This is GLOB, not LIKE */
88075 assert( matchSet<0x80 ); /* '[' is a single-byte character */
88076 while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
88077 SQLITE_SKIP_UTF8(zString);
88079 return *zString!=0;
88081 while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
88082 if( noCase ){
88083 GlogUpperToLower(c2);
88084 GlogUpperToLower(c);
88085 while( c2 != 0 && c2 != c ){
88086 c2 = sqlite3Utf8Read(&zString);
88087 GlogUpperToLower(c2);
88089 }else{
88090 while( c2 != 0 && c2 != c ){
88091 c2 = sqlite3Utf8Read(&zString);
88094 if( c2==0 ) return 0;
88095 if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
88097 return 0;
88098 }else if( c==matchOne && !prevEscape ){
88099 if( sqlite3Utf8Read(&zString)==0 ){
88100 return 0;
88102 }else if( c==matchSet ){
88103 u32 prior_c = 0;
88104 assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
88105 seen = 0;
88106 invert = 0;
88107 c = sqlite3Utf8Read(&zString);
88108 if( c==0 ) return 0;
88109 c2 = sqlite3Utf8Read(&zPattern);
88110 if( c2=='^' ){
88111 invert = 1;
88112 c2 = sqlite3Utf8Read(&zPattern);
88114 if( c2==']' ){
88115 if( c==']' ) seen = 1;
88116 c2 = sqlite3Utf8Read(&zPattern);
88118 while( c2 && c2!=']' ){
88119 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
88120 c2 = sqlite3Utf8Read(&zPattern);
88121 if( c>=prior_c && c<=c2 ) seen = 1;
88122 prior_c = 0;
88123 }else{
88124 if( c==c2 ){
88125 seen = 1;
88127 prior_c = c2;
88129 c2 = sqlite3Utf8Read(&zPattern);
88131 if( c2==0 || (seen ^ invert)==0 ){
88132 return 0;
88134 }else if( esc==c && !prevEscape ){
88135 prevEscape = 1;
88136 }else{
88137 c2 = sqlite3Utf8Read(&zString);
88138 if( noCase ){
88139 GlogUpperToLower(c);
88140 GlogUpperToLower(c2);
88142 if( c!=c2 ){
88143 return 0;
88145 prevEscape = 0;
88148 return *zString==0;
88152 ** The sqlite3_strglob() interface.
88154 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
88155 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
88159 ** Count the number of times that the LIKE operator (or GLOB which is
88160 ** just a variation of LIKE) gets called. This is used for testing
88161 ** only.
88163 #ifdef SQLITE_TEST
88164 SQLITE_API int sqlite3_like_count = 0;
88165 #endif
88169 ** Implementation of the like() SQL function. This function implements
88170 ** the build-in LIKE operator. The first argument to the function is the
88171 ** pattern and the second argument is the string. So, the SQL statements:
88173 ** A LIKE B
88175 ** is implemented as like(B,A).
88177 ** This same function (with a different compareInfo structure) computes
88178 ** the GLOB operator.
88180 static void likeFunc(
88181 sqlite3_context *context,
88182 int argc,
88183 sqlite3_value **argv
88185 const unsigned char *zA, *zB;
88186 u32 escape = 0;
88187 int nPat;
88188 sqlite3 *db = sqlite3_context_db_handle(context);
88190 zB = sqlite3_value_text(argv[0]);
88191 zA = sqlite3_value_text(argv[1]);
88193 /* Limit the length of the LIKE or GLOB pattern to avoid problems
88194 ** of deep recursion and N*N behavior in patternCompare().
88196 nPat = sqlite3_value_bytes(argv[0]);
88197 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
88198 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
88199 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
88200 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
88201 return;
88203 assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
88205 if( argc==3 ){
88206 /* The escape character string must consist of a single UTF-8 character.
88207 ** Otherwise, return an error.
88209 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
88210 if( zEsc==0 ) return;
88211 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
88212 sqlite3_result_error(context,
88213 "ESCAPE expression must be a single character", -1);
88214 return;
88216 escape = sqlite3Utf8Read(&zEsc);
88218 if( zA && zB ){
88219 struct compareInfo *pInfo = sqlite3_user_data(context);
88220 #ifdef SQLITE_TEST
88221 sqlite3_like_count++;
88222 #endif
88224 sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
88229 ** Implementation of the NULLIF(x,y) function. The result is the first
88230 ** argument if the arguments are different. The result is NULL if the
88231 ** arguments are equal to each other.
88233 static void nullifFunc(
88234 sqlite3_context *context,
88235 int NotUsed,
88236 sqlite3_value **argv
88238 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
88239 UNUSED_PARAMETER(NotUsed);
88240 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
88241 sqlite3_result_value(context, argv[0]);
88246 ** Implementation of the sqlite_version() function. The result is the version
88247 ** of the SQLite library that is running.
88249 static void versionFunc(
88250 sqlite3_context *context,
88251 int NotUsed,
88252 sqlite3_value **NotUsed2
88254 UNUSED_PARAMETER2(NotUsed, NotUsed2);
88255 /* IMP: R-48699-48617 This function is an SQL wrapper around the
88256 ** sqlite3_libversion() C-interface. */
88257 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
88261 ** Implementation of the sqlite_source_id() function. The result is a string
88262 ** that identifies the particular version of the source code used to build
88263 ** SQLite.
88265 static void sourceidFunc(
88266 sqlite3_context *context,
88267 int NotUsed,
88268 sqlite3_value **NotUsed2
88270 UNUSED_PARAMETER2(NotUsed, NotUsed2);
88271 /* IMP: R-24470-31136 This function is an SQL wrapper around the
88272 ** sqlite3_sourceid() C interface. */
88273 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
88277 ** Implementation of the sqlite_log() function. This is a wrapper around
88278 ** sqlite3_log(). The return value is NULL. The function exists purely for
88279 ** its side-effects.
88281 static void errlogFunc(
88282 sqlite3_context *context,
88283 int argc,
88284 sqlite3_value **argv
88286 UNUSED_PARAMETER(argc);
88287 UNUSED_PARAMETER(context);
88288 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
88292 ** Implementation of the sqlite_compileoption_used() function.
88293 ** The result is an integer that identifies if the compiler option
88294 ** was used to build SQLite.
88296 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88297 static void compileoptionusedFunc(
88298 sqlite3_context *context,
88299 int argc,
88300 sqlite3_value **argv
88302 const char *zOptName;
88303 assert( argc==1 );
88304 UNUSED_PARAMETER(argc);
88305 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
88306 ** function is a wrapper around the sqlite3_compileoption_used() C/C++
88307 ** function.
88309 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
88310 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
88313 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88316 ** Implementation of the sqlite_compileoption_get() function.
88317 ** The result is a string that identifies the compiler options
88318 ** used to build SQLite.
88320 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88321 static void compileoptiongetFunc(
88322 sqlite3_context *context,
88323 int argc,
88324 sqlite3_value **argv
88326 int n;
88327 assert( argc==1 );
88328 UNUSED_PARAMETER(argc);
88329 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
88330 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
88332 n = sqlite3_value_int(argv[0]);
88333 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
88335 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88337 /* Array for converting from half-bytes (nybbles) into ASCII hex
88338 ** digits. */
88339 static const char hexdigits[] = {
88340 '0', '1', '2', '3', '4', '5', '6', '7',
88341 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
88345 ** Implementation of the QUOTE() function. This function takes a single
88346 ** argument. If the argument is numeric, the return value is the same as
88347 ** the argument. If the argument is NULL, the return value is the string
88348 ** "NULL". Otherwise, the argument is enclosed in single quotes with
88349 ** single-quote escapes.
88351 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
88352 assert( argc==1 );
88353 UNUSED_PARAMETER(argc);
88354 switch( sqlite3_value_type(argv[0]) ){
88355 case SQLITE_FLOAT: {
88356 double r1, r2;
88357 char zBuf[50];
88358 r1 = sqlite3_value_double(argv[0]);
88359 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
88360 sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
88361 if( r1!=r2 ){
88362 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
88364 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
88365 break;
88367 case SQLITE_INTEGER: {
88368 sqlite3_result_value(context, argv[0]);
88369 break;
88371 case SQLITE_BLOB: {
88372 char *zText = 0;
88373 char const *zBlob = sqlite3_value_blob(argv[0]);
88374 int nBlob = sqlite3_value_bytes(argv[0]);
88375 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
88376 zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
88377 if( zText ){
88378 int i;
88379 for(i=0; i<nBlob; i++){
88380 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
88381 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
88383 zText[(nBlob*2)+2] = '\'';
88384 zText[(nBlob*2)+3] = '\0';
88385 zText[0] = 'X';
88386 zText[1] = '\'';
88387 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
88388 sqlite3_free(zText);
88390 break;
88392 case SQLITE_TEXT: {
88393 int i,j;
88394 u64 n;
88395 const unsigned char *zArg = sqlite3_value_text(argv[0]);
88396 char *z;
88398 if( zArg==0 ) return;
88399 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
88400 z = contextMalloc(context, ((i64)i)+((i64)n)+3);
88401 if( z ){
88402 z[0] = '\'';
88403 for(i=0, j=1; zArg[i]; i++){
88404 z[j++] = zArg[i];
88405 if( zArg[i]=='\'' ){
88406 z[j++] = '\'';
88409 z[j++] = '\'';
88410 z[j] = 0;
88411 sqlite3_result_text(context, z, j, sqlite3_free);
88413 break;
88415 default: {
88416 assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
88417 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
88418 break;
88424 ** The unicode() function. Return the integer unicode code-point value
88425 ** for the first character of the input string.
88427 static void unicodeFunc(
88428 sqlite3_context *context,
88429 int argc,
88430 sqlite3_value **argv
88432 const unsigned char *z = sqlite3_value_text(argv[0]);
88433 (void)argc;
88434 if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
88438 ** The char() function takes zero or more arguments, each of which is
88439 ** an integer. It constructs a string where each character of the string
88440 ** is the unicode character for the corresponding integer argument.
88442 static void charFunc(
88443 sqlite3_context *context,
88444 int argc,
88445 sqlite3_value **argv
88447 unsigned char *z, *zOut;
88448 int i;
88449 zOut = z = sqlite3_malloc( argc*4 );
88450 if( z==0 ){
88451 sqlite3_result_error_nomem(context);
88452 return;
88454 for(i=0; i<argc; i++){
88455 sqlite3_int64 x;
88456 unsigned c;
88457 x = sqlite3_value_int64(argv[i]);
88458 if( x<0 || x>0x10ffff ) x = 0xfffd;
88459 c = (unsigned)(x & 0x1fffff);
88460 if( c<0x00080 ){
88461 *zOut++ = (u8)(c&0xFF);
88462 }else if( c<0x00800 ){
88463 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
88464 *zOut++ = 0x80 + (u8)(c & 0x3F);
88465 }else if( c<0x10000 ){
88466 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
88467 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
88468 *zOut++ = 0x80 + (u8)(c & 0x3F);
88469 }else{
88470 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
88471 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
88472 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
88473 *zOut++ = 0x80 + (u8)(c & 0x3F);
88476 sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
88480 ** The hex() function. Interpret the argument as a blob. Return
88481 ** a hexadecimal rendering as text.
88483 static void hexFunc(
88484 sqlite3_context *context,
88485 int argc,
88486 sqlite3_value **argv
88488 int i, n;
88489 const unsigned char *pBlob;
88490 char *zHex, *z;
88491 assert( argc==1 );
88492 UNUSED_PARAMETER(argc);
88493 pBlob = sqlite3_value_blob(argv[0]);
88494 n = sqlite3_value_bytes(argv[0]);
88495 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
88496 z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
88497 if( zHex ){
88498 for(i=0; i<n; i++, pBlob++){
88499 unsigned char c = *pBlob;
88500 *(z++) = hexdigits[(c>>4)&0xf];
88501 *(z++) = hexdigits[c&0xf];
88503 *z = 0;
88504 sqlite3_result_text(context, zHex, n*2, sqlite3_free);
88509 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
88511 static void zeroblobFunc(
88512 sqlite3_context *context,
88513 int argc,
88514 sqlite3_value **argv
88516 i64 n;
88517 sqlite3 *db = sqlite3_context_db_handle(context);
88518 assert( argc==1 );
88519 UNUSED_PARAMETER(argc);
88520 n = sqlite3_value_int64(argv[0]);
88521 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
88522 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
88523 if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
88524 sqlite3_result_error_toobig(context);
88525 }else{
88526 sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
88531 ** The replace() function. Three arguments are all strings: call
88532 ** them A, B, and C. The result is also a string which is derived
88533 ** from A by replacing every occurrence of B with C. The match
88534 ** must be exact. Collating sequences are not used.
88536 static void replaceFunc(
88537 sqlite3_context *context,
88538 int argc,
88539 sqlite3_value **argv
88541 const unsigned char *zStr; /* The input string A */
88542 const unsigned char *zPattern; /* The pattern string B */
88543 const unsigned char *zRep; /* The replacement string C */
88544 unsigned char *zOut; /* The output */
88545 int nStr; /* Size of zStr */
88546 int nPattern; /* Size of zPattern */
88547 int nRep; /* Size of zRep */
88548 i64 nOut; /* Maximum size of zOut */
88549 int loopLimit; /* Last zStr[] that might match zPattern[] */
88550 int i, j; /* Loop counters */
88552 assert( argc==3 );
88553 UNUSED_PARAMETER(argc);
88554 zStr = sqlite3_value_text(argv[0]);
88555 if( zStr==0 ) return;
88556 nStr = sqlite3_value_bytes(argv[0]);
88557 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
88558 zPattern = sqlite3_value_text(argv[1]);
88559 if( zPattern==0 ){
88560 assert( sqlite3_value_type(argv[1])==SQLITE_NULL
88561 || sqlite3_context_db_handle(context)->mallocFailed );
88562 return;
88564 if( zPattern[0]==0 ){
88565 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
88566 sqlite3_result_value(context, argv[0]);
88567 return;
88569 nPattern = sqlite3_value_bytes(argv[1]);
88570 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
88571 zRep = sqlite3_value_text(argv[2]);
88572 if( zRep==0 ) return;
88573 nRep = sqlite3_value_bytes(argv[2]);
88574 assert( zRep==sqlite3_value_text(argv[2]) );
88575 nOut = nStr + 1;
88576 assert( nOut<SQLITE_MAX_LENGTH );
88577 zOut = contextMalloc(context, (i64)nOut);
88578 if( zOut==0 ){
88579 return;
88581 loopLimit = nStr - nPattern;
88582 for(i=j=0; i<=loopLimit; i++){
88583 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
88584 zOut[j++] = zStr[i];
88585 }else{
88586 u8 *zOld;
88587 sqlite3 *db = sqlite3_context_db_handle(context);
88588 nOut += nRep - nPattern;
88589 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
88590 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
88591 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
88592 sqlite3_result_error_toobig(context);
88593 sqlite3_free(zOut);
88594 return;
88596 zOld = zOut;
88597 zOut = sqlite3_realloc(zOut, (int)nOut);
88598 if( zOut==0 ){
88599 sqlite3_result_error_nomem(context);
88600 sqlite3_free(zOld);
88601 return;
88603 memcpy(&zOut[j], zRep, nRep);
88604 j += nRep;
88605 i += nPattern-1;
88608 assert( j+nStr-i+1==nOut );
88609 memcpy(&zOut[j], &zStr[i], nStr-i);
88610 j += nStr - i;
88611 assert( j<=nOut );
88612 zOut[j] = 0;
88613 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
88617 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
88618 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
88620 static void trimFunc(
88621 sqlite3_context *context,
88622 int argc,
88623 sqlite3_value **argv
88625 const unsigned char *zIn; /* Input string */
88626 const unsigned char *zCharSet; /* Set of characters to trim */
88627 int nIn; /* Number of bytes in input */
88628 int flags; /* 1: trimleft 2: trimright 3: trim */
88629 int i; /* Loop counter */
88630 unsigned char *aLen = 0; /* Length of each character in zCharSet */
88631 unsigned char **azChar = 0; /* Individual characters in zCharSet */
88632 int nChar; /* Number of characters in zCharSet */
88634 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
88635 return;
88637 zIn = sqlite3_value_text(argv[0]);
88638 if( zIn==0 ) return;
88639 nIn = sqlite3_value_bytes(argv[0]);
88640 assert( zIn==sqlite3_value_text(argv[0]) );
88641 if( argc==1 ){
88642 static const unsigned char lenOne[] = { 1 };
88643 static unsigned char * const azOne[] = { (u8*)" " };
88644 nChar = 1;
88645 aLen = (u8*)lenOne;
88646 azChar = (unsigned char **)azOne;
88647 zCharSet = 0;
88648 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
88649 return;
88650 }else{
88651 const unsigned char *z;
88652 for(z=zCharSet, nChar=0; *z; nChar++){
88653 SQLITE_SKIP_UTF8(z);
88655 if( nChar>0 ){
88656 azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
88657 if( azChar==0 ){
88658 return;
88660 aLen = (unsigned char*)&azChar[nChar];
88661 for(z=zCharSet, nChar=0; *z; nChar++){
88662 azChar[nChar] = (unsigned char *)z;
88663 SQLITE_SKIP_UTF8(z);
88664 aLen[nChar] = (u8)(z - azChar[nChar]);
88668 if( nChar>0 ){
88669 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
88670 if( flags & 1 ){
88671 while( nIn>0 ){
88672 int len = 0;
88673 for(i=0; i<nChar; i++){
88674 len = aLen[i];
88675 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
88677 if( i>=nChar ) break;
88678 zIn += len;
88679 nIn -= len;
88682 if( flags & 2 ){
88683 while( nIn>0 ){
88684 int len = 0;
88685 for(i=0; i<nChar; i++){
88686 len = aLen[i];
88687 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
88689 if( i>=nChar ) break;
88690 nIn -= len;
88693 if( zCharSet ){
88694 sqlite3_free(azChar);
88697 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
88701 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
88702 ** is only available if the SQLITE_SOUNDEX compile-time option is used
88703 ** when SQLite is built.
88705 #ifdef SQLITE_SOUNDEX
88707 ** Compute the soundex encoding of a word.
88709 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
88710 ** soundex encoding of the string X.
88712 static void soundexFunc(
88713 sqlite3_context *context,
88714 int argc,
88715 sqlite3_value **argv
88717 char zResult[8];
88718 const u8 *zIn;
88719 int i, j;
88720 static const unsigned char iCode[] = {
88721 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88722 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88723 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88724 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88725 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
88726 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
88727 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
88728 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
88730 assert( argc==1 );
88731 zIn = (u8*)sqlite3_value_text(argv[0]);
88732 if( zIn==0 ) zIn = (u8*)"";
88733 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
88734 if( zIn[i] ){
88735 u8 prevcode = iCode[zIn[i]&0x7f];
88736 zResult[0] = sqlite3Toupper(zIn[i]);
88737 for(j=1; j<4 && zIn[i]; i++){
88738 int code = iCode[zIn[i]&0x7f];
88739 if( code>0 ){
88740 if( code!=prevcode ){
88741 prevcode = code;
88742 zResult[j++] = code + '0';
88744 }else{
88745 prevcode = 0;
88748 while( j<4 ){
88749 zResult[j++] = '0';
88751 zResult[j] = 0;
88752 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
88753 }else{
88754 /* IMP: R-64894-50321 The string "?000" is returned if the argument
88755 ** is NULL or contains no ASCII alphabetic characters. */
88756 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
88759 #endif /* SQLITE_SOUNDEX */
88761 #ifndef SQLITE_OMIT_LOAD_EXTENSION
88763 ** A function that loads a shared-library extension then returns NULL.
88765 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
88766 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
88767 const char *zProc;
88768 sqlite3 *db = sqlite3_context_db_handle(context);
88769 char *zErrMsg = 0;
88771 if( argc==2 ){
88772 zProc = (const char *)sqlite3_value_text(argv[1]);
88773 }else{
88774 zProc = 0;
88776 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
88777 sqlite3_result_error(context, zErrMsg, -1);
88778 sqlite3_free(zErrMsg);
88781 #endif
88785 ** An instance of the following structure holds the context of a
88786 ** sum() or avg() aggregate computation.
88788 typedef struct SumCtx SumCtx;
88789 struct SumCtx {
88790 double rSum; /* Floating point sum */
88791 i64 iSum; /* Integer sum */
88792 i64 cnt; /* Number of elements summed */
88793 u8 overflow; /* True if integer overflow seen */
88794 u8 approx; /* True if non-integer value was input to the sum */
88798 ** Routines used to compute the sum, average, and total.
88800 ** The SUM() function follows the (broken) SQL standard which means
88801 ** that it returns NULL if it sums over no inputs. TOTAL returns
88802 ** 0.0 in that case. In addition, TOTAL always returns a float where
88803 ** SUM might return an integer if it never encounters a floating point
88804 ** value. TOTAL never fails, but SUM might through an exception if
88805 ** it overflows an integer.
88807 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88808 SumCtx *p;
88809 int type;
88810 assert( argc==1 );
88811 UNUSED_PARAMETER(argc);
88812 p = sqlite3_aggregate_context(context, sizeof(*p));
88813 type = sqlite3_value_numeric_type(argv[0]);
88814 if( p && type!=SQLITE_NULL ){
88815 p->cnt++;
88816 if( type==SQLITE_INTEGER ){
88817 i64 v = sqlite3_value_int64(argv[0]);
88818 p->rSum += v;
88819 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
88820 p->overflow = 1;
88822 }else{
88823 p->rSum += sqlite3_value_double(argv[0]);
88824 p->approx = 1;
88828 static void sumFinalize(sqlite3_context *context){
88829 SumCtx *p;
88830 p = sqlite3_aggregate_context(context, 0);
88831 if( p && p->cnt>0 ){
88832 if( p->overflow ){
88833 sqlite3_result_error(context,"integer overflow",-1);
88834 }else if( p->approx ){
88835 sqlite3_result_double(context, p->rSum);
88836 }else{
88837 sqlite3_result_int64(context, p->iSum);
88841 static void avgFinalize(sqlite3_context *context){
88842 SumCtx *p;
88843 p = sqlite3_aggregate_context(context, 0);
88844 if( p && p->cnt>0 ){
88845 sqlite3_result_double(context, p->rSum/(double)p->cnt);
88848 static void totalFinalize(sqlite3_context *context){
88849 SumCtx *p;
88850 p = sqlite3_aggregate_context(context, 0);
88851 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
88852 sqlite3_result_double(context, p ? p->rSum : (double)0);
88856 ** The following structure keeps track of state information for the
88857 ** count() aggregate function.
88859 typedef struct CountCtx CountCtx;
88860 struct CountCtx {
88861 i64 n;
88865 ** Routines to implement the count() aggregate function.
88867 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88868 CountCtx *p;
88869 p = sqlite3_aggregate_context(context, sizeof(*p));
88870 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
88871 p->n++;
88874 #ifndef SQLITE_OMIT_DEPRECATED
88875 /* The sqlite3_aggregate_count() function is deprecated. But just to make
88876 ** sure it still operates correctly, verify that its count agrees with our
88877 ** internal count when using count(*) and when the total count can be
88878 ** expressed as a 32-bit integer. */
88879 assert( argc==1 || p==0 || p->n>0x7fffffff
88880 || p->n==sqlite3_aggregate_count(context) );
88881 #endif
88883 static void countFinalize(sqlite3_context *context){
88884 CountCtx *p;
88885 p = sqlite3_aggregate_context(context, 0);
88886 sqlite3_result_int64(context, p ? p->n : 0);
88890 ** Routines to implement min() and max() aggregate functions.
88892 static void minmaxStep(
88893 sqlite3_context *context,
88894 int NotUsed,
88895 sqlite3_value **argv
88897 Mem *pArg = (Mem *)argv[0];
88898 Mem *pBest;
88899 UNUSED_PARAMETER(NotUsed);
88901 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
88902 if( !pBest ) return;
88904 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
88905 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
88906 }else if( pBest->flags ){
88907 int max;
88908 int cmp;
88909 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
88910 /* This step function is used for both the min() and max() aggregates,
88911 ** the only difference between the two being that the sense of the
88912 ** comparison is inverted. For the max() aggregate, the
88913 ** sqlite3_user_data() function returns (void *)-1. For min() it
88914 ** returns (void *)db, where db is the sqlite3* database pointer.
88915 ** Therefore the next statement sets variable 'max' to 1 for the max()
88916 ** aggregate, or 0 for min().
88918 max = sqlite3_user_data(context)!=0;
88919 cmp = sqlite3MemCompare(pBest, pArg, pColl);
88920 if( (max && cmp<0) || (!max && cmp>0) ){
88921 sqlite3VdbeMemCopy(pBest, pArg);
88922 }else{
88923 sqlite3SkipAccumulatorLoad(context);
88925 }else{
88926 sqlite3VdbeMemCopy(pBest, pArg);
88929 static void minMaxFinalize(sqlite3_context *context){
88930 sqlite3_value *pRes;
88931 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
88932 if( pRes ){
88933 if( pRes->flags ){
88934 sqlite3_result_value(context, pRes);
88936 sqlite3VdbeMemRelease(pRes);
88941 ** group_concat(EXPR, ?SEPARATOR?)
88943 static void groupConcatStep(
88944 sqlite3_context *context,
88945 int argc,
88946 sqlite3_value **argv
88948 const char *zVal;
88949 StrAccum *pAccum;
88950 const char *zSep;
88951 int nVal, nSep;
88952 assert( argc==1 || argc==2 );
88953 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
88954 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
88956 if( pAccum ){
88957 sqlite3 *db = sqlite3_context_db_handle(context);
88958 int firstTerm = pAccum->useMalloc==0;
88959 pAccum->useMalloc = 2;
88960 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
88961 if( !firstTerm ){
88962 if( argc==2 ){
88963 zSep = (char*)sqlite3_value_text(argv[1]);
88964 nSep = sqlite3_value_bytes(argv[1]);
88965 }else{
88966 zSep = ",";
88967 nSep = 1;
88969 sqlite3StrAccumAppend(pAccum, zSep, nSep);
88971 zVal = (char*)sqlite3_value_text(argv[0]);
88972 nVal = sqlite3_value_bytes(argv[0]);
88973 sqlite3StrAccumAppend(pAccum, zVal, nVal);
88976 static void groupConcatFinalize(sqlite3_context *context){
88977 StrAccum *pAccum;
88978 pAccum = sqlite3_aggregate_context(context, 0);
88979 if( pAccum ){
88980 if( pAccum->accError==STRACCUM_TOOBIG ){
88981 sqlite3_result_error_toobig(context);
88982 }else if( pAccum->accError==STRACCUM_NOMEM ){
88983 sqlite3_result_error_nomem(context);
88984 }else{
88985 sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
88986 sqlite3_free);
88992 ** This routine does per-connection function registration. Most
88993 ** of the built-in functions above are part of the global function set.
88994 ** This routine only deals with those that are not global.
88996 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
88997 int rc = sqlite3_overload_function(db, "MATCH", 2);
88998 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
88999 if( rc==SQLITE_NOMEM ){
89000 db->mallocFailed = 1;
89005 ** Set the LIKEOPT flag on the 2-argument function with the given name.
89007 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
89008 FuncDef *pDef;
89009 pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
89010 2, SQLITE_UTF8, 0);
89011 if( ALWAYS(pDef) ){
89012 pDef->flags = flagVal;
89017 ** Register the built-in LIKE and GLOB functions. The caseSensitive
89018 ** parameter determines whether or not the LIKE operator is case
89019 ** sensitive. GLOB is always case sensitive.
89021 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
89022 struct compareInfo *pInfo;
89023 if( caseSensitive ){
89024 pInfo = (struct compareInfo*)&likeInfoAlt;
89025 }else{
89026 pInfo = (struct compareInfo*)&likeInfoNorm;
89028 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
89029 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
89030 sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
89031 (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
89032 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
89033 setLikeOptFlag(db, "like",
89034 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
89038 ** pExpr points to an expression which implements a function. If
89039 ** it is appropriate to apply the LIKE optimization to that function
89040 ** then set aWc[0] through aWc[2] to the wildcard characters and
89041 ** return TRUE. If the function is not a LIKE-style function then
89042 ** return FALSE.
89044 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
89045 FuncDef *pDef;
89046 if( pExpr->op!=TK_FUNCTION
89047 || !pExpr->x.pList
89048 || pExpr->x.pList->nExpr!=2
89050 return 0;
89052 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
89053 pDef = sqlite3FindFunction(db, pExpr->u.zToken,
89054 sqlite3Strlen30(pExpr->u.zToken),
89055 2, SQLITE_UTF8, 0);
89056 if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
89057 return 0;
89060 /* The memcpy() statement assumes that the wildcard characters are
89061 ** the first three statements in the compareInfo structure. The
89062 ** asserts() that follow verify that assumption
89064 memcpy(aWc, pDef->pUserData, 3);
89065 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
89066 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
89067 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
89068 *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
89069 return 1;
89073 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
89074 ** to the global function hash table. This occurs at start-time (as
89075 ** a consequence of calling sqlite3_initialize()).
89077 ** After this routine runs
89079 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
89081 ** The following array holds FuncDef structures for all of the functions
89082 ** defined in this file.
89084 ** The array cannot be constant since changes are made to the
89085 ** FuncDef.pHash elements at start-time. The elements of this array
89086 ** are read-only after initialization is complete.
89088 static SQLITE_WSD FuncDef aBuiltinFunc[] = {
89089 FUNCTION(ltrim, 1, 1, 0, trimFunc ),
89090 FUNCTION(ltrim, 2, 1, 0, trimFunc ),
89091 FUNCTION(rtrim, 1, 2, 0, trimFunc ),
89092 FUNCTION(rtrim, 2, 2, 0, trimFunc ),
89093 FUNCTION(trim, 1, 3, 0, trimFunc ),
89094 FUNCTION(trim, 2, 3, 0, trimFunc ),
89095 FUNCTION(min, -1, 0, 1, minmaxFunc ),
89096 FUNCTION(min, 0, 0, 1, 0 ),
89097 AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
89098 FUNCTION(max, -1, 1, 1, minmaxFunc ),
89099 FUNCTION(max, 0, 1, 1, 0 ),
89100 AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
89101 FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
89102 FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
89103 FUNCTION(instr, 2, 0, 0, instrFunc ),
89104 FUNCTION(substr, 2, 0, 0, substrFunc ),
89105 FUNCTION(substr, 3, 0, 0, substrFunc ),
89106 FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
89107 FUNCTION(char, -1, 0, 0, charFunc ),
89108 FUNCTION(abs, 1, 0, 0, absFunc ),
89109 #ifndef SQLITE_OMIT_FLOATING_POINT
89110 FUNCTION(round, 1, 0, 0, roundFunc ),
89111 FUNCTION(round, 2, 0, 0, roundFunc ),
89112 #endif
89113 FUNCTION(upper, 1, 0, 0, upperFunc ),
89114 FUNCTION(lower, 1, 0, 0, lowerFunc ),
89115 FUNCTION(coalesce, 1, 0, 0, 0 ),
89116 FUNCTION(coalesce, 0, 0, 0, 0 ),
89117 FUNCTION2(coalesce, -1, 0, 0, ifnullFunc, SQLITE_FUNC_COALESCE),
89118 FUNCTION(hex, 1, 0, 0, hexFunc ),
89119 FUNCTION2(ifnull, 2, 0, 0, ifnullFunc, SQLITE_FUNC_COALESCE),
89120 FUNCTION(random, 0, 0, 0, randomFunc ),
89121 FUNCTION(randomblob, 1, 0, 0, randomBlob ),
89122 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
89123 FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
89124 FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
89125 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
89126 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
89127 FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
89128 FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
89129 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
89130 FUNCTION(quote, 1, 0, 0, quoteFunc ),
89131 FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
89132 FUNCTION(changes, 0, 0, 0, changes ),
89133 FUNCTION(total_changes, 0, 0, 0, total_changes ),
89134 FUNCTION(replace, 3, 0, 0, replaceFunc ),
89135 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
89136 #ifdef SQLITE_SOUNDEX
89137 FUNCTION(soundex, 1, 0, 0, soundexFunc ),
89138 #endif
89139 #ifndef SQLITE_OMIT_LOAD_EXTENSION
89140 FUNCTION(load_extension, 1, 0, 0, loadExt ),
89141 FUNCTION(load_extension, 2, 0, 0, loadExt ),
89142 #endif
89143 AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
89144 AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
89145 AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
89146 /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
89147 {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
89148 AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
89149 AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
89150 AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
89152 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
89153 #ifdef SQLITE_CASE_SENSITIVE_LIKE
89154 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
89155 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
89156 #else
89157 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
89158 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
89159 #endif
89162 int i;
89163 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
89164 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
89166 for(i=0; i<ArraySize(aBuiltinFunc); i++){
89167 sqlite3FuncDefInsert(pHash, &aFunc[i]);
89169 sqlite3RegisterDateTimeFunctions();
89170 #ifndef SQLITE_OMIT_ALTERTABLE
89171 sqlite3AlterFunctions();
89172 #endif
89175 /************** End of func.c ************************************************/
89176 /************** Begin file fkey.c ********************************************/
89179 ** The author disclaims copyright to this source code. In place of
89180 ** a legal notice, here is a blessing:
89182 ** May you do good and not evil.
89183 ** May you find forgiveness for yourself and forgive others.
89184 ** May you share freely, never taking more than you give.
89186 *************************************************************************
89187 ** This file contains code used by the compiler to add foreign key
89188 ** support to compiled SQL statements.
89191 #ifndef SQLITE_OMIT_FOREIGN_KEY
89192 #ifndef SQLITE_OMIT_TRIGGER
89195 ** Deferred and Immediate FKs
89196 ** --------------------------
89198 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
89199 ** If an immediate foreign key constraint is violated,
89200 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
89201 ** statement transaction rolled back. If a
89202 ** deferred foreign key constraint is violated, no action is taken
89203 ** immediately. However if the application attempts to commit the
89204 ** transaction before fixing the constraint violation, the attempt fails.
89206 ** Deferred constraints are implemented using a simple counter associated
89207 ** with the database handle. The counter is set to zero each time a
89208 ** database transaction is opened. Each time a statement is executed
89209 ** that causes a foreign key violation, the counter is incremented. Each
89210 ** time a statement is executed that removes an existing violation from
89211 ** the database, the counter is decremented. When the transaction is
89212 ** committed, the commit fails if the current value of the counter is
89213 ** greater than zero. This scheme has two big drawbacks:
89215 ** * When a commit fails due to a deferred foreign key constraint,
89216 ** there is no way to tell which foreign constraint is not satisfied,
89217 ** or which row it is not satisfied for.
89219 ** * If the database contains foreign key violations when the
89220 ** transaction is opened, this may cause the mechanism to malfunction.
89222 ** Despite these problems, this approach is adopted as it seems simpler
89223 ** than the alternatives.
89225 ** INSERT operations:
89227 ** I.1) For each FK for which the table is the child table, search
89228 ** the parent table for a match. If none is found increment the
89229 ** constraint counter.
89231 ** I.2) For each FK for which the table is the parent table,
89232 ** search the child table for rows that correspond to the new
89233 ** row in the parent table. Decrement the counter for each row
89234 ** found (as the constraint is now satisfied).
89236 ** DELETE operations:
89238 ** D.1) For each FK for which the table is the child table,
89239 ** search the parent table for a row that corresponds to the
89240 ** deleted row in the child table. If such a row is not found,
89241 ** decrement the counter.
89243 ** D.2) For each FK for which the table is the parent table, search
89244 ** the child table for rows that correspond to the deleted row
89245 ** in the parent table. For each found increment the counter.
89247 ** UPDATE operations:
89249 ** An UPDATE command requires that all 4 steps above are taken, but only
89250 ** for FK constraints for which the affected columns are actually
89251 ** modified (values must be compared at runtime).
89253 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
89254 ** This simplifies the implementation a bit.
89256 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
89257 ** resolution is considered to delete rows before the new row is inserted.
89258 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
89259 ** is thrown, even if the FK constraint would be satisfied after the new
89260 ** row is inserted.
89262 ** Immediate constraints are usually handled similarly. The only difference
89263 ** is that the counter used is stored as part of each individual statement
89264 ** object (struct Vdbe). If, after the statement has run, its immediate
89265 ** constraint counter is greater than zero,
89266 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
89267 ** and the statement transaction is rolled back. An exception is an INSERT
89268 ** statement that inserts a single row only (no triggers). In this case,
89269 ** instead of using a counter, an exception is thrown immediately if the
89270 ** INSERT violates a foreign key constraint. This is necessary as such
89271 ** an INSERT does not open a statement transaction.
89273 ** TODO: How should dropping a table be handled? How should renaming a
89274 ** table be handled?
89277 ** Query API Notes
89278 ** ---------------
89280 ** Before coding an UPDATE or DELETE row operation, the code-generator
89281 ** for those two operations needs to know whether or not the operation
89282 ** requires any FK processing and, if so, which columns of the original
89283 ** row are required by the FK processing VDBE code (i.e. if FKs were
89284 ** implemented using triggers, which of the old.* columns would be
89285 ** accessed). No information is required by the code-generator before
89286 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
89287 ** generation code to query for this information are:
89289 ** sqlite3FkRequired() - Test to see if FK processing is required.
89290 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
89293 ** Externally accessible module functions
89294 ** --------------------------------------
89296 ** sqlite3FkCheck() - Check for foreign key violations.
89297 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
89298 ** sqlite3FkDelete() - Delete an FKey structure.
89302 ** VDBE Calling Convention
89303 ** -----------------------
89305 ** Example:
89307 ** For the following INSERT statement:
89309 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
89310 ** INSERT INTO t1 VALUES(1, 2, 3.1);
89312 ** Register (x): 2 (type integer)
89313 ** Register (x+1): 1 (type integer)
89314 ** Register (x+2): NULL (type NULL)
89315 ** Register (x+3): 3.1 (type real)
89319 ** A foreign key constraint requires that the key columns in the parent
89320 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
89321 ** Given that pParent is the parent table for foreign key constraint pFKey,
89322 ** search the schema for a unique index on the parent key columns.
89324 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
89325 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
89326 ** is set to point to the unique index.
89328 ** If the parent key consists of a single column (the foreign key constraint
89329 ** is not a composite foreign key), output variable *paiCol is set to NULL.
89330 ** Otherwise, it is set to point to an allocated array of size N, where
89331 ** N is the number of columns in the parent key. The first element of the
89332 ** array is the index of the child table column that is mapped by the FK
89333 ** constraint to the parent table column stored in the left-most column
89334 ** of index *ppIdx. The second element of the array is the index of the
89335 ** child table column that corresponds to the second left-most column of
89336 ** *ppIdx, and so on.
89338 ** If the required index cannot be found, either because:
89340 ** 1) The named parent key columns do not exist, or
89342 ** 2) The named parent key columns do exist, but are not subject to a
89343 ** UNIQUE or PRIMARY KEY constraint, or
89345 ** 3) No parent key columns were provided explicitly as part of the
89346 ** foreign key definition, and the parent table does not have a
89347 ** PRIMARY KEY, or
89349 ** 4) No parent key columns were provided explicitly as part of the
89350 ** foreign key definition, and the PRIMARY KEY of the parent table
89351 ** consists of a a different number of columns to the child key in
89352 ** the child table.
89354 ** then non-zero is returned, and a "foreign key mismatch" error loaded
89355 ** into pParse. If an OOM error occurs, non-zero is returned and the
89356 ** pParse->db->mallocFailed flag is set.
89358 SQLITE_PRIVATE int sqlite3FkLocateIndex(
89359 Parse *pParse, /* Parse context to store any error in */
89360 Table *pParent, /* Parent table of FK constraint pFKey */
89361 FKey *pFKey, /* Foreign key to find index for */
89362 Index **ppIdx, /* OUT: Unique index on parent table */
89363 int **paiCol /* OUT: Map of index columns in pFKey */
89365 Index *pIdx = 0; /* Value to return via *ppIdx */
89366 int *aiCol = 0; /* Value to return via *paiCol */
89367 int nCol = pFKey->nCol; /* Number of columns in parent key */
89368 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
89370 /* The caller is responsible for zeroing output parameters. */
89371 assert( ppIdx && *ppIdx==0 );
89372 assert( !paiCol || *paiCol==0 );
89373 assert( pParse );
89375 /* If this is a non-composite (single column) foreign key, check if it
89376 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
89377 ** and *paiCol set to zero and return early.
89379 ** Otherwise, for a composite foreign key (more than one column), allocate
89380 ** space for the aiCol array (returned via output parameter *paiCol).
89381 ** Non-composite foreign keys do not require the aiCol array.
89383 if( nCol==1 ){
89384 /* The FK maps to the IPK if any of the following are true:
89386 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
89387 ** mapped to the primary key of table pParent, or
89388 ** 2) The FK is explicitly mapped to a column declared as INTEGER
89389 ** PRIMARY KEY.
89391 if( pParent->iPKey>=0 ){
89392 if( !zKey ) return 0;
89393 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
89395 }else if( paiCol ){
89396 assert( nCol>1 );
89397 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
89398 if( !aiCol ) return 1;
89399 *paiCol = aiCol;
89402 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
89403 if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
89404 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
89405 ** of columns. If each indexed column corresponds to a foreign key
89406 ** column of pFKey, then this index is a winner. */
89408 if( zKey==0 ){
89409 /* If zKey is NULL, then this foreign key is implicitly mapped to
89410 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
89411 ** identified by the test (Index.autoIndex==2). */
89412 if( pIdx->autoIndex==2 ){
89413 if( aiCol ){
89414 int i;
89415 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
89417 break;
89419 }else{
89420 /* If zKey is non-NULL, then this foreign key was declared to
89421 ** map to an explicit list of columns in table pParent. Check if this
89422 ** index matches those columns. Also, check that the index uses
89423 ** the default collation sequences for each column. */
89424 int i, j;
89425 for(i=0; i<nCol; i++){
89426 int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
89427 char *zDfltColl; /* Def. collation for column */
89428 char *zIdxCol; /* Name of indexed column */
89430 /* If the index uses a collation sequence that is different from
89431 ** the default collation sequence for the column, this index is
89432 ** unusable. Bail out early in this case. */
89433 zDfltColl = pParent->aCol[iCol].zColl;
89434 if( !zDfltColl ){
89435 zDfltColl = "BINARY";
89437 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
89439 zIdxCol = pParent->aCol[iCol].zName;
89440 for(j=0; j<nCol; j++){
89441 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
89442 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
89443 break;
89446 if( j==nCol ) break;
89448 if( i==nCol ) break; /* pIdx is usable */
89453 if( !pIdx ){
89454 if( !pParse->disableTriggers ){
89455 sqlite3ErrorMsg(pParse,
89456 "foreign key mismatch - \"%w\" referencing \"%w\"",
89457 pFKey->pFrom->zName, pFKey->zTo);
89459 sqlite3DbFree(pParse->db, aiCol);
89460 return 1;
89463 *ppIdx = pIdx;
89464 return 0;
89468 ** This function is called when a row is inserted into or deleted from the
89469 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
89470 ** on the child table of pFKey, this function is invoked twice for each row
89471 ** affected - once to "delete" the old row, and then again to "insert" the
89472 ** new row.
89474 ** Each time it is called, this function generates VDBE code to locate the
89475 ** row in the parent table that corresponds to the row being inserted into
89476 ** or deleted from the child table. If the parent row can be found, no
89477 ** special action is taken. Otherwise, if the parent row can *not* be
89478 ** found in the parent table:
89480 ** Operation | FK type | Action taken
89481 ** --------------------------------------------------------------------------
89482 ** INSERT immediate Increment the "immediate constraint counter".
89484 ** DELETE immediate Decrement the "immediate constraint counter".
89486 ** INSERT deferred Increment the "deferred constraint counter".
89488 ** DELETE deferred Decrement the "deferred constraint counter".
89490 ** These operations are identified in the comment at the top of this file
89491 ** (fkey.c) as "I.1" and "D.1".
89493 static void fkLookupParent(
89494 Parse *pParse, /* Parse context */
89495 int iDb, /* Index of database housing pTab */
89496 Table *pTab, /* Parent table of FK pFKey */
89497 Index *pIdx, /* Unique index on parent key columns in pTab */
89498 FKey *pFKey, /* Foreign key constraint */
89499 int *aiCol, /* Map from parent key columns to child table columns */
89500 int regData, /* Address of array containing child table row */
89501 int nIncr, /* Increment constraint counter by this */
89502 int isIgnore /* If true, pretend pTab contains all NULL values */
89504 int i; /* Iterator variable */
89505 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
89506 int iCur = pParse->nTab - 1; /* Cursor number to use */
89507 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
89509 /* If nIncr is less than zero, then check at runtime if there are any
89510 ** outstanding constraints to resolve. If there are not, there is no need
89511 ** to check if deleting this row resolves any outstanding violations.
89513 ** Check if any of the key columns in the child table row are NULL. If
89514 ** any are, then the constraint is considered satisfied. No need to
89515 ** search for a matching row in the parent table. */
89516 if( nIncr<0 ){
89517 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
89519 for(i=0; i<pFKey->nCol; i++){
89520 int iReg = aiCol[i] + regData + 1;
89521 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
89524 if( isIgnore==0 ){
89525 if( pIdx==0 ){
89526 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
89527 ** column of the parent table (table pTab). */
89528 int iMustBeInt; /* Address of MustBeInt instruction */
89529 int regTemp = sqlite3GetTempReg(pParse);
89531 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
89532 ** apply the affinity of the parent key). If this fails, then there
89533 ** is no matching parent key. Before using MustBeInt, make a copy of
89534 ** the value. Otherwise, the value inserted into the child key column
89535 ** will have INTEGER affinity applied to it, which may not be correct. */
89536 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
89537 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
89539 /* If the parent table is the same as the child table, and we are about
89540 ** to increment the constraint-counter (i.e. this is an INSERT operation),
89541 ** then check if the row being inserted matches itself. If so, do not
89542 ** increment the constraint-counter. */
89543 if( pTab==pFKey->pFrom && nIncr==1 ){
89544 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
89547 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
89548 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
89549 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
89550 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
89551 sqlite3VdbeJumpHere(v, iMustBeInt);
89552 sqlite3ReleaseTempReg(pParse, regTemp);
89553 }else{
89554 int nCol = pFKey->nCol;
89555 int regTemp = sqlite3GetTempRange(pParse, nCol);
89556 int regRec = sqlite3GetTempReg(pParse);
89557 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
89559 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
89560 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
89561 for(i=0; i<nCol; i++){
89562 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
89565 /* If the parent table is the same as the child table, and we are about
89566 ** to increment the constraint-counter (i.e. this is an INSERT operation),
89567 ** then check if the row being inserted matches itself. If so, do not
89568 ** increment the constraint-counter.
89570 ** If any of the parent-key values are NULL, then the row cannot match
89571 ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
89572 ** of the parent-key values are NULL (at this point it is known that
89573 ** none of the child key values are).
89575 if( pTab==pFKey->pFrom && nIncr==1 ){
89576 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
89577 for(i=0; i<nCol; i++){
89578 int iChild = aiCol[i]+1+regData;
89579 int iParent = pIdx->aiColumn[i]+1+regData;
89580 assert( aiCol[i]!=pTab->iPKey );
89581 if( pIdx->aiColumn[i]==pTab->iPKey ){
89582 /* The parent key is a composite key that includes the IPK column */
89583 iParent = regData;
89585 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
89586 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
89588 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
89591 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
89592 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
89593 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
89595 sqlite3ReleaseTempReg(pParse, regRec);
89596 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
89600 if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
89601 && !pParse->pToplevel
89602 && !pParse->isMultiWrite
89604 /* Special case: If this is an INSERT statement that will insert exactly
89605 ** one row into the table, raise a constraint immediately instead of
89606 ** incrementing a counter. This is necessary as the VM code is being
89607 ** generated for will not open a statement transaction. */
89608 assert( nIncr==1 );
89609 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
89610 OE_Abort, "foreign key constraint failed", P4_STATIC
89612 }else{
89613 if( nIncr>0 && pFKey->isDeferred==0 ){
89614 sqlite3ParseToplevel(pParse)->mayAbort = 1;
89616 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
89619 sqlite3VdbeResolveLabel(v, iOk);
89620 sqlite3VdbeAddOp1(v, OP_Close, iCur);
89624 ** This function is called to generate code executed when a row is deleted
89625 ** from the parent table of foreign key constraint pFKey and, if pFKey is
89626 ** deferred, when a row is inserted into the same table. When generating
89627 ** code for an SQL UPDATE operation, this function may be called twice -
89628 ** once to "delete" the old row and once to "insert" the new row.
89630 ** The code generated by this function scans through the rows in the child
89631 ** table that correspond to the parent table row being deleted or inserted.
89632 ** For each child row found, one of the following actions is taken:
89634 ** Operation | FK type | Action taken
89635 ** --------------------------------------------------------------------------
89636 ** DELETE immediate Increment the "immediate constraint counter".
89637 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
89638 ** throw a "foreign key constraint failed" exception.
89640 ** INSERT immediate Decrement the "immediate constraint counter".
89642 ** DELETE deferred Increment the "deferred constraint counter".
89643 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
89644 ** throw a "foreign key constraint failed" exception.
89646 ** INSERT deferred Decrement the "deferred constraint counter".
89648 ** These operations are identified in the comment at the top of this file
89649 ** (fkey.c) as "I.2" and "D.2".
89651 static void fkScanChildren(
89652 Parse *pParse, /* Parse context */
89653 SrcList *pSrc, /* SrcList containing the table to scan */
89654 Table *pTab,
89655 Index *pIdx, /* Foreign key index */
89656 FKey *pFKey, /* Foreign key relationship */
89657 int *aiCol, /* Map from pIdx cols to child table cols */
89658 int regData, /* Referenced table data starts here */
89659 int nIncr /* Amount to increment deferred counter by */
89661 sqlite3 *db = pParse->db; /* Database handle */
89662 int i; /* Iterator variable */
89663 Expr *pWhere = 0; /* WHERE clause to scan with */
89664 NameContext sNameContext; /* Context used to resolve WHERE clause */
89665 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
89666 int iFkIfZero = 0; /* Address of OP_FkIfZero */
89667 Vdbe *v = sqlite3GetVdbe(pParse);
89669 assert( !pIdx || pIdx->pTable==pTab );
89671 if( nIncr<0 ){
89672 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
89675 /* Create an Expr object representing an SQL expression like:
89677 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
89679 ** The collation sequence used for the comparison should be that of
89680 ** the parent key columns. The affinity of the parent key column should
89681 ** be applied to each child key value before the comparison takes place.
89683 for(i=0; i<pFKey->nCol; i++){
89684 Expr *pLeft; /* Value from parent table row */
89685 Expr *pRight; /* Column ref to child table */
89686 Expr *pEq; /* Expression (pLeft = pRight) */
89687 int iCol; /* Index of column in child table */
89688 const char *zCol; /* Name of column in child table */
89690 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
89691 if( pLeft ){
89692 /* Set the collation sequence and affinity of the LHS of each TK_EQ
89693 ** expression to the parent key column defaults. */
89694 if( pIdx ){
89695 Column *pCol;
89696 const char *zColl;
89697 iCol = pIdx->aiColumn[i];
89698 pCol = &pTab->aCol[iCol];
89699 if( pTab->iPKey==iCol ) iCol = -1;
89700 pLeft->iTable = regData+iCol+1;
89701 pLeft->affinity = pCol->affinity;
89702 zColl = pCol->zColl;
89703 if( zColl==0 ) zColl = db->pDfltColl->zName;
89704 pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
89705 }else{
89706 pLeft->iTable = regData;
89707 pLeft->affinity = SQLITE_AFF_INTEGER;
89710 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
89711 assert( iCol>=0 );
89712 zCol = pFKey->pFrom->aCol[iCol].zName;
89713 pRight = sqlite3Expr(db, TK_ID, zCol);
89714 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
89715 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89718 /* If the child table is the same as the parent table, and this scan
89719 ** is taking place as part of a DELETE operation (operation D.2), omit the
89720 ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
89721 ** clause, where $rowid is the rowid of the row being deleted. */
89722 if( pTab==pFKey->pFrom && nIncr>0 ){
89723 Expr *pEq; /* Expression (pLeft = pRight) */
89724 Expr *pLeft; /* Value from parent table row */
89725 Expr *pRight; /* Column ref to child table */
89726 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
89727 pRight = sqlite3Expr(db, TK_COLUMN, 0);
89728 if( pLeft && pRight ){
89729 pLeft->iTable = regData;
89730 pLeft->affinity = SQLITE_AFF_INTEGER;
89731 pRight->iTable = pSrc->a[0].iCursor;
89732 pRight->iColumn = -1;
89734 pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
89735 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89738 /* Resolve the references in the WHERE clause. */
89739 memset(&sNameContext, 0, sizeof(NameContext));
89740 sNameContext.pSrcList = pSrc;
89741 sNameContext.pParse = pParse;
89742 sqlite3ResolveExprNames(&sNameContext, pWhere);
89744 /* Create VDBE to loop through the entries in pSrc that match the WHERE
89745 ** clause. If the constraint is not deferred, throw an exception for
89746 ** each row found. Otherwise, for deferred constraints, increment the
89747 ** deferred constraint counter by nIncr for each row selected. */
89748 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
89749 if( nIncr>0 && pFKey->isDeferred==0 ){
89750 sqlite3ParseToplevel(pParse)->mayAbort = 1;
89752 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
89753 if( pWInfo ){
89754 sqlite3WhereEnd(pWInfo);
89757 /* Clean up the WHERE clause constructed above. */
89758 sqlite3ExprDelete(db, pWhere);
89759 if( iFkIfZero ){
89760 sqlite3VdbeJumpHere(v, iFkIfZero);
89765 ** This function returns a pointer to the head of a linked list of FK
89766 ** constraints for which table pTab is the parent table. For example,
89767 ** given the following schema:
89769 ** CREATE TABLE t1(a PRIMARY KEY);
89770 ** CREATE TABLE t2(b REFERENCES t1(a);
89772 ** Calling this function with table "t1" as an argument returns a pointer
89773 ** to the FKey structure representing the foreign key constraint on table
89774 ** "t2". Calling this function with "t2" as the argument would return a
89775 ** NULL pointer (as there are no FK constraints for which t2 is the parent
89776 ** table).
89778 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
89779 int nName = sqlite3Strlen30(pTab->zName);
89780 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
89784 ** The second argument is a Trigger structure allocated by the
89785 ** fkActionTrigger() routine. This function deletes the Trigger structure
89786 ** and all of its sub-components.
89788 ** The Trigger structure or any of its sub-components may be allocated from
89789 ** the lookaside buffer belonging to database handle dbMem.
89791 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
89792 if( p ){
89793 TriggerStep *pStep = p->step_list;
89794 sqlite3ExprDelete(dbMem, pStep->pWhere);
89795 sqlite3ExprListDelete(dbMem, pStep->pExprList);
89796 sqlite3SelectDelete(dbMem, pStep->pSelect);
89797 sqlite3ExprDelete(dbMem, p->pWhen);
89798 sqlite3DbFree(dbMem, p);
89803 ** This function is called to generate code that runs when table pTab is
89804 ** being dropped from the database. The SrcList passed as the second argument
89805 ** to this function contains a single entry guaranteed to resolve to
89806 ** table pTab.
89808 ** Normally, no code is required. However, if either
89810 ** (a) The table is the parent table of a FK constraint, or
89811 ** (b) The table is the child table of a deferred FK constraint and it is
89812 ** determined at runtime that there are outstanding deferred FK
89813 ** constraint violations in the database,
89815 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
89816 ** the table from the database. Triggers are disabled while running this
89817 ** DELETE, but foreign key actions are not.
89819 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
89820 sqlite3 *db = pParse->db;
89821 if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
89822 int iSkip = 0;
89823 Vdbe *v = sqlite3GetVdbe(pParse);
89825 assert( v ); /* VDBE has already been allocated */
89826 if( sqlite3FkReferences(pTab)==0 ){
89827 /* Search for a deferred foreign key constraint for which this table
89828 ** is the child table. If one cannot be found, return without
89829 ** generating any VDBE code. If one can be found, then jump over
89830 ** the entire DELETE if there are no outstanding deferred constraints
89831 ** when this statement is run. */
89832 FKey *p;
89833 for(p=pTab->pFKey; p; p=p->pNextFrom){
89834 if( p->isDeferred ) break;
89836 if( !p ) return;
89837 iSkip = sqlite3VdbeMakeLabel(v);
89838 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
89841 pParse->disableTriggers = 1;
89842 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
89843 pParse->disableTriggers = 0;
89845 /* If the DELETE has generated immediate foreign key constraint
89846 ** violations, halt the VDBE and return an error at this point, before
89847 ** any modifications to the schema are made. This is because statement
89848 ** transactions are not able to rollback schema changes. */
89849 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
89850 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
89851 OE_Abort, "foreign key constraint failed", P4_STATIC
89854 if( iSkip ){
89855 sqlite3VdbeResolveLabel(v, iSkip);
89861 ** This function is called when inserting, deleting or updating a row of
89862 ** table pTab to generate VDBE code to perform foreign key constraint
89863 ** processing for the operation.
89865 ** For a DELETE operation, parameter regOld is passed the index of the
89866 ** first register in an array of (pTab->nCol+1) registers containing the
89867 ** rowid of the row being deleted, followed by each of the column values
89868 ** of the row being deleted, from left to right. Parameter regNew is passed
89869 ** zero in this case.
89871 ** For an INSERT operation, regOld is passed zero and regNew is passed the
89872 ** first register of an array of (pTab->nCol+1) registers containing the new
89873 ** row data.
89875 ** For an UPDATE operation, this function is called twice. Once before
89876 ** the original record is deleted from the table using the calling convention
89877 ** described for DELETE. Then again after the original record is deleted
89878 ** but before the new record is inserted using the INSERT convention.
89880 SQLITE_PRIVATE void sqlite3FkCheck(
89881 Parse *pParse, /* Parse context */
89882 Table *pTab, /* Row is being deleted from this table */
89883 int regOld, /* Previous row data is stored here */
89884 int regNew /* New row data is stored here */
89886 sqlite3 *db = pParse->db; /* Database handle */
89887 FKey *pFKey; /* Used to iterate through FKs */
89888 int iDb; /* Index of database containing pTab */
89889 const char *zDb; /* Name of database containing pTab */
89890 int isIgnoreErrors = pParse->disableTriggers;
89892 /* Exactly one of regOld and regNew should be non-zero. */
89893 assert( (regOld==0)!=(regNew==0) );
89895 /* If foreign-keys are disabled, this function is a no-op. */
89896 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
89898 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89899 zDb = db->aDb[iDb].zName;
89901 /* Loop through all the foreign key constraints for which pTab is the
89902 ** child table (the table that the foreign key definition is part of). */
89903 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
89904 Table *pTo; /* Parent table of foreign key pFKey */
89905 Index *pIdx = 0; /* Index on key columns in pTo */
89906 int *aiFree = 0;
89907 int *aiCol;
89908 int iCol;
89909 int i;
89910 int isIgnore = 0;
89912 /* Find the parent table of this foreign key. Also find a unique index
89913 ** on the parent key columns in the parent table. If either of these
89914 ** schema items cannot be located, set an error in pParse and return
89915 ** early. */
89916 if( pParse->disableTriggers ){
89917 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
89918 }else{
89919 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
89921 if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
89922 assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
89923 if( !isIgnoreErrors || db->mallocFailed ) return;
89924 if( pTo==0 ){
89925 /* If isIgnoreErrors is true, then a table is being dropped. In this
89926 ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
89927 ** before actually dropping it in order to check FK constraints.
89928 ** If the parent table of an FK constraint on the current table is
89929 ** missing, behave as if it is empty. i.e. decrement the relevant
89930 ** FK counter for each row of the current table with non-NULL keys.
89932 Vdbe *v = sqlite3GetVdbe(pParse);
89933 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
89934 for(i=0; i<pFKey->nCol; i++){
89935 int iReg = pFKey->aCol[i].iFrom + regOld + 1;
89936 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
89938 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
89940 continue;
89942 assert( pFKey->nCol==1 || (aiFree && pIdx) );
89944 if( aiFree ){
89945 aiCol = aiFree;
89946 }else{
89947 iCol = pFKey->aCol[0].iFrom;
89948 aiCol = &iCol;
89950 for(i=0; i<pFKey->nCol; i++){
89951 if( aiCol[i]==pTab->iPKey ){
89952 aiCol[i] = -1;
89954 #ifndef SQLITE_OMIT_AUTHORIZATION
89955 /* Request permission to read the parent key columns. If the
89956 ** authorization callback returns SQLITE_IGNORE, behave as if any
89957 ** values read from the parent table are NULL. */
89958 if( db->xAuth ){
89959 int rcauth;
89960 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
89961 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
89962 isIgnore = (rcauth==SQLITE_IGNORE);
89964 #endif
89967 /* Take a shared-cache advisory read-lock on the parent table. Allocate
89968 ** a cursor to use to search the unique index on the parent key columns
89969 ** in the parent table. */
89970 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
89971 pParse->nTab++;
89973 if( regOld!=0 ){
89974 /* A row is being removed from the child table. Search for the parent.
89975 ** If the parent does not exist, removing the child row resolves an
89976 ** outstanding foreign key constraint violation. */
89977 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
89979 if( regNew!=0 ){
89980 /* A row is being added to the child table. If a parent row cannot
89981 ** be found, adding the child row has violated the FK constraint. */
89982 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
89985 sqlite3DbFree(db, aiFree);
89988 /* Loop through all the foreign key constraints that refer to this table */
89989 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
89990 Index *pIdx = 0; /* Foreign key index for pFKey */
89991 SrcList *pSrc;
89992 int *aiCol = 0;
89994 if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
89995 && !pParse->pToplevel && !pParse->isMultiWrite
89997 assert( regOld==0 && regNew!=0 );
89998 /* Inserting a single row into a parent table cannot cause an immediate
89999 ** foreign key violation. So do nothing in this case. */
90000 continue;
90003 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
90004 if( !isIgnoreErrors || db->mallocFailed ) return;
90005 continue;
90007 assert( aiCol || pFKey->nCol==1 );
90009 /* Create a SrcList structure containing a single table (the table
90010 ** the foreign key that refers to this table is attached to). This
90011 ** is required for the sqlite3WhereXXX() interface. */
90012 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
90013 if( pSrc ){
90014 struct SrcList_item *pItem = pSrc->a;
90015 pItem->pTab = pFKey->pFrom;
90016 pItem->zName = pFKey->pFrom->zName;
90017 pItem->pTab->nRef++;
90018 pItem->iCursor = pParse->nTab++;
90020 if( regNew!=0 ){
90021 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
90023 if( regOld!=0 ){
90024 /* If there is a RESTRICT action configured for the current operation
90025 ** on the parent table of this FK, then throw an exception
90026 ** immediately if the FK constraint is violated, even if this is a
90027 ** deferred trigger. That's what RESTRICT means. To defer checking
90028 ** the constraint, the FK should specify NO ACTION (represented
90029 ** using OE_None). NO ACTION is the default. */
90030 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
90032 pItem->zName = 0;
90033 sqlite3SrcListDelete(db, pSrc);
90035 sqlite3DbFree(db, aiCol);
90039 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
90042 ** This function is called before generating code to update or delete a
90043 ** row contained in table pTab.
90045 SQLITE_PRIVATE u32 sqlite3FkOldmask(
90046 Parse *pParse, /* Parse context */
90047 Table *pTab /* Table being modified */
90049 u32 mask = 0;
90050 if( pParse->db->flags&SQLITE_ForeignKeys ){
90051 FKey *p;
90052 int i;
90053 for(p=pTab->pFKey; p; p=p->pNextFrom){
90054 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
90056 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
90057 Index *pIdx = 0;
90058 sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
90059 if( pIdx ){
90060 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
90064 return mask;
90068 ** This function is called before generating code to update or delete a
90069 ** row contained in table pTab. If the operation is a DELETE, then
90070 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
90071 ** to an array of size N, where N is the number of columns in table pTab.
90072 ** If the i'th column is not modified by the UPDATE, then the corresponding
90073 ** entry in the aChange[] array is set to -1. If the column is modified,
90074 ** the value is 0 or greater. Parameter chngRowid is set to true if the
90075 ** UPDATE statement modifies the rowid fields of the table.
90077 ** If any foreign key processing will be required, this function returns
90078 ** true. If there is no foreign key related processing, this function
90079 ** returns false.
90081 SQLITE_PRIVATE int sqlite3FkRequired(
90082 Parse *pParse, /* Parse context */
90083 Table *pTab, /* Table being modified */
90084 int *aChange, /* Non-NULL for UPDATE operations */
90085 int chngRowid /* True for UPDATE that affects rowid */
90087 if( pParse->db->flags&SQLITE_ForeignKeys ){
90088 if( !aChange ){
90089 /* A DELETE operation. Foreign key processing is required if the
90090 ** table in question is either the child or parent table for any
90091 ** foreign key constraint. */
90092 return (sqlite3FkReferences(pTab) || pTab->pFKey);
90093 }else{
90094 /* This is an UPDATE. Foreign key processing is only required if the
90095 ** operation modifies one or more child or parent key columns. */
90096 int i;
90097 FKey *p;
90099 /* Check if any child key columns are being modified. */
90100 for(p=pTab->pFKey; p; p=p->pNextFrom){
90101 for(i=0; i<p->nCol; i++){
90102 int iChildKey = p->aCol[i].iFrom;
90103 if( aChange[iChildKey]>=0 ) return 1;
90104 if( iChildKey==pTab->iPKey && chngRowid ) return 1;
90108 /* Check if any parent key columns are being modified. */
90109 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
90110 for(i=0; i<p->nCol; i++){
90111 char *zKey = p->aCol[i].zCol;
90112 int iKey;
90113 for(iKey=0; iKey<pTab->nCol; iKey++){
90114 Column *pCol = &pTab->aCol[iKey];
90115 if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey)
90116 : (pCol->colFlags & COLFLAG_PRIMKEY)!=0) ){
90117 if( aChange[iKey]>=0 ) return 1;
90118 if( iKey==pTab->iPKey && chngRowid ) return 1;
90125 return 0;
90129 ** This function is called when an UPDATE or DELETE operation is being
90130 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
90131 ** If the current operation is an UPDATE, then the pChanges parameter is
90132 ** passed a pointer to the list of columns being modified. If it is a
90133 ** DELETE, pChanges is passed a NULL pointer.
90135 ** It returns a pointer to a Trigger structure containing a trigger
90136 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
90137 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
90138 ** returned (these actions require no special handling by the triggers
90139 ** sub-system, code for them is created by fkScanChildren()).
90141 ** For example, if pFKey is the foreign key and pTab is table "p" in
90142 ** the following schema:
90144 ** CREATE TABLE p(pk PRIMARY KEY);
90145 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
90147 ** then the returned trigger structure is equivalent to:
90149 ** CREATE TRIGGER ... DELETE ON p BEGIN
90150 ** DELETE FROM c WHERE ck = old.pk;
90151 ** END;
90153 ** The returned pointer is cached as part of the foreign key object. It
90154 ** is eventually freed along with the rest of the foreign key object by
90155 ** sqlite3FkDelete().
90157 static Trigger *fkActionTrigger(
90158 Parse *pParse, /* Parse context */
90159 Table *pTab, /* Table being updated or deleted from */
90160 FKey *pFKey, /* Foreign key to get action for */
90161 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
90163 sqlite3 *db = pParse->db; /* Database handle */
90164 int action; /* One of OE_None, OE_Cascade etc. */
90165 Trigger *pTrigger; /* Trigger definition to return */
90166 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
90168 action = pFKey->aAction[iAction];
90169 pTrigger = pFKey->apTrigger[iAction];
90171 if( action!=OE_None && !pTrigger ){
90172 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
90173 char const *zFrom; /* Name of child table */
90174 int nFrom; /* Length in bytes of zFrom */
90175 Index *pIdx = 0; /* Parent key index for this FK */
90176 int *aiCol = 0; /* child table cols -> parent key cols */
90177 TriggerStep *pStep = 0; /* First (only) step of trigger program */
90178 Expr *pWhere = 0; /* WHERE clause of trigger step */
90179 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
90180 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
90181 int i; /* Iterator variable */
90182 Expr *pWhen = 0; /* WHEN clause for the trigger */
90184 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
90185 assert( aiCol || pFKey->nCol==1 );
90187 for(i=0; i<pFKey->nCol; i++){
90188 Token tOld = { "old", 3 }; /* Literal "old" token */
90189 Token tNew = { "new", 3 }; /* Literal "new" token */
90190 Token tFromCol; /* Name of column in child table */
90191 Token tToCol; /* Name of column in parent table */
90192 int iFromCol; /* Idx of column in child table */
90193 Expr *pEq; /* tFromCol = OLD.tToCol */
90195 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
90196 assert( iFromCol>=0 );
90197 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
90198 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
90200 tToCol.n = sqlite3Strlen30(tToCol.z);
90201 tFromCol.n = sqlite3Strlen30(tFromCol.z);
90203 /* Create the expression "OLD.zToCol = zFromCol". It is important
90204 ** that the "OLD.zToCol" term is on the LHS of the = operator, so
90205 ** that the affinity and collation sequence associated with the
90206 ** parent table are used for the comparison. */
90207 pEq = sqlite3PExpr(pParse, TK_EQ,
90208 sqlite3PExpr(pParse, TK_DOT,
90209 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
90210 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
90211 , 0),
90212 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
90213 , 0);
90214 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
90216 /* For ON UPDATE, construct the next term of the WHEN clause.
90217 ** The final WHEN clause will be like this:
90219 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
90221 if( pChanges ){
90222 pEq = sqlite3PExpr(pParse, TK_IS,
90223 sqlite3PExpr(pParse, TK_DOT,
90224 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
90225 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
90227 sqlite3PExpr(pParse, TK_DOT,
90228 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
90229 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
90232 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
90235 if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
90236 Expr *pNew;
90237 if( action==OE_Cascade ){
90238 pNew = sqlite3PExpr(pParse, TK_DOT,
90239 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
90240 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
90241 , 0);
90242 }else if( action==OE_SetDflt ){
90243 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
90244 if( pDflt ){
90245 pNew = sqlite3ExprDup(db, pDflt, 0);
90246 }else{
90247 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
90249 }else{
90250 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
90252 pList = sqlite3ExprListAppend(pParse, pList, pNew);
90253 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
90256 sqlite3DbFree(db, aiCol);
90258 zFrom = pFKey->pFrom->zName;
90259 nFrom = sqlite3Strlen30(zFrom);
90261 if( action==OE_Restrict ){
90262 Token tFrom;
90263 Expr *pRaise;
90265 tFrom.z = zFrom;
90266 tFrom.n = nFrom;
90267 pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
90268 if( pRaise ){
90269 pRaise->affinity = OE_Abort;
90271 pSelect = sqlite3SelectNew(pParse,
90272 sqlite3ExprListAppend(pParse, 0, pRaise),
90273 sqlite3SrcListAppend(db, 0, &tFrom, 0),
90274 pWhere,
90275 0, 0, 0, 0, 0, 0
90277 pWhere = 0;
90280 /* Disable lookaside memory allocation */
90281 enableLookaside = db->lookaside.bEnabled;
90282 db->lookaside.bEnabled = 0;
90284 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
90285 sizeof(Trigger) + /* struct Trigger */
90286 sizeof(TriggerStep) + /* Single step in trigger program */
90287 nFrom + 1 /* Space for pStep->target.z */
90289 if( pTrigger ){
90290 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
90291 pStep->target.z = (char *)&pStep[1];
90292 pStep->target.n = nFrom;
90293 memcpy((char *)pStep->target.z, zFrom, nFrom);
90295 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
90296 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
90297 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
90298 if( pWhen ){
90299 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
90300 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
90304 /* Re-enable the lookaside buffer, if it was disabled earlier. */
90305 db->lookaside.bEnabled = enableLookaside;
90307 sqlite3ExprDelete(db, pWhere);
90308 sqlite3ExprDelete(db, pWhen);
90309 sqlite3ExprListDelete(db, pList);
90310 sqlite3SelectDelete(db, pSelect);
90311 if( db->mallocFailed==1 ){
90312 fkTriggerDelete(db, pTrigger);
90313 return 0;
90315 assert( pStep!=0 );
90317 switch( action ){
90318 case OE_Restrict:
90319 pStep->op = TK_SELECT;
90320 break;
90321 case OE_Cascade:
90322 if( !pChanges ){
90323 pStep->op = TK_DELETE;
90324 break;
90326 default:
90327 pStep->op = TK_UPDATE;
90329 pStep->pTrig = pTrigger;
90330 pTrigger->pSchema = pTab->pSchema;
90331 pTrigger->pTabSchema = pTab->pSchema;
90332 pFKey->apTrigger[iAction] = pTrigger;
90333 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
90336 return pTrigger;
90340 ** This function is called when deleting or updating a row to implement
90341 ** any required CASCADE, SET NULL or SET DEFAULT actions.
90343 SQLITE_PRIVATE void sqlite3FkActions(
90344 Parse *pParse, /* Parse context */
90345 Table *pTab, /* Table being updated or deleted from */
90346 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
90347 int regOld /* Address of array containing old row */
90349 /* If foreign-key support is enabled, iterate through all FKs that
90350 ** refer to table pTab. If there is an action associated with the FK
90351 ** for this operation (either update or delete), invoke the associated
90352 ** trigger sub-program. */
90353 if( pParse->db->flags&SQLITE_ForeignKeys ){
90354 FKey *pFKey; /* Iterator variable */
90355 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
90356 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
90357 if( pAction ){
90358 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
90364 #endif /* ifndef SQLITE_OMIT_TRIGGER */
90367 ** Free all memory associated with foreign key definitions attached to
90368 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
90369 ** hash table.
90371 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
90372 FKey *pFKey; /* Iterator variable */
90373 FKey *pNext; /* Copy of pFKey->pNextFrom */
90375 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
90376 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
90378 /* Remove the FK from the fkeyHash hash table. */
90379 if( !db || db->pnBytesFreed==0 ){
90380 if( pFKey->pPrevTo ){
90381 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
90382 }else{
90383 void *p = (void *)pFKey->pNextTo;
90384 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
90385 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
90387 if( pFKey->pNextTo ){
90388 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
90392 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
90393 ** classified as either immediate or deferred.
90395 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
90397 /* Delete any triggers created to implement actions for this FK. */
90398 #ifndef SQLITE_OMIT_TRIGGER
90399 fkTriggerDelete(db, pFKey->apTrigger[0]);
90400 fkTriggerDelete(db, pFKey->apTrigger[1]);
90401 #endif
90403 pNext = pFKey->pNextFrom;
90404 sqlite3DbFree(db, pFKey);
90407 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
90409 /************** End of fkey.c ************************************************/
90410 /************** Begin file insert.c ******************************************/
90412 ** 2001 September 15
90414 ** The author disclaims copyright to this source code. In place of
90415 ** a legal notice, here is a blessing:
90417 ** May you do good and not evil.
90418 ** May you find forgiveness for yourself and forgive others.
90419 ** May you share freely, never taking more than you give.
90421 *************************************************************************
90422 ** This file contains C code routines that are called by the parser
90423 ** to handle INSERT statements in SQLite.
90427 ** Generate code that will open a table for reading.
90429 SQLITE_PRIVATE void sqlite3OpenTable(
90430 Parse *p, /* Generate code into this VDBE */
90431 int iCur, /* The cursor number of the table */
90432 int iDb, /* The database index in sqlite3.aDb[] */
90433 Table *pTab, /* The table to be opened */
90434 int opcode /* OP_OpenRead or OP_OpenWrite */
90436 Vdbe *v;
90437 assert( !IsVirtual(pTab) );
90438 v = sqlite3GetVdbe(p);
90439 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
90440 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
90441 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
90442 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
90443 VdbeComment((v, "%s", pTab->zName));
90447 ** Return a pointer to the column affinity string associated with index
90448 ** pIdx. A column affinity string has one character for each column in
90449 ** the table, according to the affinity of the column:
90451 ** Character Column affinity
90452 ** ------------------------------
90453 ** 'a' TEXT
90454 ** 'b' NONE
90455 ** 'c' NUMERIC
90456 ** 'd' INTEGER
90457 ** 'e' REAL
90459 ** An extra 'd' is appended to the end of the string to cover the
90460 ** rowid that appears as the last column in every index.
90462 ** Memory for the buffer containing the column index affinity string
90463 ** is managed along with the rest of the Index structure. It will be
90464 ** released when sqlite3DeleteIndex() is called.
90466 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
90467 if( !pIdx->zColAff ){
90468 /* The first time a column affinity string for a particular index is
90469 ** required, it is allocated and populated here. It is then stored as
90470 ** a member of the Index structure for subsequent use.
90472 ** The column affinity string will eventually be deleted by
90473 ** sqliteDeleteIndex() when the Index structure itself is cleaned
90474 ** up.
90476 int n;
90477 Table *pTab = pIdx->pTable;
90478 sqlite3 *db = sqlite3VdbeDb(v);
90479 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
90480 if( !pIdx->zColAff ){
90481 db->mallocFailed = 1;
90482 return 0;
90484 for(n=0; n<pIdx->nColumn; n++){
90485 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
90487 pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
90488 pIdx->zColAff[n] = 0;
90491 return pIdx->zColAff;
90495 ** Set P4 of the most recently inserted opcode to a column affinity
90496 ** string for table pTab. A column affinity string has one character
90497 ** for each column indexed by the index, according to the affinity of the
90498 ** column:
90500 ** Character Column affinity
90501 ** ------------------------------
90502 ** 'a' TEXT
90503 ** 'b' NONE
90504 ** 'c' NUMERIC
90505 ** 'd' INTEGER
90506 ** 'e' REAL
90508 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
90509 /* The first time a column affinity string for a particular table
90510 ** is required, it is allocated and populated here. It is then
90511 ** stored as a member of the Table structure for subsequent use.
90513 ** The column affinity string will eventually be deleted by
90514 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
90516 if( !pTab->zColAff ){
90517 char *zColAff;
90518 int i;
90519 sqlite3 *db = sqlite3VdbeDb(v);
90521 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
90522 if( !zColAff ){
90523 db->mallocFailed = 1;
90524 return;
90527 for(i=0; i<pTab->nCol; i++){
90528 zColAff[i] = pTab->aCol[i].affinity;
90530 zColAff[pTab->nCol] = '\0';
90532 pTab->zColAff = zColAff;
90535 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
90539 ** Return non-zero if the table pTab in database iDb or any of its indices
90540 ** have been opened at any point in the VDBE program beginning at location
90541 ** iStartAddr throught the end of the program. This is used to see if
90542 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
90543 ** run without using temporary table for the results of the SELECT.
90545 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
90546 Vdbe *v = sqlite3GetVdbe(p);
90547 int i;
90548 int iEnd = sqlite3VdbeCurrentAddr(v);
90549 #ifndef SQLITE_OMIT_VIRTUALTABLE
90550 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
90551 #endif
90553 for(i=iStartAddr; i<iEnd; i++){
90554 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
90555 assert( pOp!=0 );
90556 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
90557 Index *pIndex;
90558 int tnum = pOp->p2;
90559 if( tnum==pTab->tnum ){
90560 return 1;
90562 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
90563 if( tnum==pIndex->tnum ){
90564 return 1;
90568 #ifndef SQLITE_OMIT_VIRTUALTABLE
90569 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
90570 assert( pOp->p4.pVtab!=0 );
90571 assert( pOp->p4type==P4_VTAB );
90572 return 1;
90574 #endif
90576 return 0;
90579 #ifndef SQLITE_OMIT_AUTOINCREMENT
90581 ** Locate or create an AutoincInfo structure associated with table pTab
90582 ** which is in database iDb. Return the register number for the register
90583 ** that holds the maximum rowid.
90585 ** There is at most one AutoincInfo structure per table even if the
90586 ** same table is autoincremented multiple times due to inserts within
90587 ** triggers. A new AutoincInfo structure is created if this is the
90588 ** first use of table pTab. On 2nd and subsequent uses, the original
90589 ** AutoincInfo structure is used.
90591 ** Three memory locations are allocated:
90593 ** (1) Register to hold the name of the pTab table.
90594 ** (2) Register to hold the maximum ROWID of pTab.
90595 ** (3) Register to hold the rowid in sqlite_sequence of pTab
90597 ** The 2nd register is the one that is returned. That is all the
90598 ** insert routine needs to know about.
90600 static int autoIncBegin(
90601 Parse *pParse, /* Parsing context */
90602 int iDb, /* Index of the database holding pTab */
90603 Table *pTab /* The table we are writing to */
90605 int memId = 0; /* Register holding maximum rowid */
90606 if( pTab->tabFlags & TF_Autoincrement ){
90607 Parse *pToplevel = sqlite3ParseToplevel(pParse);
90608 AutoincInfo *pInfo;
90610 pInfo = pToplevel->pAinc;
90611 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
90612 if( pInfo==0 ){
90613 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
90614 if( pInfo==0 ) return 0;
90615 pInfo->pNext = pToplevel->pAinc;
90616 pToplevel->pAinc = pInfo;
90617 pInfo->pTab = pTab;
90618 pInfo->iDb = iDb;
90619 pToplevel->nMem++; /* Register to hold name of table */
90620 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
90621 pToplevel->nMem++; /* Rowid in sqlite_sequence */
90623 memId = pInfo->regCtr;
90625 return memId;
90629 ** This routine generates code that will initialize all of the
90630 ** register used by the autoincrement tracker.
90632 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
90633 AutoincInfo *p; /* Information about an AUTOINCREMENT */
90634 sqlite3 *db = pParse->db; /* The database connection */
90635 Db *pDb; /* Database only autoinc table */
90636 int memId; /* Register holding max rowid */
90637 int addr; /* A VDBE address */
90638 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
90640 /* This routine is never called during trigger-generation. It is
90641 ** only called from the top-level */
90642 assert( pParse->pTriggerTab==0 );
90643 assert( pParse==sqlite3ParseToplevel(pParse) );
90645 assert( v ); /* We failed long ago if this is not so */
90646 for(p = pParse->pAinc; p; p = p->pNext){
90647 pDb = &db->aDb[p->iDb];
90648 memId = p->regCtr;
90649 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
90650 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
90651 sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
90652 addr = sqlite3VdbeCurrentAddr(v);
90653 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
90654 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
90655 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
90656 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
90657 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
90658 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
90659 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
90660 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
90661 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
90662 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
90663 sqlite3VdbeAddOp0(v, OP_Close);
90668 ** Update the maximum rowid for an autoincrement calculation.
90670 ** This routine should be called when the top of the stack holds a
90671 ** new rowid that is about to be inserted. If that new rowid is
90672 ** larger than the maximum rowid in the memId memory cell, then the
90673 ** memory cell is updated. The stack is unchanged.
90675 static void autoIncStep(Parse *pParse, int memId, int regRowid){
90676 if( memId>0 ){
90677 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
90682 ** This routine generates the code needed to write autoincrement
90683 ** maximum rowid values back into the sqlite_sequence register.
90684 ** Every statement that might do an INSERT into an autoincrement
90685 ** table (either directly or through triggers) needs to call this
90686 ** routine just before the "exit" code.
90688 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
90689 AutoincInfo *p;
90690 Vdbe *v = pParse->pVdbe;
90691 sqlite3 *db = pParse->db;
90693 assert( v );
90694 for(p = pParse->pAinc; p; p = p->pNext){
90695 Db *pDb = &db->aDb[p->iDb];
90696 int j1, j2, j3, j4, j5;
90697 int iRec;
90698 int memId = p->regCtr;
90700 iRec = sqlite3GetTempReg(pParse);
90701 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
90702 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
90703 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
90704 j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
90705 j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
90706 j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
90707 sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
90708 sqlite3VdbeJumpHere(v, j2);
90709 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
90710 j5 = sqlite3VdbeAddOp0(v, OP_Goto);
90711 sqlite3VdbeJumpHere(v, j4);
90712 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
90713 sqlite3VdbeJumpHere(v, j1);
90714 sqlite3VdbeJumpHere(v, j5);
90715 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
90716 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
90717 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90718 sqlite3VdbeAddOp0(v, OP_Close);
90719 sqlite3ReleaseTempReg(pParse, iRec);
90722 #else
90724 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
90725 ** above are all no-ops
90727 # define autoIncBegin(A,B,C) (0)
90728 # define autoIncStep(A,B,C)
90729 #endif /* SQLITE_OMIT_AUTOINCREMENT */
90733 ** Generate code for a co-routine that will evaluate a subquery one
90734 ** row at a time.
90736 ** The pSelect parameter is the subquery that the co-routine will evaluation.
90737 ** Information about the location of co-routine and the registers it will use
90738 ** is returned by filling in the pDest object.
90740 ** Registers are allocated as follows:
90742 ** pDest->iSDParm The register holding the next entry-point of the
90743 ** co-routine. Run the co-routine to its next breakpoint
90744 ** by calling "OP_Yield $X" where $X is pDest->iSDParm.
90746 ** pDest->iSDParm+1 The register holding the "completed" flag for the
90747 ** co-routine. This register is 0 if the previous Yield
90748 ** generated a new result row, or 1 if the subquery
90749 ** has completed. If the Yield is called again
90750 ** after this register becomes 1, then the VDBE will
90751 ** halt with an SQLITE_INTERNAL error.
90753 ** pDest->iSdst First result register.
90755 ** pDest->nSdst Number of result registers.
90757 ** This routine handles all of the register allocation and fills in the
90758 ** pDest structure appropriately.
90760 ** Here is a schematic of the generated code assuming that X is the
90761 ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
90762 ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
90763 ** registers that hold the result set, reg[pDest->iSdst] through
90764 ** reg[pDest->iSdst+pDest->nSdst-1]:
90766 ** X <- A
90767 ** EOF <- 0
90768 ** goto B
90769 ** A: setup for the SELECT
90770 ** loop rows in the SELECT
90771 ** load results into registers R..S
90772 ** yield X
90773 ** end loop
90774 ** cleanup after the SELECT
90775 ** EOF <- 1
90776 ** yield X
90777 ** halt-error
90778 ** B:
90780 ** To use this subroutine, the caller generates code as follows:
90782 ** [ Co-routine generated by this subroutine, shown above ]
90783 ** S: yield X
90784 ** if EOF goto E
90785 ** if skip this row, goto C
90786 ** if terminate loop, goto E
90787 ** deal with this row
90788 ** C: goto S
90789 ** E:
90791 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
90792 int regYield; /* Register holding co-routine entry-point */
90793 int regEof; /* Register holding co-routine completion flag */
90794 int addrTop; /* Top of the co-routine */
90795 int j1; /* Jump instruction */
90796 int rc; /* Result code */
90797 Vdbe *v; /* VDBE under construction */
90799 regYield = ++pParse->nMem;
90800 regEof = ++pParse->nMem;
90801 v = sqlite3GetVdbe(pParse);
90802 addrTop = sqlite3VdbeCurrentAddr(v);
90803 sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
90804 VdbeComment((v, "Co-routine entry point"));
90805 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
90806 VdbeComment((v, "Co-routine completion flag"));
90807 sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
90808 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
90809 rc = sqlite3Select(pParse, pSelect, pDest);
90810 assert( pParse->nErr==0 || rc );
90811 if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
90812 if( rc ) return rc;
90813 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
90814 sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */
90815 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
90816 VdbeComment((v, "End of coroutine"));
90817 sqlite3VdbeJumpHere(v, j1); /* label B: */
90818 return rc;
90823 /* Forward declaration */
90824 static int xferOptimization(
90825 Parse *pParse, /* Parser context */
90826 Table *pDest, /* The table we are inserting into */
90827 Select *pSelect, /* A SELECT statement to use as the data source */
90828 int onError, /* How to handle constraint errors */
90829 int iDbDest /* The database of pDest */
90833 ** This routine is call to handle SQL of the following forms:
90835 ** insert into TABLE (IDLIST) values(EXPRLIST)
90836 ** insert into TABLE (IDLIST) select
90838 ** The IDLIST following the table name is always optional. If omitted,
90839 ** then a list of all columns for the table is substituted. The IDLIST
90840 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
90842 ** The pList parameter holds EXPRLIST in the first form of the INSERT
90843 ** statement above, and pSelect is NULL. For the second form, pList is
90844 ** NULL and pSelect is a pointer to the select statement used to generate
90845 ** data for the insert.
90847 ** The code generated follows one of four templates. For a simple
90848 ** select with data coming from a VALUES clause, the code executes
90849 ** once straight down through. Pseudo-code follows (we call this
90850 ** the "1st template"):
90852 ** open write cursor to <table> and its indices
90853 ** puts VALUES clause expressions onto the stack
90854 ** write the resulting record into <table>
90855 ** cleanup
90857 ** The three remaining templates assume the statement is of the form
90859 ** INSERT INTO <table> SELECT ...
90861 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
90862 ** in other words if the SELECT pulls all columns from a single table
90863 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
90864 ** if <table2> and <table1> are distinct tables but have identical
90865 ** schemas, including all the same indices, then a special optimization
90866 ** is invoked that copies raw records from <table2> over to <table1>.
90867 ** See the xferOptimization() function for the implementation of this
90868 ** template. This is the 2nd template.
90870 ** open a write cursor to <table>
90871 ** open read cursor on <table2>
90872 ** transfer all records in <table2> over to <table>
90873 ** close cursors
90874 ** foreach index on <table>
90875 ** open a write cursor on the <table> index
90876 ** open a read cursor on the corresponding <table2> index
90877 ** transfer all records from the read to the write cursors
90878 ** close cursors
90879 ** end foreach
90881 ** The 3rd template is for when the second template does not apply
90882 ** and the SELECT clause does not read from <table> at any time.
90883 ** The generated code follows this template:
90885 ** EOF <- 0
90886 ** X <- A
90887 ** goto B
90888 ** A: setup for the SELECT
90889 ** loop over the rows in the SELECT
90890 ** load values into registers R..R+n
90891 ** yield X
90892 ** end loop
90893 ** cleanup after the SELECT
90894 ** EOF <- 1
90895 ** yield X
90896 ** goto A
90897 ** B: open write cursor to <table> and its indices
90898 ** C: yield X
90899 ** if EOF goto D
90900 ** insert the select result into <table> from R..R+n
90901 ** goto C
90902 ** D: cleanup
90904 ** The 4th template is used if the insert statement takes its
90905 ** values from a SELECT but the data is being inserted into a table
90906 ** that is also read as part of the SELECT. In the third form,
90907 ** we have to use a intermediate table to store the results of
90908 ** the select. The template is like this:
90910 ** EOF <- 0
90911 ** X <- A
90912 ** goto B
90913 ** A: setup for the SELECT
90914 ** loop over the tables in the SELECT
90915 ** load value into register R..R+n
90916 ** yield X
90917 ** end loop
90918 ** cleanup after the SELECT
90919 ** EOF <- 1
90920 ** yield X
90921 ** halt-error
90922 ** B: open temp table
90923 ** L: yield X
90924 ** if EOF goto M
90925 ** insert row from R..R+n into temp table
90926 ** goto L
90927 ** M: open write cursor to <table> and its indices
90928 ** rewind temp table
90929 ** C: loop over rows of intermediate table
90930 ** transfer values form intermediate table into <table>
90931 ** end loop
90932 ** D: cleanup
90934 SQLITE_PRIVATE void sqlite3Insert(
90935 Parse *pParse, /* Parser context */
90936 SrcList *pTabList, /* Name of table into which we are inserting */
90937 ExprList *pList, /* List of values to be inserted */
90938 Select *pSelect, /* A SELECT statement to use as the data source */
90939 IdList *pColumn, /* Column names corresponding to IDLIST. */
90940 int onError /* How to handle constraint errors */
90942 sqlite3 *db; /* The main database structure */
90943 Table *pTab; /* The table to insert into. aka TABLE */
90944 char *zTab; /* Name of the table into which we are inserting */
90945 const char *zDb; /* Name of the database holding this table */
90946 int i, j, idx; /* Loop counters */
90947 Vdbe *v; /* Generate code into this virtual machine */
90948 Index *pIdx; /* For looping over indices of the table */
90949 int nColumn; /* Number of columns in the data */
90950 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
90951 int baseCur = 0; /* VDBE Cursor number for pTab */
90952 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
90953 int endOfLoop; /* Label for the end of the insertion loop */
90954 int useTempTable = 0; /* Store SELECT results in intermediate table */
90955 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
90956 int addrInsTop = 0; /* Jump to label "D" */
90957 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
90958 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
90959 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
90960 int iDb; /* Index of database holding TABLE */
90961 Db *pDb; /* The database containing table being inserted into */
90962 int appendFlag = 0; /* True if the insert is likely to be an append */
90964 /* Register allocations */
90965 int regFromSelect = 0;/* Base register for data coming from SELECT */
90966 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
90967 int regRowCount = 0; /* Memory cell used for the row counter */
90968 int regIns; /* Block of regs holding rowid+data being inserted */
90969 int regRowid; /* registers holding insert rowid */
90970 int regData; /* register holding first column to insert */
90971 int regEof = 0; /* Register recording end of SELECT data */
90972 int *aRegIdx = 0; /* One register allocated to each index */
90974 #ifndef SQLITE_OMIT_TRIGGER
90975 int isView; /* True if attempting to insert into a view */
90976 Trigger *pTrigger; /* List of triggers on pTab, if required */
90977 int tmask; /* Mask of trigger times */
90978 #endif
90980 db = pParse->db;
90981 memset(&dest, 0, sizeof(dest));
90982 if( pParse->nErr || db->mallocFailed ){
90983 goto insert_cleanup;
90986 /* Locate the table into which we will be inserting new information.
90988 assert( pTabList->nSrc==1 );
90989 zTab = pTabList->a[0].zName;
90990 if( NEVER(zTab==0) ) goto insert_cleanup;
90991 pTab = sqlite3SrcListLookup(pParse, pTabList);
90992 if( pTab==0 ){
90993 goto insert_cleanup;
90995 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90996 assert( iDb<db->nDb );
90997 pDb = &db->aDb[iDb];
90998 zDb = pDb->zName;
90999 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
91000 goto insert_cleanup;
91003 /* Figure out if we have any triggers and if the table being
91004 ** inserted into is a view
91006 #ifndef SQLITE_OMIT_TRIGGER
91007 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
91008 isView = pTab->pSelect!=0;
91009 #else
91010 # define pTrigger 0
91011 # define tmask 0
91012 # define isView 0
91013 #endif
91014 #ifdef SQLITE_OMIT_VIEW
91015 # undef isView
91016 # define isView 0
91017 #endif
91018 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
91020 /* If pTab is really a view, make sure it has been initialized.
91021 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
91022 ** module table).
91024 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
91025 goto insert_cleanup;
91028 /* Ensure that:
91029 * (a) the table is not read-only,
91030 * (b) that if it is a view then ON INSERT triggers exist
91032 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
91033 goto insert_cleanup;
91036 /* Allocate a VDBE
91038 v = sqlite3GetVdbe(pParse);
91039 if( v==0 ) goto insert_cleanup;
91040 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
91041 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
91043 #ifndef SQLITE_OMIT_XFER_OPT
91044 /* If the statement is of the form
91046 ** INSERT INTO <table1> SELECT * FROM <table2>;
91048 ** Then special optimizations can be applied that make the transfer
91049 ** very fast and which reduce fragmentation of indices.
91051 ** This is the 2nd template.
91053 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
91054 assert( !pTrigger );
91055 assert( pList==0 );
91056 goto insert_end;
91058 #endif /* SQLITE_OMIT_XFER_OPT */
91060 /* If this is an AUTOINCREMENT table, look up the sequence number in the
91061 ** sqlite_sequence table and store it in memory cell regAutoinc.
91063 regAutoinc = autoIncBegin(pParse, iDb, pTab);
91065 /* Figure out how many columns of data are supplied. If the data
91066 ** is coming from a SELECT statement, then generate a co-routine that
91067 ** produces a single row of the SELECT on each invocation. The
91068 ** co-routine is the common header to the 3rd and 4th templates.
91070 if( pSelect ){
91071 /* Data is coming from a SELECT. Generate a co-routine to run that
91072 ** SELECT. */
91073 int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
91074 if( rc ) goto insert_cleanup;
91076 regEof = dest.iSDParm + 1;
91077 regFromSelect = dest.iSdst;
91078 assert( pSelect->pEList );
91079 nColumn = pSelect->pEList->nExpr;
91080 assert( dest.nSdst==nColumn );
91082 /* Set useTempTable to TRUE if the result of the SELECT statement
91083 ** should be written into a temporary table (template 4). Set to
91084 ** FALSE if each* row of the SELECT can be written directly into
91085 ** the destination table (template 3).
91087 ** A temp table must be used if the table being updated is also one
91088 ** of the tables being read by the SELECT statement. Also use a
91089 ** temp table in the case of row triggers.
91091 if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
91092 useTempTable = 1;
91095 if( useTempTable ){
91096 /* Invoke the coroutine to extract information from the SELECT
91097 ** and add it to a transient table srcTab. The code generated
91098 ** here is from the 4th template:
91100 ** B: open temp table
91101 ** L: yield X
91102 ** if EOF goto M
91103 ** insert row from R..R+n into temp table
91104 ** goto L
91105 ** M: ...
91107 int regRec; /* Register to hold packed record */
91108 int regTempRowid; /* Register to hold temp table ROWID */
91109 int addrTop; /* Label "L" */
91110 int addrIf; /* Address of jump to M */
91112 srcTab = pParse->nTab++;
91113 regRec = sqlite3GetTempReg(pParse);
91114 regTempRowid = sqlite3GetTempReg(pParse);
91115 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
91116 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
91117 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
91118 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
91119 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
91120 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
91121 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
91122 sqlite3VdbeJumpHere(v, addrIf);
91123 sqlite3ReleaseTempReg(pParse, regRec);
91124 sqlite3ReleaseTempReg(pParse, regTempRowid);
91126 }else{
91127 /* This is the case if the data for the INSERT is coming from a VALUES
91128 ** clause
91130 NameContext sNC;
91131 memset(&sNC, 0, sizeof(sNC));
91132 sNC.pParse = pParse;
91133 srcTab = -1;
91134 assert( useTempTable==0 );
91135 nColumn = pList ? pList->nExpr : 0;
91136 for(i=0; i<nColumn; i++){
91137 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
91138 goto insert_cleanup;
91143 /* Make sure the number of columns in the source data matches the number
91144 ** of columns to be inserted into the table.
91146 if( IsVirtual(pTab) ){
91147 for(i=0; i<pTab->nCol; i++){
91148 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
91151 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
91152 sqlite3ErrorMsg(pParse,
91153 "table %S has %d columns but %d values were supplied",
91154 pTabList, 0, pTab->nCol-nHidden, nColumn);
91155 goto insert_cleanup;
91157 if( pColumn!=0 && nColumn!=pColumn->nId ){
91158 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
91159 goto insert_cleanup;
91162 /* If the INSERT statement included an IDLIST term, then make sure
91163 ** all elements of the IDLIST really are columns of the table and
91164 ** remember the column indices.
91166 ** If the table has an INTEGER PRIMARY KEY column and that column
91167 ** is named in the IDLIST, then record in the keyColumn variable
91168 ** the index into IDLIST of the primary key column. keyColumn is
91169 ** the index of the primary key as it appears in IDLIST, not as
91170 ** is appears in the original table. (The index of the primary
91171 ** key in the original table is pTab->iPKey.)
91173 if( pColumn ){
91174 for(i=0; i<pColumn->nId; i++){
91175 pColumn->a[i].idx = -1;
91177 for(i=0; i<pColumn->nId; i++){
91178 for(j=0; j<pTab->nCol; j++){
91179 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
91180 pColumn->a[i].idx = j;
91181 if( j==pTab->iPKey ){
91182 keyColumn = i;
91184 break;
91187 if( j>=pTab->nCol ){
91188 if( sqlite3IsRowid(pColumn->a[i].zName) ){
91189 keyColumn = i;
91190 }else{
91191 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
91192 pTabList, 0, pColumn->a[i].zName);
91193 pParse->checkSchema = 1;
91194 goto insert_cleanup;
91200 /* If there is no IDLIST term but the table has an integer primary
91201 ** key, the set the keyColumn variable to the primary key column index
91202 ** in the original table definition.
91204 if( pColumn==0 && nColumn>0 ){
91205 keyColumn = pTab->iPKey;
91208 /* Initialize the count of rows to be inserted
91210 if( db->flags & SQLITE_CountRows ){
91211 regRowCount = ++pParse->nMem;
91212 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
91215 /* If this is not a view, open the table and and all indices */
91216 if( !isView ){
91217 int nIdx;
91219 baseCur = pParse->nTab;
91220 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
91221 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
91222 if( aRegIdx==0 ){
91223 goto insert_cleanup;
91225 for(i=0; i<nIdx; i++){
91226 aRegIdx[i] = ++pParse->nMem;
91230 /* This is the top of the main insertion loop */
91231 if( useTempTable ){
91232 /* This block codes the top of loop only. The complete loop is the
91233 ** following pseudocode (template 4):
91235 ** rewind temp table
91236 ** C: loop over rows of intermediate table
91237 ** transfer values form intermediate table into <table>
91238 ** end loop
91239 ** D: ...
91241 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
91242 addrCont = sqlite3VdbeCurrentAddr(v);
91243 }else if( pSelect ){
91244 /* This block codes the top of loop only. The complete loop is the
91245 ** following pseudocode (template 3):
91247 ** C: yield X
91248 ** if EOF goto D
91249 ** insert the select result into <table> from R..R+n
91250 ** goto C
91251 ** D: ...
91253 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
91254 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
91257 /* Allocate registers for holding the rowid of the new row,
91258 ** the content of the new row, and the assemblied row record.
91260 regRowid = regIns = pParse->nMem+1;
91261 pParse->nMem += pTab->nCol + 1;
91262 if( IsVirtual(pTab) ){
91263 regRowid++;
91264 pParse->nMem++;
91266 regData = regRowid+1;
91268 /* Run the BEFORE and INSTEAD OF triggers, if there are any
91270 endOfLoop = sqlite3VdbeMakeLabel(v);
91271 if( tmask & TRIGGER_BEFORE ){
91272 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
91274 /* build the NEW.* reference row. Note that if there is an INTEGER
91275 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
91276 ** translated into a unique ID for the row. But on a BEFORE trigger,
91277 ** we do not know what the unique ID will be (because the insert has
91278 ** not happened yet) so we substitute a rowid of -1
91280 if( keyColumn<0 ){
91281 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
91282 }else{
91283 int j1;
91284 if( useTempTable ){
91285 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
91286 }else{
91287 assert( pSelect==0 ); /* Otherwise useTempTable is true */
91288 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
91290 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
91291 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
91292 sqlite3VdbeJumpHere(v, j1);
91293 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
91296 /* Cannot have triggers on a virtual table. If it were possible,
91297 ** this block would have to account for hidden column.
91299 assert( !IsVirtual(pTab) );
91301 /* Create the new column data
91303 for(i=0; i<pTab->nCol; i++){
91304 if( pColumn==0 ){
91305 j = i;
91306 }else{
91307 for(j=0; j<pColumn->nId; j++){
91308 if( pColumn->a[j].idx==i ) break;
91311 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
91312 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
91313 }else if( useTempTable ){
91314 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
91315 }else{
91316 assert( pSelect==0 ); /* Otherwise useTempTable is true */
91317 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
91321 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
91322 ** do not attempt any conversions before assembling the record.
91323 ** If this is a real table, attempt conversions as required by the
91324 ** table column affinities.
91326 if( !isView ){
91327 sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
91328 sqlite3TableAffinityStr(v, pTab);
91331 /* Fire BEFORE or INSTEAD OF triggers */
91332 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
91333 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
91335 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
91338 /* Push the record number for the new entry onto the stack. The
91339 ** record number is a randomly generate integer created by NewRowid
91340 ** except when the table has an INTEGER PRIMARY KEY column, in which
91341 ** case the record number is the same as that column.
91343 if( !isView ){
91344 if( IsVirtual(pTab) ){
91345 /* The row that the VUpdate opcode will delete: none */
91346 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
91348 if( keyColumn>=0 ){
91349 if( useTempTable ){
91350 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
91351 }else if( pSelect ){
91352 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
91353 }else{
91354 VdbeOp *pOp;
91355 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
91356 pOp = sqlite3VdbeGetOp(v, -1);
91357 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
91358 appendFlag = 1;
91359 pOp->opcode = OP_NewRowid;
91360 pOp->p1 = baseCur;
91361 pOp->p2 = regRowid;
91362 pOp->p3 = regAutoinc;
91365 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
91366 ** to generate a unique primary key value.
91368 if( !appendFlag ){
91369 int j1;
91370 if( !IsVirtual(pTab) ){
91371 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
91372 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
91373 sqlite3VdbeJumpHere(v, j1);
91374 }else{
91375 j1 = sqlite3VdbeCurrentAddr(v);
91376 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
91378 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
91380 }else if( IsVirtual(pTab) ){
91381 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
91382 }else{
91383 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
91384 appendFlag = 1;
91386 autoIncStep(pParse, regAutoinc, regRowid);
91388 /* Push onto the stack, data for all columns of the new entry, beginning
91389 ** with the first column.
91391 nHidden = 0;
91392 for(i=0; i<pTab->nCol; i++){
91393 int iRegStore = regRowid+1+i;
91394 if( i==pTab->iPKey ){
91395 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
91396 ** Whenever this column is read, the record number will be substituted
91397 ** in its place. So will fill this column with a NULL to avoid
91398 ** taking up data space with information that will never be used. */
91399 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
91400 continue;
91402 if( pColumn==0 ){
91403 if( IsHiddenColumn(&pTab->aCol[i]) ){
91404 assert( IsVirtual(pTab) );
91405 j = -1;
91406 nHidden++;
91407 }else{
91408 j = i - nHidden;
91410 }else{
91411 for(j=0; j<pColumn->nId; j++){
91412 if( pColumn->a[j].idx==i ) break;
91415 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
91416 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
91417 }else if( useTempTable ){
91418 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
91419 }else if( pSelect ){
91420 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
91421 }else{
91422 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
91426 /* Generate code to check constraints and generate index keys and
91427 ** do the insertion.
91429 #ifndef SQLITE_OMIT_VIRTUALTABLE
91430 if( IsVirtual(pTab) ){
91431 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
91432 sqlite3VtabMakeWritable(pParse, pTab);
91433 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
91434 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
91435 sqlite3MayAbort(pParse);
91436 }else
91437 #endif
91439 int isReplace; /* Set to true if constraints may cause a replace */
91440 sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
91441 keyColumn>=0, 0, onError, endOfLoop, &isReplace
91443 sqlite3FkCheck(pParse, pTab, 0, regIns);
91444 sqlite3CompleteInsertion(
91445 pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
91450 /* Update the count of rows that are inserted
91452 if( (db->flags & SQLITE_CountRows)!=0 ){
91453 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
91456 if( pTrigger ){
91457 /* Code AFTER triggers */
91458 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
91459 pTab, regData-2-pTab->nCol, onError, endOfLoop);
91462 /* The bottom of the main insertion loop, if the data source
91463 ** is a SELECT statement.
91465 sqlite3VdbeResolveLabel(v, endOfLoop);
91466 if( useTempTable ){
91467 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
91468 sqlite3VdbeJumpHere(v, addrInsTop);
91469 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
91470 }else if( pSelect ){
91471 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
91472 sqlite3VdbeJumpHere(v, addrInsTop);
91475 if( !IsVirtual(pTab) && !isView ){
91476 /* Close all tables opened */
91477 sqlite3VdbeAddOp1(v, OP_Close, baseCur);
91478 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
91479 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
91483 insert_end:
91484 /* Update the sqlite_sequence table by storing the content of the
91485 ** maximum rowid counter values recorded while inserting into
91486 ** autoincrement tables.
91488 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
91489 sqlite3AutoincrementEnd(pParse);
91493 ** Return the number of rows inserted. If this routine is
91494 ** generating code because of a call to sqlite3NestedParse(), do not
91495 ** invoke the callback function.
91497 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
91498 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
91499 sqlite3VdbeSetNumCols(v, 1);
91500 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
91503 insert_cleanup:
91504 sqlite3SrcListDelete(db, pTabList);
91505 sqlite3ExprListDelete(db, pList);
91506 sqlite3SelectDelete(db, pSelect);
91507 sqlite3IdListDelete(db, pColumn);
91508 sqlite3DbFree(db, aRegIdx);
91511 /* Make sure "isView" and other macros defined above are undefined. Otherwise
91512 ** thely may interfere with compilation of other functions in this file
91513 ** (or in another file, if this file becomes part of the amalgamation). */
91514 #ifdef isView
91515 #undef isView
91516 #endif
91517 #ifdef pTrigger
91518 #undef pTrigger
91519 #endif
91520 #ifdef tmask
91521 #undef tmask
91522 #endif
91526 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
91528 ** The input is a range of consecutive registers as follows:
91530 ** 1. The rowid of the row after the update.
91532 ** 2. The data in the first column of the entry after the update.
91534 ** i. Data from middle columns...
91536 ** N. The data in the last column of the entry after the update.
91538 ** The regRowid parameter is the index of the register containing (1).
91540 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
91541 ** the address of a register containing the rowid before the update takes
91542 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
91543 ** is false, indicating an INSERT statement, then a non-zero rowidChng
91544 ** indicates that the rowid was explicitly specified as part of the
91545 ** INSERT statement. If rowidChng is false, it means that the rowid is
91546 ** computed automatically in an insert or that the rowid value is not
91547 ** modified by an update.
91549 ** The code generated by this routine store new index entries into
91550 ** registers identified by aRegIdx[]. No index entry is created for
91551 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
91552 ** the same as the order of indices on the linked list of indices
91553 ** attached to the table.
91555 ** This routine also generates code to check constraints. NOT NULL,
91556 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
91557 ** then the appropriate action is performed. There are five possible
91558 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
91560 ** Constraint type Action What Happens
91561 ** --------------- ---------- ----------------------------------------
91562 ** any ROLLBACK The current transaction is rolled back and
91563 ** sqlite3_exec() returns immediately with a
91564 ** return code of SQLITE_CONSTRAINT.
91566 ** any ABORT Back out changes from the current command
91567 ** only (do not do a complete rollback) then
91568 ** cause sqlite3_exec() to return immediately
91569 ** with SQLITE_CONSTRAINT.
91571 ** any FAIL Sqlite3_exec() returns immediately with a
91572 ** return code of SQLITE_CONSTRAINT. The
91573 ** transaction is not rolled back and any
91574 ** prior changes are retained.
91576 ** any IGNORE The record number and data is popped from
91577 ** the stack and there is an immediate jump
91578 ** to label ignoreDest.
91580 ** NOT NULL REPLACE The NULL value is replace by the default
91581 ** value for that column. If the default value
91582 ** is NULL, the action is the same as ABORT.
91584 ** UNIQUE REPLACE The other row that conflicts with the row
91585 ** being inserted is removed.
91587 ** CHECK REPLACE Illegal. The results in an exception.
91589 ** Which action to take is determined by the overrideError parameter.
91590 ** Or if overrideError==OE_Default, then the pParse->onError parameter
91591 ** is used. Or if pParse->onError==OE_Default then the onError value
91592 ** for the constraint is used.
91594 ** The calling routine must open a read/write cursor for pTab with
91595 ** cursor number "baseCur". All indices of pTab must also have open
91596 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
91597 ** Except, if there is no possibility of a REPLACE action then
91598 ** cursors do not need to be open for indices where aRegIdx[i]==0.
91600 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
91601 Parse *pParse, /* The parser context */
91602 Table *pTab, /* the table into which we are inserting */
91603 int baseCur, /* Index of a read/write cursor pointing at pTab */
91604 int regRowid, /* Index of the range of input registers */
91605 int *aRegIdx, /* Register used by each index. 0 for unused indices */
91606 int rowidChng, /* True if the rowid might collide with existing entry */
91607 int isUpdate, /* True for UPDATE, False for INSERT */
91608 int overrideError, /* Override onError to this if not OE_Default */
91609 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
91610 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
91612 int i; /* loop counter */
91613 Vdbe *v; /* VDBE under constrution */
91614 int nCol; /* Number of columns */
91615 int onError; /* Conflict resolution strategy */
91616 int j1; /* Addresss of jump instruction */
91617 int j2 = 0, j3; /* Addresses of jump instructions */
91618 int regData; /* Register containing first data column */
91619 int iCur; /* Table cursor number */
91620 Index *pIdx; /* Pointer to one of the indices */
91621 sqlite3 *db; /* Database connection */
91622 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
91623 int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
91625 db = pParse->db;
91626 v = sqlite3GetVdbe(pParse);
91627 assert( v!=0 );
91628 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
91629 nCol = pTab->nCol;
91630 regData = regRowid + 1;
91632 /* Test all NOT NULL constraints.
91634 for(i=0; i<nCol; i++){
91635 if( i==pTab->iPKey ){
91636 continue;
91638 onError = pTab->aCol[i].notNull;
91639 if( onError==OE_None ) continue;
91640 if( overrideError!=OE_Default ){
91641 onError = overrideError;
91642 }else if( onError==OE_Default ){
91643 onError = OE_Abort;
91645 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
91646 onError = OE_Abort;
91648 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
91649 || onError==OE_Ignore || onError==OE_Replace );
91650 switch( onError ){
91651 case OE_Abort:
91652 sqlite3MayAbort(pParse);
91653 case OE_Rollback:
91654 case OE_Fail: {
91655 char *zMsg;
91656 sqlite3VdbeAddOp3(v, OP_HaltIfNull,
91657 SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
91658 zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
91659 pTab->zName, pTab->aCol[i].zName);
91660 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
91661 break;
91663 case OE_Ignore: {
91664 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
91665 break;
91667 default: {
91668 assert( onError==OE_Replace );
91669 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
91670 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
91671 sqlite3VdbeJumpHere(v, j1);
91672 break;
91677 /* Test all CHECK constraints
91679 #ifndef SQLITE_OMIT_CHECK
91680 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
91681 ExprList *pCheck = pTab->pCheck;
91682 pParse->ckBase = regData;
91683 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
91684 for(i=0; i<pCheck->nExpr; i++){
91685 int allOk = sqlite3VdbeMakeLabel(v);
91686 sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
91687 if( onError==OE_Ignore ){
91688 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91689 }else{
91690 char *zConsName = pCheck->a[i].zName;
91691 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
91692 if( zConsName ){
91693 zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
91694 }else{
91695 zConsName = 0;
91697 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
91698 onError, zConsName, P4_DYNAMIC);
91700 sqlite3VdbeResolveLabel(v, allOk);
91703 #endif /* !defined(SQLITE_OMIT_CHECK) */
91705 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
91706 ** of the new record does not previously exist. Except, if this
91707 ** is an UPDATE and the primary key is not changing, that is OK.
91709 if( rowidChng ){
91710 onError = pTab->keyConf;
91711 if( overrideError!=OE_Default ){
91712 onError = overrideError;
91713 }else if( onError==OE_Default ){
91714 onError = OE_Abort;
91717 if( isUpdate ){
91718 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
91720 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
91721 switch( onError ){
91722 default: {
91723 onError = OE_Abort;
91724 /* Fall thru into the next case */
91726 case OE_Rollback:
91727 case OE_Abort:
91728 case OE_Fail: {
91729 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
91730 onError, "PRIMARY KEY must be unique", P4_STATIC);
91731 break;
91733 case OE_Replace: {
91734 /* If there are DELETE triggers on this table and the
91735 ** recursive-triggers flag is set, call GenerateRowDelete() to
91736 ** remove the conflicting row from the table. This will fire
91737 ** the triggers and remove both the table and index b-tree entries.
91739 ** Otherwise, if there are no triggers or the recursive-triggers
91740 ** flag is not set, but the table has one or more indexes, call
91741 ** GenerateRowIndexDelete(). This removes the index b-tree entries
91742 ** only. The table b-tree entry will be replaced by the new entry
91743 ** when it is inserted.
91745 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
91746 ** also invoke MultiWrite() to indicate that this VDBE may require
91747 ** statement rollback (if the statement is aborted after the delete
91748 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
91749 ** but being more selective here allows statements like:
91751 ** REPLACE INTO t(rowid) VALUES($newrowid)
91753 ** to run without a statement journal if there are no indexes on the
91754 ** table.
91756 Trigger *pTrigger = 0;
91757 if( db->flags&SQLITE_RecTriggers ){
91758 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
91760 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
91761 sqlite3MultiWrite(pParse);
91762 sqlite3GenerateRowDelete(
91763 pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
91765 }else if( pTab->pIndex ){
91766 sqlite3MultiWrite(pParse);
91767 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
91769 seenReplace = 1;
91770 break;
91772 case OE_Ignore: {
91773 assert( seenReplace==0 );
91774 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91775 break;
91778 sqlite3VdbeJumpHere(v, j3);
91779 if( isUpdate ){
91780 sqlite3VdbeJumpHere(v, j2);
91784 /* Test all UNIQUE constraints by creating entries for each UNIQUE
91785 ** index and making sure that duplicate entries do not already exist.
91786 ** Add the new records to the indices as we go.
91788 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
91789 int regIdx;
91790 int regR;
91791 int addrSkipRow = 0;
91793 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
91795 if( pIdx->pPartIdxWhere ){
91796 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
91797 addrSkipRow = sqlite3VdbeMakeLabel(v);
91798 pParse->ckBase = regData;
91799 sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
91800 SQLITE_JUMPIFNULL);
91801 pParse->ckBase = 0;
91804 /* Create a key for accessing the index entry */
91805 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
91806 for(i=0; i<pIdx->nColumn; i++){
91807 int idx = pIdx->aiColumn[i];
91808 if( idx==pTab->iPKey ){
91809 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
91810 }else{
91811 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
91814 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
91815 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
91816 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
91817 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
91819 /* Find out what action to take in case there is an indexing conflict */
91820 onError = pIdx->onError;
91821 if( onError==OE_None ){
91822 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
91823 sqlite3VdbeResolveLabel(v, addrSkipRow);
91824 continue; /* pIdx is not a UNIQUE index */
91826 if( overrideError!=OE_Default ){
91827 onError = overrideError;
91828 }else if( onError==OE_Default ){
91829 onError = OE_Abort;
91831 if( seenReplace ){
91832 if( onError==OE_Ignore ) onError = OE_Replace;
91833 else if( onError==OE_Fail ) onError = OE_Abort;
91836 /* Check to see if the new index entry will be unique */
91837 regR = sqlite3GetTempReg(pParse);
91838 sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
91839 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
91840 regR, SQLITE_INT_TO_PTR(regIdx),
91841 P4_INT32);
91842 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
91844 /* Generate code that executes if the new index entry is not unique */
91845 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
91846 || onError==OE_Ignore || onError==OE_Replace );
91847 switch( onError ){
91848 case OE_Rollback:
91849 case OE_Abort:
91850 case OE_Fail: {
91851 int j;
91852 StrAccum errMsg;
91853 const char *zSep;
91854 char *zErr;
91856 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
91857 errMsg.db = db;
91858 zSep = pIdx->nColumn>1 ? "columns " : "column ";
91859 for(j=0; j<pIdx->nColumn; j++){
91860 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
91861 sqlite3StrAccumAppend(&errMsg, zSep, -1);
91862 zSep = ", ";
91863 sqlite3StrAccumAppend(&errMsg, zCol, -1);
91865 sqlite3StrAccumAppend(&errMsg,
91866 pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
91867 zErr = sqlite3StrAccumFinish(&errMsg);
91868 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
91869 onError, zErr, 0);
91870 sqlite3DbFree(errMsg.db, zErr);
91871 break;
91873 case OE_Ignore: {
91874 assert( seenReplace==0 );
91875 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91876 break;
91878 default: {
91879 Trigger *pTrigger = 0;
91880 assert( onError==OE_Replace );
91881 sqlite3MultiWrite(pParse);
91882 if( db->flags&SQLITE_RecTriggers ){
91883 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
91885 sqlite3GenerateRowDelete(
91886 pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
91888 seenReplace = 1;
91889 break;
91892 sqlite3VdbeJumpHere(v, j3);
91893 sqlite3VdbeResolveLabel(v, addrSkipRow);
91894 sqlite3ReleaseTempReg(pParse, regR);
91897 if( pbMayReplace ){
91898 *pbMayReplace = seenReplace;
91903 ** This routine generates code to finish the INSERT or UPDATE operation
91904 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
91905 ** A consecutive range of registers starting at regRowid contains the
91906 ** rowid and the content to be inserted.
91908 ** The arguments to this routine should be the same as the first six
91909 ** arguments to sqlite3GenerateConstraintChecks.
91911 SQLITE_PRIVATE void sqlite3CompleteInsertion(
91912 Parse *pParse, /* The parser context */
91913 Table *pTab, /* the table into which we are inserting */
91914 int baseCur, /* Index of a read/write cursor pointing at pTab */
91915 int regRowid, /* Range of content */
91916 int *aRegIdx, /* Register used by each index. 0 for unused indices */
91917 int isUpdate, /* True for UPDATE, False for INSERT */
91918 int appendBias, /* True if this is likely to be an append */
91919 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
91921 int i;
91922 Vdbe *v;
91923 Index *pIdx;
91924 u8 pik_flags;
91925 int regData;
91926 int regRec;
91928 v = sqlite3GetVdbe(pParse);
91929 assert( v!=0 );
91930 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
91931 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91932 if( aRegIdx[i]==0 ) continue;
91933 if( pIdx->pPartIdxWhere ){
91934 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
91936 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
91937 if( useSeekResult ){
91938 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
91941 regData = regRowid + 1;
91942 regRec = sqlite3GetTempReg(pParse);
91943 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
91944 sqlite3TableAffinityStr(v, pTab);
91945 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
91946 if( pParse->nested ){
91947 pik_flags = 0;
91948 }else{
91949 pik_flags = OPFLAG_NCHANGE;
91950 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
91952 if( appendBias ){
91953 pik_flags |= OPFLAG_APPEND;
91955 if( useSeekResult ){
91956 pik_flags |= OPFLAG_USESEEKRESULT;
91958 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
91959 if( !pParse->nested ){
91960 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
91962 sqlite3VdbeChangeP5(v, pik_flags);
91966 ** Generate code that will open cursors for a table and for all
91967 ** indices of that table. The "baseCur" parameter is the cursor number used
91968 ** for the table. Indices are opened on subsequent cursors.
91970 ** Return the number of indices on the table.
91972 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
91973 Parse *pParse, /* Parsing context */
91974 Table *pTab, /* Table to be opened */
91975 int baseCur, /* Cursor number assigned to the table */
91976 int op /* OP_OpenRead or OP_OpenWrite */
91978 int i;
91979 int iDb;
91980 Index *pIdx;
91981 Vdbe *v;
91983 if( IsVirtual(pTab) ) return 0;
91984 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91985 v = sqlite3GetVdbe(pParse);
91986 assert( v!=0 );
91987 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
91988 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91989 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
91990 assert( pIdx->pSchema==pTab->pSchema );
91991 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
91992 (char*)pKey, P4_KEYINFO_HANDOFF);
91993 VdbeComment((v, "%s", pIdx->zName));
91995 if( pParse->nTab<baseCur+i ){
91996 pParse->nTab = baseCur+i;
91998 return i-1;
92002 #ifdef SQLITE_TEST
92004 ** The following global variable is incremented whenever the
92005 ** transfer optimization is used. This is used for testing
92006 ** purposes only - to make sure the transfer optimization really
92007 ** is happening when it is suppose to.
92009 SQLITE_API int sqlite3_xferopt_count;
92010 #endif /* SQLITE_TEST */
92013 #ifndef SQLITE_OMIT_XFER_OPT
92015 ** Check to collation names to see if they are compatible.
92017 static int xferCompatibleCollation(const char *z1, const char *z2){
92018 if( z1==0 ){
92019 return z2==0;
92021 if( z2==0 ){
92022 return 0;
92024 return sqlite3StrICmp(z1, z2)==0;
92029 ** Check to see if index pSrc is compatible as a source of data
92030 ** for index pDest in an insert transfer optimization. The rules
92031 ** for a compatible index:
92033 ** * The index is over the same set of columns
92034 ** * The same DESC and ASC markings occurs on all columns
92035 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
92036 ** * The same collating sequence on each column
92037 ** * The index has the exact same WHERE clause
92039 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
92040 int i;
92041 assert( pDest && pSrc );
92042 assert( pDest->pTable!=pSrc->pTable );
92043 if( pDest->nColumn!=pSrc->nColumn ){
92044 return 0; /* Different number of columns */
92046 if( pDest->onError!=pSrc->onError ){
92047 return 0; /* Different conflict resolution strategies */
92049 for(i=0; i<pSrc->nColumn; i++){
92050 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
92051 return 0; /* Different columns indexed */
92053 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
92054 return 0; /* Different sort orders */
92056 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
92057 return 0; /* Different collating sequences */
92060 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
92061 return 0; /* Different WHERE clauses */
92064 /* If no test above fails then the indices must be compatible */
92065 return 1;
92069 ** Attempt the transfer optimization on INSERTs of the form
92071 ** INSERT INTO tab1 SELECT * FROM tab2;
92073 ** The xfer optimization transfers raw records from tab2 over to tab1.
92074 ** Columns are not decoded and reassemblied, which greatly improves
92075 ** performance. Raw index records are transferred in the same way.
92077 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
92078 ** There are lots of rules for determining compatibility - see comments
92079 ** embedded in the code for details.
92081 ** This routine returns TRUE if the optimization is guaranteed to be used.
92082 ** Sometimes the xfer optimization will only work if the destination table
92083 ** is empty - a factor that can only be determined at run-time. In that
92084 ** case, this routine generates code for the xfer optimization but also
92085 ** does a test to see if the destination table is empty and jumps over the
92086 ** xfer optimization code if the test fails. In that case, this routine
92087 ** returns FALSE so that the caller will know to go ahead and generate
92088 ** an unoptimized transfer. This routine also returns FALSE if there
92089 ** is no chance that the xfer optimization can be applied.
92091 ** This optimization is particularly useful at making VACUUM run faster.
92093 static int xferOptimization(
92094 Parse *pParse, /* Parser context */
92095 Table *pDest, /* The table we are inserting into */
92096 Select *pSelect, /* A SELECT statement to use as the data source */
92097 int onError, /* How to handle constraint errors */
92098 int iDbDest /* The database of pDest */
92100 ExprList *pEList; /* The result set of the SELECT */
92101 Table *pSrc; /* The table in the FROM clause of SELECT */
92102 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
92103 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
92104 int i; /* Loop counter */
92105 int iDbSrc; /* The database of pSrc */
92106 int iSrc, iDest; /* Cursors from source and destination */
92107 int addr1, addr2; /* Loop addresses */
92108 int emptyDestTest; /* Address of test for empty pDest */
92109 int emptySrcTest; /* Address of test for empty pSrc */
92110 Vdbe *v; /* The VDBE we are building */
92111 KeyInfo *pKey; /* Key information for an index */
92112 int regAutoinc; /* Memory register used by AUTOINC */
92113 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
92114 int regData, regRowid; /* Registers holding data and rowid */
92116 if( pSelect==0 ){
92117 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
92119 if( sqlite3TriggerList(pParse, pDest) ){
92120 return 0; /* tab1 must not have triggers */
92122 #ifndef SQLITE_OMIT_VIRTUALTABLE
92123 if( pDest->tabFlags & TF_Virtual ){
92124 return 0; /* tab1 must not be a virtual table */
92126 #endif
92127 if( onError==OE_Default ){
92128 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
92129 if( onError==OE_Default ) onError = OE_Abort;
92131 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
92132 if( pSelect->pSrc->nSrc!=1 ){
92133 return 0; /* FROM clause must have exactly one term */
92135 if( pSelect->pSrc->a[0].pSelect ){
92136 return 0; /* FROM clause cannot contain a subquery */
92138 if( pSelect->pWhere ){
92139 return 0; /* SELECT may not have a WHERE clause */
92141 if( pSelect->pOrderBy ){
92142 return 0; /* SELECT may not have an ORDER BY clause */
92144 /* Do not need to test for a HAVING clause. If HAVING is present but
92145 ** there is no ORDER BY, we will get an error. */
92146 if( pSelect->pGroupBy ){
92147 return 0; /* SELECT may not have a GROUP BY clause */
92149 if( pSelect->pLimit ){
92150 return 0; /* SELECT may not have a LIMIT clause */
92152 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
92153 if( pSelect->pPrior ){
92154 return 0; /* SELECT may not be a compound query */
92156 if( pSelect->selFlags & SF_Distinct ){
92157 return 0; /* SELECT may not be DISTINCT */
92159 pEList = pSelect->pEList;
92160 assert( pEList!=0 );
92161 if( pEList->nExpr!=1 ){
92162 return 0; /* The result set must have exactly one column */
92164 assert( pEList->a[0].pExpr );
92165 if( pEList->a[0].pExpr->op!=TK_ALL ){
92166 return 0; /* The result set must be the special operator "*" */
92169 /* At this point we have established that the statement is of the
92170 ** correct syntactic form to participate in this optimization. Now
92171 ** we have to check the semantics.
92173 pItem = pSelect->pSrc->a;
92174 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
92175 if( pSrc==0 ){
92176 return 0; /* FROM clause does not contain a real table */
92178 if( pSrc==pDest ){
92179 return 0; /* tab1 and tab2 may not be the same table */
92181 #ifndef SQLITE_OMIT_VIRTUALTABLE
92182 if( pSrc->tabFlags & TF_Virtual ){
92183 return 0; /* tab2 must not be a virtual table */
92185 #endif
92186 if( pSrc->pSelect ){
92187 return 0; /* tab2 may not be a view */
92189 if( pDest->nCol!=pSrc->nCol ){
92190 return 0; /* Number of columns must be the same in tab1 and tab2 */
92192 if( pDest->iPKey!=pSrc->iPKey ){
92193 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
92195 for(i=0; i<pDest->nCol; i++){
92196 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
92197 return 0; /* Affinity must be the same on all columns */
92199 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
92200 return 0; /* Collating sequence must be the same on all columns */
92202 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
92203 return 0; /* tab2 must be NOT NULL if tab1 is */
92206 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
92207 if( pDestIdx->onError!=OE_None ){
92208 destHasUniqueIdx = 1;
92210 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
92211 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
92213 if( pSrcIdx==0 ){
92214 return 0; /* pDestIdx has no corresponding index in pSrc */
92217 #ifndef SQLITE_OMIT_CHECK
92218 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
92219 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
92221 #endif
92222 #ifndef SQLITE_OMIT_FOREIGN_KEY
92223 /* Disallow the transfer optimization if the destination table constains
92224 ** any foreign key constraints. This is more restrictive than necessary.
92225 ** But the main beneficiary of the transfer optimization is the VACUUM
92226 ** command, and the VACUUM command disables foreign key constraints. So
92227 ** the extra complication to make this rule less restrictive is probably
92228 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
92230 if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
92231 return 0;
92233 #endif
92234 if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
92235 return 0; /* xfer opt does not play well with PRAGMA count_changes */
92238 /* If we get this far, it means that the xfer optimization is at
92239 ** least a possibility, though it might only work if the destination
92240 ** table (tab1) is initially empty.
92242 #ifdef SQLITE_TEST
92243 sqlite3_xferopt_count++;
92244 #endif
92245 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
92246 v = sqlite3GetVdbe(pParse);
92247 sqlite3CodeVerifySchema(pParse, iDbSrc);
92248 iSrc = pParse->nTab++;
92249 iDest = pParse->nTab++;
92250 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
92251 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
92252 if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
92253 || destHasUniqueIdx /* (2) */
92254 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
92256 /* In some circumstances, we are able to run the xfer optimization
92257 ** only if the destination table is initially empty. This code makes
92258 ** that determination. Conditions under which the destination must
92259 ** be empty:
92261 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
92262 ** (If the destination is not initially empty, the rowid fields
92263 ** of index entries might need to change.)
92265 ** (2) The destination has a unique index. (The xfer optimization
92266 ** is unable to test uniqueness.)
92268 ** (3) onError is something other than OE_Abort and OE_Rollback.
92270 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
92271 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
92272 sqlite3VdbeJumpHere(v, addr1);
92273 }else{
92274 emptyDestTest = 0;
92276 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
92277 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
92278 regData = sqlite3GetTempReg(pParse);
92279 regRowid = sqlite3GetTempReg(pParse);
92280 if( pDest->iPKey>=0 ){
92281 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
92282 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
92283 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
92284 onError, "PRIMARY KEY must be unique", P4_STATIC);
92285 sqlite3VdbeJumpHere(v, addr2);
92286 autoIncStep(pParse, regAutoinc, regRowid);
92287 }else if( pDest->pIndex==0 ){
92288 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
92289 }else{
92290 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
92291 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
92293 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
92294 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
92295 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
92296 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
92297 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
92298 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
92299 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
92300 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
92302 assert( pSrcIdx );
92303 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
92304 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
92305 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
92306 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
92307 (char*)pKey, P4_KEYINFO_HANDOFF);
92308 VdbeComment((v, "%s", pSrcIdx->zName));
92309 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
92310 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
92311 (char*)pKey, P4_KEYINFO_HANDOFF);
92312 VdbeComment((v, "%s", pDestIdx->zName));
92313 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
92314 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
92315 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
92316 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
92317 sqlite3VdbeJumpHere(v, addr1);
92319 sqlite3VdbeJumpHere(v, emptySrcTest);
92320 sqlite3ReleaseTempReg(pParse, regRowid);
92321 sqlite3ReleaseTempReg(pParse, regData);
92322 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
92323 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
92324 if( emptyDestTest ){
92325 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
92326 sqlite3VdbeJumpHere(v, emptyDestTest);
92327 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
92328 return 0;
92329 }else{
92330 return 1;
92333 #endif /* SQLITE_OMIT_XFER_OPT */
92335 /************** End of insert.c **********************************************/
92336 /************** Begin file legacy.c ******************************************/
92338 ** 2001 September 15
92340 ** The author disclaims copyright to this source code. In place of
92341 ** a legal notice, here is a blessing:
92343 ** May you do good and not evil.
92344 ** May you find forgiveness for yourself and forgive others.
92345 ** May you share freely, never taking more than you give.
92347 *************************************************************************
92348 ** Main file for the SQLite library. The routines in this file
92349 ** implement the programmer interface to the library. Routines in
92350 ** other files are for internal use by SQLite and should not be
92351 ** accessed by users of the library.
92356 ** Execute SQL code. Return one of the SQLITE_ success/failure
92357 ** codes. Also write an error message into memory obtained from
92358 ** malloc() and make *pzErrMsg point to that message.
92360 ** If the SQL is a query, then for each row in the query result
92361 ** the xCallback() function is called. pArg becomes the first
92362 ** argument to xCallback(). If xCallback=NULL then no callback
92363 ** is invoked, even for queries.
92365 SQLITE_API int sqlite3_exec(
92366 sqlite3 *db, /* The database on which the SQL executes */
92367 const char *zSql, /* The SQL to be executed */
92368 sqlite3_callback xCallback, /* Invoke this callback routine */
92369 void *pArg, /* First argument to xCallback() */
92370 char **pzErrMsg /* Write error messages here */
92372 int rc = SQLITE_OK; /* Return code */
92373 const char *zLeftover; /* Tail of unprocessed SQL */
92374 sqlite3_stmt *pStmt = 0; /* The current SQL statement */
92375 char **azCols = 0; /* Names of result columns */
92376 int callbackIsInit; /* True if callback data is initialized */
92378 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
92379 if( zSql==0 ) zSql = "";
92381 sqlite3_mutex_enter(db->mutex);
92382 sqlite3Error(db, SQLITE_OK, 0);
92383 while( rc==SQLITE_OK && zSql[0] ){
92384 int nCol;
92385 char **azVals = 0;
92387 pStmt = 0;
92388 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
92389 assert( rc==SQLITE_OK || pStmt==0 );
92390 if( rc!=SQLITE_OK ){
92391 continue;
92393 if( !pStmt ){
92394 /* this happens for a comment or white-space */
92395 zSql = zLeftover;
92396 continue;
92399 callbackIsInit = 0;
92400 nCol = sqlite3_column_count(pStmt);
92402 while( 1 ){
92403 int i;
92404 rc = sqlite3_step(pStmt);
92406 /* Invoke the callback function if required */
92407 if( xCallback && (SQLITE_ROW==rc ||
92408 (SQLITE_DONE==rc && !callbackIsInit
92409 && db->flags&SQLITE_NullCallback)) ){
92410 if( !callbackIsInit ){
92411 azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
92412 if( azCols==0 ){
92413 goto exec_out;
92415 for(i=0; i<nCol; i++){
92416 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
92417 /* sqlite3VdbeSetColName() installs column names as UTF8
92418 ** strings so there is no way for sqlite3_column_name() to fail. */
92419 assert( azCols[i]!=0 );
92421 callbackIsInit = 1;
92423 if( rc==SQLITE_ROW ){
92424 azVals = &azCols[nCol];
92425 for(i=0; i<nCol; i++){
92426 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
92427 if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
92428 db->mallocFailed = 1;
92429 goto exec_out;
92433 if( xCallback(pArg, nCol, azVals, azCols) ){
92434 rc = SQLITE_ABORT;
92435 sqlite3VdbeFinalize((Vdbe *)pStmt);
92436 pStmt = 0;
92437 sqlite3Error(db, SQLITE_ABORT, 0);
92438 goto exec_out;
92442 if( rc!=SQLITE_ROW ){
92443 rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
92444 pStmt = 0;
92445 zSql = zLeftover;
92446 while( sqlite3Isspace(zSql[0]) ) zSql++;
92447 break;
92451 sqlite3DbFree(db, azCols);
92452 azCols = 0;
92455 exec_out:
92456 if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
92457 sqlite3DbFree(db, azCols);
92459 rc = sqlite3ApiExit(db, rc);
92460 if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
92461 int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
92462 *pzErrMsg = sqlite3Malloc(nErrMsg);
92463 if( *pzErrMsg ){
92464 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
92465 }else{
92466 rc = SQLITE_NOMEM;
92467 sqlite3Error(db, SQLITE_NOMEM, 0);
92469 }else if( pzErrMsg ){
92470 *pzErrMsg = 0;
92473 assert( (rc&db->errMask)==rc );
92474 sqlite3_mutex_leave(db->mutex);
92475 return rc;
92478 /************** End of legacy.c **********************************************/
92479 /************** Begin file loadext.c *****************************************/
92481 ** 2006 June 7
92483 ** The author disclaims copyright to this source code. In place of
92484 ** a legal notice, here is a blessing:
92486 ** May you do good and not evil.
92487 ** May you find forgiveness for yourself and forgive others.
92488 ** May you share freely, never taking more than you give.
92490 *************************************************************************
92491 ** This file contains code used to dynamically load extensions into
92492 ** the SQLite library.
92495 #ifndef SQLITE_CORE
92496 #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
92497 #endif
92498 /************** Include sqlite3ext.h in the middle of loadext.c **************/
92499 /************** Begin file sqlite3ext.h **************************************/
92501 ** 2006 June 7
92503 ** The author disclaims copyright to this source code. In place of
92504 ** a legal notice, here is a blessing:
92506 ** May you do good and not evil.
92507 ** May you find forgiveness for yourself and forgive others.
92508 ** May you share freely, never taking more than you give.
92510 *************************************************************************
92511 ** This header file defines the SQLite interface for use by
92512 ** shared libraries that want to be imported as extensions into
92513 ** an SQLite instance. Shared libraries that intend to be loaded
92514 ** as extensions by SQLite should #include this file instead of
92515 ** sqlite3.h.
92517 #ifndef _SQLITE3EXT_H_
92518 #define _SQLITE3EXT_H_
92520 typedef struct sqlite3_api_routines sqlite3_api_routines;
92523 ** The following structure holds pointers to all of the SQLite API
92524 ** routines.
92526 ** WARNING: In order to maintain backwards compatibility, add new
92527 ** interfaces to the end of this structure only. If you insert new
92528 ** interfaces in the middle of this structure, then older different
92529 ** versions of SQLite will not be able to load each others' shared
92530 ** libraries!
92532 struct sqlite3_api_routines {
92533 void * (*aggregate_context)(sqlite3_context*,int nBytes);
92534 int (*aggregate_count)(sqlite3_context*);
92535 int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
92536 int (*bind_double)(sqlite3_stmt*,int,double);
92537 int (*bind_int)(sqlite3_stmt*,int,int);
92538 int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
92539 int (*bind_null)(sqlite3_stmt*,int);
92540 int (*bind_parameter_count)(sqlite3_stmt*);
92541 int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
92542 const char * (*bind_parameter_name)(sqlite3_stmt*,int);
92543 int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
92544 int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
92545 int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
92546 int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
92547 int (*busy_timeout)(sqlite3*,int ms);
92548 int (*changes)(sqlite3*);
92549 int (*close)(sqlite3*);
92550 int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
92551 int eTextRep,const char*));
92552 int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
92553 int eTextRep,const void*));
92554 const void * (*column_blob)(sqlite3_stmt*,int iCol);
92555 int (*column_bytes)(sqlite3_stmt*,int iCol);
92556 int (*column_bytes16)(sqlite3_stmt*,int iCol);
92557 int (*column_count)(sqlite3_stmt*pStmt);
92558 const char * (*column_database_name)(sqlite3_stmt*,int);
92559 const void * (*column_database_name16)(sqlite3_stmt*,int);
92560 const char * (*column_decltype)(sqlite3_stmt*,int i);
92561 const void * (*column_decltype16)(sqlite3_stmt*,int);
92562 double (*column_double)(sqlite3_stmt*,int iCol);
92563 int (*column_int)(sqlite3_stmt*,int iCol);
92564 sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
92565 const char * (*column_name)(sqlite3_stmt*,int);
92566 const void * (*column_name16)(sqlite3_stmt*,int);
92567 const char * (*column_origin_name)(sqlite3_stmt*,int);
92568 const void * (*column_origin_name16)(sqlite3_stmt*,int);
92569 const char * (*column_table_name)(sqlite3_stmt*,int);
92570 const void * (*column_table_name16)(sqlite3_stmt*,int);
92571 const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
92572 const void * (*column_text16)(sqlite3_stmt*,int iCol);
92573 int (*column_type)(sqlite3_stmt*,int iCol);
92574 sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
92575 void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
92576 int (*complete)(const char*sql);
92577 int (*complete16)(const void*sql);
92578 int (*create_collation)(sqlite3*,const char*,int,void*,
92579 int(*)(void*,int,const void*,int,const void*));
92580 int (*create_collation16)(sqlite3*,const void*,int,void*,
92581 int(*)(void*,int,const void*,int,const void*));
92582 int (*create_function)(sqlite3*,const char*,int,int,void*,
92583 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92584 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92585 void (*xFinal)(sqlite3_context*));
92586 int (*create_function16)(sqlite3*,const void*,int,int,void*,
92587 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92588 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92589 void (*xFinal)(sqlite3_context*));
92590 int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
92591 int (*data_count)(sqlite3_stmt*pStmt);
92592 sqlite3 * (*db_handle)(sqlite3_stmt*);
92593 int (*declare_vtab)(sqlite3*,const char*);
92594 int (*enable_shared_cache)(int);
92595 int (*errcode)(sqlite3*db);
92596 const char * (*errmsg)(sqlite3*);
92597 const void * (*errmsg16)(sqlite3*);
92598 int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
92599 int (*expired)(sqlite3_stmt*);
92600 int (*finalize)(sqlite3_stmt*pStmt);
92601 void (*free)(void*);
92602 void (*free_table)(char**result);
92603 int (*get_autocommit)(sqlite3*);
92604 void * (*get_auxdata)(sqlite3_context*,int);
92605 int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
92606 int (*global_recover)(void);
92607 void (*interruptx)(sqlite3*);
92608 sqlite_int64 (*last_insert_rowid)(sqlite3*);
92609 const char * (*libversion)(void);
92610 int (*libversion_number)(void);
92611 void *(*malloc)(int);
92612 char * (*mprintf)(const char*,...);
92613 int (*open)(const char*,sqlite3**);
92614 int (*open16)(const void*,sqlite3**);
92615 int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
92616 int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
92617 void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
92618 void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
92619 void *(*realloc)(void*,int);
92620 int (*reset)(sqlite3_stmt*pStmt);
92621 void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
92622 void (*result_double)(sqlite3_context*,double);
92623 void (*result_error)(sqlite3_context*,const char*,int);
92624 void (*result_error16)(sqlite3_context*,const void*,int);
92625 void (*result_int)(sqlite3_context*,int);
92626 void (*result_int64)(sqlite3_context*,sqlite_int64);
92627 void (*result_null)(sqlite3_context*);
92628 void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
92629 void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
92630 void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
92631 void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
92632 void (*result_value)(sqlite3_context*,sqlite3_value*);
92633 void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
92634 int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
92635 const char*,const char*),void*);
92636 void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
92637 char * (*snprintf)(int,char*,const char*,...);
92638 int (*step)(sqlite3_stmt*);
92639 int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
92640 char const**,char const**,int*,int*,int*);
92641 void (*thread_cleanup)(void);
92642 int (*total_changes)(sqlite3*);
92643 void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
92644 int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
92645 void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
92646 sqlite_int64),void*);
92647 void * (*user_data)(sqlite3_context*);
92648 const void * (*value_blob)(sqlite3_value*);
92649 int (*value_bytes)(sqlite3_value*);
92650 int (*value_bytes16)(sqlite3_value*);
92651 double (*value_double)(sqlite3_value*);
92652 int (*value_int)(sqlite3_value*);
92653 sqlite_int64 (*value_int64)(sqlite3_value*);
92654 int (*value_numeric_type)(sqlite3_value*);
92655 const unsigned char * (*value_text)(sqlite3_value*);
92656 const void * (*value_text16)(sqlite3_value*);
92657 const void * (*value_text16be)(sqlite3_value*);
92658 const void * (*value_text16le)(sqlite3_value*);
92659 int (*value_type)(sqlite3_value*);
92660 char *(*vmprintf)(const char*,va_list);
92661 /* Added ??? */
92662 int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
92663 /* Added by 3.3.13 */
92664 int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
92665 int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
92666 int (*clear_bindings)(sqlite3_stmt*);
92667 /* Added by 3.4.1 */
92668 int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
92669 void (*xDestroy)(void *));
92670 /* Added by 3.5.0 */
92671 int (*bind_zeroblob)(sqlite3_stmt*,int,int);
92672 int (*blob_bytes)(sqlite3_blob*);
92673 int (*blob_close)(sqlite3_blob*);
92674 int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
92675 int,sqlite3_blob**);
92676 int (*blob_read)(sqlite3_blob*,void*,int,int);
92677 int (*blob_write)(sqlite3_blob*,const void*,int,int);
92678 int (*create_collation_v2)(sqlite3*,const char*,int,void*,
92679 int(*)(void*,int,const void*,int,const void*),
92680 void(*)(void*));
92681 int (*file_control)(sqlite3*,const char*,int,void*);
92682 sqlite3_int64 (*memory_highwater)(int);
92683 sqlite3_int64 (*memory_used)(void);
92684 sqlite3_mutex *(*mutex_alloc)(int);
92685 void (*mutex_enter)(sqlite3_mutex*);
92686 void (*mutex_free)(sqlite3_mutex*);
92687 void (*mutex_leave)(sqlite3_mutex*);
92688 int (*mutex_try)(sqlite3_mutex*);
92689 int (*open_v2)(const char*,sqlite3**,int,const char*);
92690 int (*release_memory)(int);
92691 void (*result_error_nomem)(sqlite3_context*);
92692 void (*result_error_toobig)(sqlite3_context*);
92693 int (*sleep)(int);
92694 void (*soft_heap_limit)(int);
92695 sqlite3_vfs *(*vfs_find)(const char*);
92696 int (*vfs_register)(sqlite3_vfs*,int);
92697 int (*vfs_unregister)(sqlite3_vfs*);
92698 int (*xthreadsafe)(void);
92699 void (*result_zeroblob)(sqlite3_context*,int);
92700 void (*result_error_code)(sqlite3_context*,int);
92701 int (*test_control)(int, ...);
92702 void (*randomness)(int,void*);
92703 sqlite3 *(*context_db_handle)(sqlite3_context*);
92704 int (*extended_result_codes)(sqlite3*,int);
92705 int (*limit)(sqlite3*,int,int);
92706 sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
92707 const char *(*sql)(sqlite3_stmt*);
92708 int (*status)(int,int*,int*,int);
92709 int (*backup_finish)(sqlite3_backup*);
92710 sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
92711 int (*backup_pagecount)(sqlite3_backup*);
92712 int (*backup_remaining)(sqlite3_backup*);
92713 int (*backup_step)(sqlite3_backup*,int);
92714 const char *(*compileoption_get)(int);
92715 int (*compileoption_used)(const char*);
92716 int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
92717 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92718 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92719 void (*xFinal)(sqlite3_context*),
92720 void(*xDestroy)(void*));
92721 int (*db_config)(sqlite3*,int,...);
92722 sqlite3_mutex *(*db_mutex)(sqlite3*);
92723 int (*db_status)(sqlite3*,int,int*,int*,int);
92724 int (*extended_errcode)(sqlite3*);
92725 void (*log)(int,const char*,...);
92726 sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
92727 const char *(*sourceid)(void);
92728 int (*stmt_status)(sqlite3_stmt*,int,int);
92729 int (*strnicmp)(const char*,const char*,int);
92730 int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
92731 int (*wal_autocheckpoint)(sqlite3*,int);
92732 int (*wal_checkpoint)(sqlite3*,const char*);
92733 void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
92734 int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
92735 int (*vtab_config)(sqlite3*,int op,...);
92736 int (*vtab_on_conflict)(sqlite3*);
92737 /* Version 3.7.16 and later */
92738 int (*close_v2)(sqlite3*);
92739 const char *(*db_filename)(sqlite3*,const char*);
92740 int (*db_readonly)(sqlite3*,const char*);
92741 int (*db_release_memory)(sqlite3*);
92742 const char *(*errstr)(int);
92743 int (*stmt_busy)(sqlite3_stmt*);
92744 int (*stmt_readonly)(sqlite3_stmt*);
92745 int (*stricmp)(const char*,const char*);
92746 int (*uri_boolean)(const char*,const char*,int);
92747 sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
92748 const char *(*uri_parameter)(const char*,const char*);
92749 char *(*vsnprintf)(int,char*,const char*,va_list);
92750 int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
92754 ** The following macros redefine the API routines so that they are
92755 ** redirected throught the global sqlite3_api structure.
92757 ** This header file is also used by the loadext.c source file
92758 ** (part of the main SQLite library - not an extension) so that
92759 ** it can get access to the sqlite3_api_routines structure
92760 ** definition. But the main library does not want to redefine
92761 ** the API. So the redefinition macros are only valid if the
92762 ** SQLITE_CORE macros is undefined.
92764 #ifndef SQLITE_CORE
92765 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
92766 #ifndef SQLITE_OMIT_DEPRECATED
92767 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
92768 #endif
92769 #define sqlite3_bind_blob sqlite3_api->bind_blob
92770 #define sqlite3_bind_double sqlite3_api->bind_double
92771 #define sqlite3_bind_int sqlite3_api->bind_int
92772 #define sqlite3_bind_int64 sqlite3_api->bind_int64
92773 #define sqlite3_bind_null sqlite3_api->bind_null
92774 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
92775 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
92776 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
92777 #define sqlite3_bind_text sqlite3_api->bind_text
92778 #define sqlite3_bind_text16 sqlite3_api->bind_text16
92779 #define sqlite3_bind_value sqlite3_api->bind_value
92780 #define sqlite3_busy_handler sqlite3_api->busy_handler
92781 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
92782 #define sqlite3_changes sqlite3_api->changes
92783 #define sqlite3_close sqlite3_api->close
92784 #define sqlite3_collation_needed sqlite3_api->collation_needed
92785 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
92786 #define sqlite3_column_blob sqlite3_api->column_blob
92787 #define sqlite3_column_bytes sqlite3_api->column_bytes
92788 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
92789 #define sqlite3_column_count sqlite3_api->column_count
92790 #define sqlite3_column_database_name sqlite3_api->column_database_name
92791 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
92792 #define sqlite3_column_decltype sqlite3_api->column_decltype
92793 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
92794 #define sqlite3_column_double sqlite3_api->column_double
92795 #define sqlite3_column_int sqlite3_api->column_int
92796 #define sqlite3_column_int64 sqlite3_api->column_int64
92797 #define sqlite3_column_name sqlite3_api->column_name
92798 #define sqlite3_column_name16 sqlite3_api->column_name16
92799 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
92800 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
92801 #define sqlite3_column_table_name sqlite3_api->column_table_name
92802 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
92803 #define sqlite3_column_text sqlite3_api->column_text
92804 #define sqlite3_column_text16 sqlite3_api->column_text16
92805 #define sqlite3_column_type sqlite3_api->column_type
92806 #define sqlite3_column_value sqlite3_api->column_value
92807 #define sqlite3_commit_hook sqlite3_api->commit_hook
92808 #define sqlite3_complete sqlite3_api->complete
92809 #define sqlite3_complete16 sqlite3_api->complete16
92810 #define sqlite3_create_collation sqlite3_api->create_collation
92811 #define sqlite3_create_collation16 sqlite3_api->create_collation16
92812 #define sqlite3_create_function sqlite3_api->create_function
92813 #define sqlite3_create_function16 sqlite3_api->create_function16
92814 #define sqlite3_create_module sqlite3_api->create_module
92815 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
92816 #define sqlite3_data_count sqlite3_api->data_count
92817 #define sqlite3_db_handle sqlite3_api->db_handle
92818 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
92819 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
92820 #define sqlite3_errcode sqlite3_api->errcode
92821 #define sqlite3_errmsg sqlite3_api->errmsg
92822 #define sqlite3_errmsg16 sqlite3_api->errmsg16
92823 #define sqlite3_exec sqlite3_api->exec
92824 #ifndef SQLITE_OMIT_DEPRECATED
92825 #define sqlite3_expired sqlite3_api->expired
92826 #endif
92827 #define sqlite3_finalize sqlite3_api->finalize
92828 #define sqlite3_free sqlite3_api->free
92829 #define sqlite3_free_table sqlite3_api->free_table
92830 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
92831 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
92832 #define sqlite3_get_table sqlite3_api->get_table
92833 #ifndef SQLITE_OMIT_DEPRECATED
92834 #define sqlite3_global_recover sqlite3_api->global_recover
92835 #endif
92836 #define sqlite3_interrupt sqlite3_api->interruptx
92837 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
92838 #define sqlite3_libversion sqlite3_api->libversion
92839 #define sqlite3_libversion_number sqlite3_api->libversion_number
92840 #define sqlite3_malloc sqlite3_api->malloc
92841 #define sqlite3_mprintf sqlite3_api->mprintf
92842 #define sqlite3_open sqlite3_api->open
92843 #define sqlite3_open16 sqlite3_api->open16
92844 #define sqlite3_prepare sqlite3_api->prepare
92845 #define sqlite3_prepare16 sqlite3_api->prepare16
92846 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
92847 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
92848 #define sqlite3_profile sqlite3_api->profile
92849 #define sqlite3_progress_handler sqlite3_api->progress_handler
92850 #define sqlite3_realloc sqlite3_api->realloc
92851 #define sqlite3_reset sqlite3_api->reset
92852 #define sqlite3_result_blob sqlite3_api->result_blob
92853 #define sqlite3_result_double sqlite3_api->result_double
92854 #define sqlite3_result_error sqlite3_api->result_error
92855 #define sqlite3_result_error16 sqlite3_api->result_error16
92856 #define sqlite3_result_int sqlite3_api->result_int
92857 #define sqlite3_result_int64 sqlite3_api->result_int64
92858 #define sqlite3_result_null sqlite3_api->result_null
92859 #define sqlite3_result_text sqlite3_api->result_text
92860 #define sqlite3_result_text16 sqlite3_api->result_text16
92861 #define sqlite3_result_text16be sqlite3_api->result_text16be
92862 #define sqlite3_result_text16le sqlite3_api->result_text16le
92863 #define sqlite3_result_value sqlite3_api->result_value
92864 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
92865 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
92866 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
92867 #define sqlite3_snprintf sqlite3_api->snprintf
92868 #define sqlite3_step sqlite3_api->step
92869 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
92870 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
92871 #define sqlite3_total_changes sqlite3_api->total_changes
92872 #define sqlite3_trace sqlite3_api->trace
92873 #ifndef SQLITE_OMIT_DEPRECATED
92874 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
92875 #endif
92876 #define sqlite3_update_hook sqlite3_api->update_hook
92877 #define sqlite3_user_data sqlite3_api->user_data
92878 #define sqlite3_value_blob sqlite3_api->value_blob
92879 #define sqlite3_value_bytes sqlite3_api->value_bytes
92880 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
92881 #define sqlite3_value_double sqlite3_api->value_double
92882 #define sqlite3_value_int sqlite3_api->value_int
92883 #define sqlite3_value_int64 sqlite3_api->value_int64
92884 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
92885 #define sqlite3_value_text sqlite3_api->value_text
92886 #define sqlite3_value_text16 sqlite3_api->value_text16
92887 #define sqlite3_value_text16be sqlite3_api->value_text16be
92888 #define sqlite3_value_text16le sqlite3_api->value_text16le
92889 #define sqlite3_value_type sqlite3_api->value_type
92890 #define sqlite3_vmprintf sqlite3_api->vmprintf
92891 #define sqlite3_overload_function sqlite3_api->overload_function
92892 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
92893 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
92894 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
92895 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
92896 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
92897 #define sqlite3_blob_close sqlite3_api->blob_close
92898 #define sqlite3_blob_open sqlite3_api->blob_open
92899 #define sqlite3_blob_read sqlite3_api->blob_read
92900 #define sqlite3_blob_write sqlite3_api->blob_write
92901 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
92902 #define sqlite3_file_control sqlite3_api->file_control
92903 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
92904 #define sqlite3_memory_used sqlite3_api->memory_used
92905 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
92906 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
92907 #define sqlite3_mutex_free sqlite3_api->mutex_free
92908 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
92909 #define sqlite3_mutex_try sqlite3_api->mutex_try
92910 #define sqlite3_open_v2 sqlite3_api->open_v2
92911 #define sqlite3_release_memory sqlite3_api->release_memory
92912 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
92913 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
92914 #define sqlite3_sleep sqlite3_api->sleep
92915 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
92916 #define sqlite3_vfs_find sqlite3_api->vfs_find
92917 #define sqlite3_vfs_register sqlite3_api->vfs_register
92918 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
92919 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
92920 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
92921 #define sqlite3_result_error_code sqlite3_api->result_error_code
92922 #define sqlite3_test_control sqlite3_api->test_control
92923 #define sqlite3_randomness sqlite3_api->randomness
92924 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
92925 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
92926 #define sqlite3_limit sqlite3_api->limit
92927 #define sqlite3_next_stmt sqlite3_api->next_stmt
92928 #define sqlite3_sql sqlite3_api->sql
92929 #define sqlite3_status sqlite3_api->status
92930 #define sqlite3_backup_finish sqlite3_api->backup_finish
92931 #define sqlite3_backup_init sqlite3_api->backup_init
92932 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
92933 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
92934 #define sqlite3_backup_step sqlite3_api->backup_step
92935 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
92936 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
92937 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
92938 #define sqlite3_db_config sqlite3_api->db_config
92939 #define sqlite3_db_mutex sqlite3_api->db_mutex
92940 #define sqlite3_db_status sqlite3_api->db_status
92941 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
92942 #define sqlite3_log sqlite3_api->log
92943 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
92944 #define sqlite3_sourceid sqlite3_api->sourceid
92945 #define sqlite3_stmt_status sqlite3_api->stmt_status
92946 #define sqlite3_strnicmp sqlite3_api->strnicmp
92947 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
92948 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
92949 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
92950 #define sqlite3_wal_hook sqlite3_api->wal_hook
92951 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
92952 #define sqlite3_vtab_config sqlite3_api->vtab_config
92953 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
92954 /* Version 3.7.16 and later */
92955 #define sqlite3_close_v2 sqlite3_api->close_v2
92956 #define sqlite3_db_filename sqlite3_api->db_filename
92957 #define sqlite3_db_readonly sqlite3_api->db_readonly
92958 #define sqlite3_db_release_memory sqlite3_api->db_release_memory
92959 #define sqlite3_errstr sqlite3_api->errstr
92960 #define sqlite3_stmt_busy sqlite3_api->stmt_busy
92961 #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
92962 #define sqlite3_stricmp sqlite3_api->stricmp
92963 #define sqlite3_uri_boolean sqlite3_api->uri_boolean
92964 #define sqlite3_uri_int64 sqlite3_api->uri_int64
92965 #define sqlite3_uri_parameter sqlite3_api->uri_parameter
92966 #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
92967 #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
92968 #endif /* SQLITE_CORE */
92970 #ifndef SQLITE_CORE
92971 /* This case when the file really is being compiled as a loadable
92972 ** extension */
92973 # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
92974 # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
92975 # define SQLITE_EXTENSION_INIT3 \
92976 extern const sqlite3_api_routines *sqlite3_api;
92977 #else
92978 /* This case when the file is being statically linked into the
92979 ** application */
92980 # define SQLITE_EXTENSION_INIT1 /*no-op*/
92981 # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
92982 # define SQLITE_EXTENSION_INIT3 /*no-op*/
92983 #endif
92985 #endif /* _SQLITE3EXT_H_ */
92987 /************** End of sqlite3ext.h ******************************************/
92988 /************** Continuing where we left off in loadext.c ********************/
92989 /* #include <string.h> */
92991 #ifndef SQLITE_OMIT_LOAD_EXTENSION
92994 ** Some API routines are omitted when various features are
92995 ** excluded from a build of SQLite. Substitute a NULL pointer
92996 ** for any missing APIs.
92998 #ifndef SQLITE_ENABLE_COLUMN_METADATA
92999 # define sqlite3_column_database_name 0
93000 # define sqlite3_column_database_name16 0
93001 # define sqlite3_column_table_name 0
93002 # define sqlite3_column_table_name16 0
93003 # define sqlite3_column_origin_name 0
93004 # define sqlite3_column_origin_name16 0
93005 # define sqlite3_table_column_metadata 0
93006 #endif
93008 #ifdef SQLITE_OMIT_AUTHORIZATION
93009 # define sqlite3_set_authorizer 0
93010 #endif
93012 #ifdef SQLITE_OMIT_UTF16
93013 # define sqlite3_bind_text16 0
93014 # define sqlite3_collation_needed16 0
93015 # define sqlite3_column_decltype16 0
93016 # define sqlite3_column_name16 0
93017 # define sqlite3_column_text16 0
93018 # define sqlite3_complete16 0
93019 # define sqlite3_create_collation16 0
93020 # define sqlite3_create_function16 0
93021 # define sqlite3_errmsg16 0
93022 # define sqlite3_open16 0
93023 # define sqlite3_prepare16 0
93024 # define sqlite3_prepare16_v2 0
93025 # define sqlite3_result_error16 0
93026 # define sqlite3_result_text16 0
93027 # define sqlite3_result_text16be 0
93028 # define sqlite3_result_text16le 0
93029 # define sqlite3_value_text16 0
93030 # define sqlite3_value_text16be 0
93031 # define sqlite3_value_text16le 0
93032 # define sqlite3_column_database_name16 0
93033 # define sqlite3_column_table_name16 0
93034 # define sqlite3_column_origin_name16 0
93035 #endif
93037 #ifdef SQLITE_OMIT_COMPLETE
93038 # define sqlite3_complete 0
93039 # define sqlite3_complete16 0
93040 #endif
93042 #ifdef SQLITE_OMIT_DECLTYPE
93043 # define sqlite3_column_decltype16 0
93044 # define sqlite3_column_decltype 0
93045 #endif
93047 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
93048 # define sqlite3_progress_handler 0
93049 #endif
93051 #ifdef SQLITE_OMIT_VIRTUALTABLE
93052 # define sqlite3_create_module 0
93053 # define sqlite3_create_module_v2 0
93054 # define sqlite3_declare_vtab 0
93055 # define sqlite3_vtab_config 0
93056 # define sqlite3_vtab_on_conflict 0
93057 #endif
93059 #ifdef SQLITE_OMIT_SHARED_CACHE
93060 # define sqlite3_enable_shared_cache 0
93061 #endif
93063 #ifdef SQLITE_OMIT_TRACE
93064 # define sqlite3_profile 0
93065 # define sqlite3_trace 0
93066 #endif
93068 #ifdef SQLITE_OMIT_GET_TABLE
93069 # define sqlite3_free_table 0
93070 # define sqlite3_get_table 0
93071 #endif
93073 #ifdef SQLITE_OMIT_INCRBLOB
93074 #define sqlite3_bind_zeroblob 0
93075 #define sqlite3_blob_bytes 0
93076 #define sqlite3_blob_close 0
93077 #define sqlite3_blob_open 0
93078 #define sqlite3_blob_read 0
93079 #define sqlite3_blob_write 0
93080 #define sqlite3_blob_reopen 0
93081 #endif
93084 ** The following structure contains pointers to all SQLite API routines.
93085 ** A pointer to this structure is passed into extensions when they are
93086 ** loaded so that the extension can make calls back into the SQLite
93087 ** library.
93089 ** When adding new APIs, add them to the bottom of this structure
93090 ** in order to preserve backwards compatibility.
93092 ** Extensions that use newer APIs should first call the
93093 ** sqlite3_libversion_number() to make sure that the API they
93094 ** intend to use is supported by the library. Extensions should
93095 ** also check to make sure that the pointer to the function is
93096 ** not NULL before calling it.
93098 static const sqlite3_api_routines sqlite3Apis = {
93099 sqlite3_aggregate_context,
93100 #ifndef SQLITE_OMIT_DEPRECATED
93101 sqlite3_aggregate_count,
93102 #else
93104 #endif
93105 sqlite3_bind_blob,
93106 sqlite3_bind_double,
93107 sqlite3_bind_int,
93108 sqlite3_bind_int64,
93109 sqlite3_bind_null,
93110 sqlite3_bind_parameter_count,
93111 sqlite3_bind_parameter_index,
93112 sqlite3_bind_parameter_name,
93113 sqlite3_bind_text,
93114 sqlite3_bind_text16,
93115 sqlite3_bind_value,
93116 sqlite3_busy_handler,
93117 sqlite3_busy_timeout,
93118 sqlite3_changes,
93119 sqlite3_close,
93120 sqlite3_collation_needed,
93121 sqlite3_collation_needed16,
93122 sqlite3_column_blob,
93123 sqlite3_column_bytes,
93124 sqlite3_column_bytes16,
93125 sqlite3_column_count,
93126 sqlite3_column_database_name,
93127 sqlite3_column_database_name16,
93128 sqlite3_column_decltype,
93129 sqlite3_column_decltype16,
93130 sqlite3_column_double,
93131 sqlite3_column_int,
93132 sqlite3_column_int64,
93133 sqlite3_column_name,
93134 sqlite3_column_name16,
93135 sqlite3_column_origin_name,
93136 sqlite3_column_origin_name16,
93137 sqlite3_column_table_name,
93138 sqlite3_column_table_name16,
93139 sqlite3_column_text,
93140 sqlite3_column_text16,
93141 sqlite3_column_type,
93142 sqlite3_column_value,
93143 sqlite3_commit_hook,
93144 sqlite3_complete,
93145 sqlite3_complete16,
93146 sqlite3_create_collation,
93147 sqlite3_create_collation16,
93148 sqlite3_create_function,
93149 sqlite3_create_function16,
93150 sqlite3_create_module,
93151 sqlite3_data_count,
93152 sqlite3_db_handle,
93153 sqlite3_declare_vtab,
93154 sqlite3_enable_shared_cache,
93155 sqlite3_errcode,
93156 sqlite3_errmsg,
93157 sqlite3_errmsg16,
93158 sqlite3_exec,
93159 #ifndef SQLITE_OMIT_DEPRECATED
93160 sqlite3_expired,
93161 #else
93163 #endif
93164 sqlite3_finalize,
93165 sqlite3_free,
93166 sqlite3_free_table,
93167 sqlite3_get_autocommit,
93168 sqlite3_get_auxdata,
93169 sqlite3_get_table,
93170 0, /* Was sqlite3_global_recover(), but that function is deprecated */
93171 sqlite3_interrupt,
93172 sqlite3_last_insert_rowid,
93173 sqlite3_libversion,
93174 sqlite3_libversion_number,
93175 sqlite3_malloc,
93176 sqlite3_mprintf,
93177 sqlite3_open,
93178 sqlite3_open16,
93179 sqlite3_prepare,
93180 sqlite3_prepare16,
93181 sqlite3_profile,
93182 sqlite3_progress_handler,
93183 sqlite3_realloc,
93184 sqlite3_reset,
93185 sqlite3_result_blob,
93186 sqlite3_result_double,
93187 sqlite3_result_error,
93188 sqlite3_result_error16,
93189 sqlite3_result_int,
93190 sqlite3_result_int64,
93191 sqlite3_result_null,
93192 sqlite3_result_text,
93193 sqlite3_result_text16,
93194 sqlite3_result_text16be,
93195 sqlite3_result_text16le,
93196 sqlite3_result_value,
93197 sqlite3_rollback_hook,
93198 sqlite3_set_authorizer,
93199 sqlite3_set_auxdata,
93200 sqlite3_snprintf,
93201 sqlite3_step,
93202 sqlite3_table_column_metadata,
93203 #ifndef SQLITE_OMIT_DEPRECATED
93204 sqlite3_thread_cleanup,
93205 #else
93207 #endif
93208 sqlite3_total_changes,
93209 sqlite3_trace,
93210 #ifndef SQLITE_OMIT_DEPRECATED
93211 sqlite3_transfer_bindings,
93212 #else
93214 #endif
93215 sqlite3_update_hook,
93216 sqlite3_user_data,
93217 sqlite3_value_blob,
93218 sqlite3_value_bytes,
93219 sqlite3_value_bytes16,
93220 sqlite3_value_double,
93221 sqlite3_value_int,
93222 sqlite3_value_int64,
93223 sqlite3_value_numeric_type,
93224 sqlite3_value_text,
93225 sqlite3_value_text16,
93226 sqlite3_value_text16be,
93227 sqlite3_value_text16le,
93228 sqlite3_value_type,
93229 sqlite3_vmprintf,
93231 ** The original API set ends here. All extensions can call any
93232 ** of the APIs above provided that the pointer is not NULL. But
93233 ** before calling APIs that follow, extension should check the
93234 ** sqlite3_libversion_number() to make sure they are dealing with
93235 ** a library that is new enough to support that API.
93236 *************************************************************************
93238 sqlite3_overload_function,
93241 ** Added after 3.3.13
93243 sqlite3_prepare_v2,
93244 sqlite3_prepare16_v2,
93245 sqlite3_clear_bindings,
93248 ** Added for 3.4.1
93250 sqlite3_create_module_v2,
93253 ** Added for 3.5.0
93255 sqlite3_bind_zeroblob,
93256 sqlite3_blob_bytes,
93257 sqlite3_blob_close,
93258 sqlite3_blob_open,
93259 sqlite3_blob_read,
93260 sqlite3_blob_write,
93261 sqlite3_create_collation_v2,
93262 sqlite3_file_control,
93263 sqlite3_memory_highwater,
93264 sqlite3_memory_used,
93265 #ifdef SQLITE_MUTEX_OMIT
93271 #else
93272 sqlite3_mutex_alloc,
93273 sqlite3_mutex_enter,
93274 sqlite3_mutex_free,
93275 sqlite3_mutex_leave,
93276 sqlite3_mutex_try,
93277 #endif
93278 sqlite3_open_v2,
93279 sqlite3_release_memory,
93280 sqlite3_result_error_nomem,
93281 sqlite3_result_error_toobig,
93282 sqlite3_sleep,
93283 sqlite3_soft_heap_limit,
93284 sqlite3_vfs_find,
93285 sqlite3_vfs_register,
93286 sqlite3_vfs_unregister,
93289 ** Added for 3.5.8
93291 sqlite3_threadsafe,
93292 sqlite3_result_zeroblob,
93293 sqlite3_result_error_code,
93294 sqlite3_test_control,
93295 sqlite3_randomness,
93296 sqlite3_context_db_handle,
93299 ** Added for 3.6.0
93301 sqlite3_extended_result_codes,
93302 sqlite3_limit,
93303 sqlite3_next_stmt,
93304 sqlite3_sql,
93305 sqlite3_status,
93308 ** Added for 3.7.4
93310 sqlite3_backup_finish,
93311 sqlite3_backup_init,
93312 sqlite3_backup_pagecount,
93313 sqlite3_backup_remaining,
93314 sqlite3_backup_step,
93315 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
93316 sqlite3_compileoption_get,
93317 sqlite3_compileoption_used,
93318 #else
93321 #endif
93322 sqlite3_create_function_v2,
93323 sqlite3_db_config,
93324 sqlite3_db_mutex,
93325 sqlite3_db_status,
93326 sqlite3_extended_errcode,
93327 sqlite3_log,
93328 sqlite3_soft_heap_limit64,
93329 sqlite3_sourceid,
93330 sqlite3_stmt_status,
93331 sqlite3_strnicmp,
93332 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
93333 sqlite3_unlock_notify,
93334 #else
93336 #endif
93337 #ifndef SQLITE_OMIT_WAL
93338 sqlite3_wal_autocheckpoint,
93339 sqlite3_wal_checkpoint,
93340 sqlite3_wal_hook,
93341 #else
93345 #endif
93346 sqlite3_blob_reopen,
93347 sqlite3_vtab_config,
93348 sqlite3_vtab_on_conflict,
93349 sqlite3_close_v2,
93350 sqlite3_db_filename,
93351 sqlite3_db_readonly,
93352 sqlite3_db_release_memory,
93353 sqlite3_errstr,
93354 sqlite3_stmt_busy,
93355 sqlite3_stmt_readonly,
93356 sqlite3_stricmp,
93357 sqlite3_uri_boolean,
93358 sqlite3_uri_int64,
93359 sqlite3_uri_parameter,
93360 sqlite3_vsnprintf,
93361 sqlite3_wal_checkpoint_v2
93365 ** Attempt to load an SQLite extension library contained in the file
93366 ** zFile. The entry point is zProc. zProc may be 0 in which case a
93367 ** default entry point name (sqlite3_extension_init) is used. Use
93368 ** of the default name is recommended.
93370 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
93372 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
93373 ** error message text. The calling function should free this memory
93374 ** by calling sqlite3DbFree(db, ).
93376 static int sqlite3LoadExtension(
93377 sqlite3 *db, /* Load the extension into this database connection */
93378 const char *zFile, /* Name of the shared library containing extension */
93379 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
93380 char **pzErrMsg /* Put error message here if not 0 */
93382 sqlite3_vfs *pVfs = db->pVfs;
93383 void *handle;
93384 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
93385 char *zErrmsg = 0;
93386 const char *zEntry;
93387 char *zAltEntry = 0;
93388 void **aHandle;
93389 int nMsg = 300 + sqlite3Strlen30(zFile);
93390 int ii;
93392 /* Shared library endings to try if zFile cannot be loaded as written */
93393 static const char *azEndings[] = {
93394 #if SQLITE_OS_WIN
93395 "dll"
93396 #elif defined(__APPLE__)
93397 "dylib"
93398 #else
93399 "so"
93400 #endif
93404 if( pzErrMsg ) *pzErrMsg = 0;
93406 /* Ticket #1863. To avoid a creating security problems for older
93407 ** applications that relink against newer versions of SQLite, the
93408 ** ability to run load_extension is turned off by default. One
93409 ** must call sqlite3_enable_load_extension() to turn on extension
93410 ** loading. Otherwise you get the following error.
93412 if( (db->flags & SQLITE_LoadExtension)==0 ){
93413 if( pzErrMsg ){
93414 *pzErrMsg = sqlite3_mprintf("not authorized");
93416 return SQLITE_ERROR;
93419 zEntry = zProc ? zProc : "sqlite3_extension_init";
93421 handle = sqlite3OsDlOpen(pVfs, zFile);
93422 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
93423 for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
93424 char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
93425 if( zAltFile==0 ) return SQLITE_NOMEM;
93426 handle = sqlite3OsDlOpen(pVfs, zAltFile);
93427 sqlite3_free(zAltFile);
93429 #endif
93430 if( handle==0 ){
93431 if( pzErrMsg ){
93432 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
93433 if( zErrmsg ){
93434 sqlite3_snprintf(nMsg, zErrmsg,
93435 "unable to open shared library [%s]", zFile);
93436 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
93439 return SQLITE_ERROR;
93441 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93442 sqlite3OsDlSym(pVfs, handle, zEntry);
93444 /* If no entry point was specified and the default legacy
93445 ** entry point name "sqlite3_extension_init" was not found, then
93446 ** construct an entry point name "sqlite3_X_init" where the X is
93447 ** replaced by the lowercase value of every ASCII alphabetic
93448 ** character in the filename after the last "/" upto the first ".",
93449 ** and eliding the first three characters if they are "lib".
93450 ** Examples:
93452 ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
93453 ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
93455 if( xInit==0 && zProc==0 ){
93456 int iFile, iEntry, c;
93457 int ncFile = sqlite3Strlen30(zFile);
93458 zAltEntry = sqlite3_malloc(ncFile+30);
93459 if( zAltEntry==0 ){
93460 sqlite3OsDlClose(pVfs, handle);
93461 return SQLITE_NOMEM;
93463 memcpy(zAltEntry, "sqlite3_", 8);
93464 for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
93465 iFile++;
93466 if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
93467 for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
93468 if( sqlite3Isalpha(c) ){
93469 zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
93472 memcpy(zAltEntry+iEntry, "_init", 6);
93473 zEntry = zAltEntry;
93474 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93475 sqlite3OsDlSym(pVfs, handle, zEntry);
93477 if( xInit==0 ){
93478 if( pzErrMsg ){
93479 nMsg += sqlite3Strlen30(zEntry);
93480 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
93481 if( zErrmsg ){
93482 sqlite3_snprintf(nMsg, zErrmsg,
93483 "no entry point [%s] in shared library [%s]", zEntry, zFile);
93484 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
93487 sqlite3OsDlClose(pVfs, handle);
93488 sqlite3_free(zAltEntry);
93489 return SQLITE_ERROR;
93491 sqlite3_free(zAltEntry);
93492 if( xInit(db, &zErrmsg, &sqlite3Apis) ){
93493 if( pzErrMsg ){
93494 *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
93496 sqlite3_free(zErrmsg);
93497 sqlite3OsDlClose(pVfs, handle);
93498 return SQLITE_ERROR;
93501 /* Append the new shared library handle to the db->aExtension array. */
93502 aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
93503 if( aHandle==0 ){
93504 return SQLITE_NOMEM;
93506 if( db->nExtension>0 ){
93507 memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
93509 sqlite3DbFree(db, db->aExtension);
93510 db->aExtension = aHandle;
93512 db->aExtension[db->nExtension++] = handle;
93513 return SQLITE_OK;
93515 SQLITE_API int sqlite3_load_extension(
93516 sqlite3 *db, /* Load the extension into this database connection */
93517 const char *zFile, /* Name of the shared library containing extension */
93518 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
93519 char **pzErrMsg /* Put error message here if not 0 */
93521 int rc;
93522 sqlite3_mutex_enter(db->mutex);
93523 rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
93524 rc = sqlite3ApiExit(db, rc);
93525 sqlite3_mutex_leave(db->mutex);
93526 return rc;
93530 ** Call this routine when the database connection is closing in order
93531 ** to clean up loaded extensions
93533 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
93534 int i;
93535 assert( sqlite3_mutex_held(db->mutex) );
93536 for(i=0; i<db->nExtension; i++){
93537 sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
93539 sqlite3DbFree(db, db->aExtension);
93543 ** Enable or disable extension loading. Extension loading is disabled by
93544 ** default so as not to open security holes in older applications.
93546 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
93547 sqlite3_mutex_enter(db->mutex);
93548 if( onoff ){
93549 db->flags |= SQLITE_LoadExtension;
93550 }else{
93551 db->flags &= ~SQLITE_LoadExtension;
93553 sqlite3_mutex_leave(db->mutex);
93554 return SQLITE_OK;
93557 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
93560 ** The auto-extension code added regardless of whether or not extension
93561 ** loading is supported. We need a dummy sqlite3Apis pointer for that
93562 ** code if regular extension loading is not available. This is that
93563 ** dummy pointer.
93565 #ifdef SQLITE_OMIT_LOAD_EXTENSION
93566 static const sqlite3_api_routines sqlite3Apis = { 0 };
93567 #endif
93571 ** The following object holds the list of automatically loaded
93572 ** extensions.
93574 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
93575 ** mutex must be held while accessing this list.
93577 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
93578 static SQLITE_WSD struct sqlite3AutoExtList {
93579 int nExt; /* Number of entries in aExt[] */
93580 void (**aExt)(void); /* Pointers to the extension init functions */
93581 } sqlite3Autoext = { 0, 0 };
93583 /* The "wsdAutoext" macro will resolve to the autoextension
93584 ** state vector. If writable static data is unsupported on the target,
93585 ** we have to locate the state vector at run-time. In the more common
93586 ** case where writable static data is supported, wsdStat can refer directly
93587 ** to the "sqlite3Autoext" state vector declared above.
93589 #ifdef SQLITE_OMIT_WSD
93590 # define wsdAutoextInit \
93591 sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
93592 # define wsdAutoext x[0]
93593 #else
93594 # define wsdAutoextInit
93595 # define wsdAutoext sqlite3Autoext
93596 #endif
93600 ** Register a statically linked extension that is automatically
93601 ** loaded by every new database connection.
93603 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
93604 int rc = SQLITE_OK;
93605 #ifndef SQLITE_OMIT_AUTOINIT
93606 rc = sqlite3_initialize();
93607 if( rc ){
93608 return rc;
93609 }else
93610 #endif
93612 int i;
93613 #if SQLITE_THREADSAFE
93614 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93615 #endif
93616 wsdAutoextInit;
93617 sqlite3_mutex_enter(mutex);
93618 for(i=0; i<wsdAutoext.nExt; i++){
93619 if( wsdAutoext.aExt[i]==xInit ) break;
93621 if( i==wsdAutoext.nExt ){
93622 int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
93623 void (**aNew)(void);
93624 aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
93625 if( aNew==0 ){
93626 rc = SQLITE_NOMEM;
93627 }else{
93628 wsdAutoext.aExt = aNew;
93629 wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
93630 wsdAutoext.nExt++;
93633 sqlite3_mutex_leave(mutex);
93634 assert( (rc&0xff)==rc );
93635 return rc;
93640 ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
93641 ** set of routines that is invoked for each new database connection, if it
93642 ** is currently on the list. If xInit is not on the list, then this
93643 ** routine is a no-op.
93645 ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
93646 ** was not on the list.
93648 SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
93649 #if SQLITE_THREADSAFE
93650 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93651 #endif
93652 int i;
93653 int n = 0;
93654 wsdAutoextInit;
93655 sqlite3_mutex_enter(mutex);
93656 for(i=wsdAutoext.nExt-1; i>=0; i--){
93657 if( wsdAutoext.aExt[i]==xInit ){
93658 wsdAutoext.nExt--;
93659 wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
93660 n++;
93661 break;
93664 sqlite3_mutex_leave(mutex);
93665 return n;
93669 ** Reset the automatic extension loading mechanism.
93671 SQLITE_API void sqlite3_reset_auto_extension(void){
93672 #ifndef SQLITE_OMIT_AUTOINIT
93673 if( sqlite3_initialize()==SQLITE_OK )
93674 #endif
93676 #if SQLITE_THREADSAFE
93677 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93678 #endif
93679 wsdAutoextInit;
93680 sqlite3_mutex_enter(mutex);
93681 sqlite3_free(wsdAutoext.aExt);
93682 wsdAutoext.aExt = 0;
93683 wsdAutoext.nExt = 0;
93684 sqlite3_mutex_leave(mutex);
93689 ** Load all automatic extensions.
93691 ** If anything goes wrong, set an error in the database connection.
93693 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
93694 int i;
93695 int go = 1;
93696 int rc;
93697 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
93699 wsdAutoextInit;
93700 if( wsdAutoext.nExt==0 ){
93701 /* Common case: early out without every having to acquire a mutex */
93702 return;
93704 for(i=0; go; i++){
93705 char *zErrmsg;
93706 #if SQLITE_THREADSAFE
93707 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93708 #endif
93709 sqlite3_mutex_enter(mutex);
93710 if( i>=wsdAutoext.nExt ){
93711 xInit = 0;
93712 go = 0;
93713 }else{
93714 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93715 wsdAutoext.aExt[i];
93717 sqlite3_mutex_leave(mutex);
93718 zErrmsg = 0;
93719 if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
93720 sqlite3Error(db, rc,
93721 "automatic extension loading failed: %s", zErrmsg);
93722 go = 0;
93724 sqlite3_free(zErrmsg);
93728 /************** End of loadext.c *********************************************/
93729 /************** Begin file pragma.c ******************************************/
93731 ** 2003 April 6
93733 ** The author disclaims copyright to this source code. In place of
93734 ** a legal notice, here is a blessing:
93736 ** May you do good and not evil.
93737 ** May you find forgiveness for yourself and forgive others.
93738 ** May you share freely, never taking more than you give.
93740 *************************************************************************
93741 ** This file contains code used to implement the PRAGMA command.
93745 ** Interpret the given string as a safety level. Return 0 for OFF,
93746 ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
93747 ** unrecognized string argument. The FULL option is disallowed
93748 ** if the omitFull parameter it 1.
93750 ** Note that the values returned are one less that the values that
93751 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
93752 ** to support legacy SQL code. The safety level used to be boolean
93753 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
93755 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
93756 /* 123456789 123456789 */
93757 static const char zText[] = "onoffalseyestruefull";
93758 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
93759 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
93760 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
93761 int i, n;
93762 if( sqlite3Isdigit(*z) ){
93763 return (u8)sqlite3Atoi(z);
93765 n = sqlite3Strlen30(z);
93766 for(i=0; i<ArraySize(iLength)-omitFull; i++){
93767 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
93768 return iValue[i];
93771 return dflt;
93775 ** Interpret the given string as a boolean value.
93777 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
93778 return getSafetyLevel(z,1,dflt)!=0;
93781 /* The sqlite3GetBoolean() function is used by other modules but the
93782 ** remainder of this file is specific to PRAGMA processing. So omit
93783 ** the rest of the file if PRAGMAs are omitted from the build.
93785 #if !defined(SQLITE_OMIT_PRAGMA)
93788 ** Interpret the given string as a locking mode value.
93790 static int getLockingMode(const char *z){
93791 if( z ){
93792 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
93793 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
93795 return PAGER_LOCKINGMODE_QUERY;
93798 #ifndef SQLITE_OMIT_AUTOVACUUM
93800 ** Interpret the given string as an auto-vacuum mode value.
93802 ** The following strings, "none", "full" and "incremental" are
93803 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
93805 static int getAutoVacuum(const char *z){
93806 int i;
93807 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
93808 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
93809 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
93810 i = sqlite3Atoi(z);
93811 return (u8)((i>=0&&i<=2)?i:0);
93813 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
93815 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93817 ** Interpret the given string as a temp db location. Return 1 for file
93818 ** backed temporary databases, 2 for the Red-Black tree in memory database
93819 ** and 0 to use the compile-time default.
93821 static int getTempStore(const char *z){
93822 if( z[0]>='0' && z[0]<='2' ){
93823 return z[0] - '0';
93824 }else if( sqlite3StrICmp(z, "file")==0 ){
93825 return 1;
93826 }else if( sqlite3StrICmp(z, "memory")==0 ){
93827 return 2;
93828 }else{
93829 return 0;
93832 #endif /* SQLITE_PAGER_PRAGMAS */
93834 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93836 ** Invalidate temp storage, either when the temp storage is changed
93837 ** from default, or when 'file' and the temp_store_directory has changed
93839 static int invalidateTempStorage(Parse *pParse){
93840 sqlite3 *db = pParse->db;
93841 if( db->aDb[1].pBt!=0 ){
93842 if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
93843 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
93844 "from within a transaction");
93845 return SQLITE_ERROR;
93847 sqlite3BtreeClose(db->aDb[1].pBt);
93848 db->aDb[1].pBt = 0;
93849 sqlite3ResetAllSchemasOfConnection(db);
93851 return SQLITE_OK;
93853 #endif /* SQLITE_PAGER_PRAGMAS */
93855 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93857 ** If the TEMP database is open, close it and mark the database schema
93858 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
93859 ** or DEFAULT_TEMP_STORE pragmas.
93861 static int changeTempStorage(Parse *pParse, const char *zStorageType){
93862 int ts = getTempStore(zStorageType);
93863 sqlite3 *db = pParse->db;
93864 if( db->temp_store==ts ) return SQLITE_OK;
93865 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
93866 return SQLITE_ERROR;
93868 db->temp_store = (u8)ts;
93869 return SQLITE_OK;
93871 #endif /* SQLITE_PAGER_PRAGMAS */
93874 ** Generate code to return a single integer value.
93876 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
93877 Vdbe *v = sqlite3GetVdbe(pParse);
93878 int mem = ++pParse->nMem;
93879 i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
93880 if( pI64 ){
93881 memcpy(pI64, &value, sizeof(value));
93883 sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
93884 sqlite3VdbeSetNumCols(v, 1);
93885 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
93886 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
93891 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
93892 ** set these values for all pagers.
93894 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93895 static void setAllPagerFlags(sqlite3 *db){
93896 if( db->autoCommit ){
93897 Db *pDb = db->aDb;
93898 int n = db->nDb;
93899 assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
93900 assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
93901 assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
93902 assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
93903 == PAGER_FLAGS_MASK );
93904 assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
93905 while( (n--) > 0 ){
93906 if( pDb->pBt ){
93907 sqlite3BtreeSetPagerFlags(pDb->pBt,
93908 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
93910 pDb++;
93914 #else
93915 # define setAllPagerFlags(X) /* no-op */
93916 #endif
93919 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
93921 ** Check to see if zRight and zLeft refer to a pragma that queries
93922 ** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
93923 ** Also, implement the pragma.
93925 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
93926 static const struct sPragmaType {
93927 const char *zName; /* Name of the pragma */
93928 int mask; /* Mask for the db->flags value */
93929 } aPragma[] = {
93930 { "full_column_names", SQLITE_FullColNames },
93931 { "short_column_names", SQLITE_ShortColNames },
93932 { "count_changes", SQLITE_CountRows },
93933 { "empty_result_callbacks", SQLITE_NullCallback },
93934 { "legacy_file_format", SQLITE_LegacyFileFmt },
93935 { "fullfsync", SQLITE_FullFSync },
93936 { "checkpoint_fullfsync", SQLITE_CkptFullFSync },
93937 { "cache_spill", SQLITE_CacheSpill },
93938 { "reverse_unordered_selects", SQLITE_ReverseOrder },
93939 { "query_only", SQLITE_QueryOnly },
93940 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
93941 { "automatic_index", SQLITE_AutoIndex },
93942 #endif
93943 #ifdef SQLITE_DEBUG
93944 { "sql_trace", SQLITE_SqlTrace },
93945 { "vdbe_listing", SQLITE_VdbeListing },
93946 { "vdbe_trace", SQLITE_VdbeTrace },
93947 { "vdbe_addoptrace", SQLITE_VdbeAddopTrace},
93948 { "vdbe_debug", SQLITE_SqlTrace | SQLITE_VdbeListing
93949 | SQLITE_VdbeTrace },
93950 #endif
93951 #ifndef SQLITE_OMIT_CHECK
93952 { "ignore_check_constraints", SQLITE_IgnoreChecks },
93953 #endif
93954 /* The following is VERY experimental */
93955 { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
93957 /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
93958 ** flag if there are any active statements. */
93959 { "read_uncommitted", SQLITE_ReadUncommitted },
93960 { "recursive_triggers", SQLITE_RecTriggers },
93962 /* This flag may only be set if both foreign-key and trigger support
93963 ** are present in the build. */
93964 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
93965 { "foreign_keys", SQLITE_ForeignKeys },
93966 { "defer_foreign_keys", SQLITE_DeferFKs },
93967 #endif
93969 int i;
93970 const struct sPragmaType *p;
93971 for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
93972 if( sqlite3StrICmp(zLeft, p->zName)==0 ){
93973 sqlite3 *db = pParse->db;
93974 Vdbe *v;
93975 v = sqlite3GetVdbe(pParse);
93976 assert( v!=0 ); /* Already allocated by sqlite3Pragma() */
93977 if( ALWAYS(v) ){
93978 if( zRight==0 ){
93979 returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
93980 }else{
93981 int mask = p->mask; /* Mask of bits to set or clear. */
93982 if( db->autoCommit==0 ){
93983 /* Foreign key support may not be enabled or disabled while not
93984 ** in auto-commit mode. */
93985 mask &= ~(SQLITE_ForeignKeys);
93988 if( sqlite3GetBoolean(zRight, 0) ){
93989 db->flags |= mask;
93990 }else{
93991 db->flags &= ~mask;
93992 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
93995 /* Many of the flag-pragmas modify the code generated by the SQL
93996 ** compiler (eg. count_changes). So add an opcode to expire all
93997 ** compiled SQL statements after modifying a pragma value.
93999 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
94003 return 1;
94006 return 0;
94008 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
94011 ** Return a human-readable name for a constraint resolution action.
94013 #ifndef SQLITE_OMIT_FOREIGN_KEY
94014 static const char *actionName(u8 action){
94015 const char *zName;
94016 switch( action ){
94017 case OE_SetNull: zName = "SET NULL"; break;
94018 case OE_SetDflt: zName = "SET DEFAULT"; break;
94019 case OE_Cascade: zName = "CASCADE"; break;
94020 case OE_Restrict: zName = "RESTRICT"; break;
94021 default: zName = "NO ACTION";
94022 assert( action==OE_None ); break;
94024 return zName;
94026 #endif
94030 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
94031 ** defined in pager.h. This function returns the associated lowercase
94032 ** journal-mode name.
94034 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
94035 static char * const azModeName[] = {
94036 "delete", "persist", "off", "truncate", "memory"
94037 #ifndef SQLITE_OMIT_WAL
94038 , "wal"
94039 #endif
94041 assert( PAGER_JOURNALMODE_DELETE==0 );
94042 assert( PAGER_JOURNALMODE_PERSIST==1 );
94043 assert( PAGER_JOURNALMODE_OFF==2 );
94044 assert( PAGER_JOURNALMODE_TRUNCATE==3 );
94045 assert( PAGER_JOURNALMODE_MEMORY==4 );
94046 assert( PAGER_JOURNALMODE_WAL==5 );
94047 assert( eMode>=0 && eMode<=ArraySize(azModeName) );
94049 if( eMode==ArraySize(azModeName) ) return 0;
94050 return azModeName[eMode];
94054 ** Process a pragma statement.
94056 ** Pragmas are of this form:
94058 ** PRAGMA [database.]id [= value]
94060 ** The identifier might also be a string. The value is a string, and
94061 ** identifier, or a number. If minusFlag is true, then the value is
94062 ** a number that was preceded by a minus sign.
94064 ** If the left side is "database.id" then pId1 is the database name
94065 ** and pId2 is the id. If the left side is just "id" then pId1 is the
94066 ** id and pId2 is any empty string.
94068 SQLITE_PRIVATE void sqlite3Pragma(
94069 Parse *pParse,
94070 Token *pId1, /* First part of [database.]id field */
94071 Token *pId2, /* Second part of [database.]id field, or NULL */
94072 Token *pValue, /* Token for <value>, or NULL */
94073 int minusFlag /* True if a '-' sign preceded <value> */
94075 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
94076 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
94077 const char *zDb = 0; /* The database name */
94078 Token *pId; /* Pointer to <id> token */
94079 int iDb; /* Database index for <database> */
94080 char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
94081 int rc; /* return value form SQLITE_FCNTL_PRAGMA */
94082 sqlite3 *db = pParse->db; /* The database connection */
94083 Db *pDb; /* The specific database being pragmaed */
94084 Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
94086 if( v==0 ) return;
94087 sqlite3VdbeRunOnlyOnce(v);
94088 pParse->nMem = 2;
94090 /* Interpret the [database.] part of the pragma statement. iDb is the
94091 ** index of the database this pragma is being applied to in db.aDb[]. */
94092 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
94093 if( iDb<0 ) return;
94094 pDb = &db->aDb[iDb];
94096 /* If the temp database has been explicitly named as part of the
94097 ** pragma, make sure it is open.
94099 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
94100 return;
94103 zLeft = sqlite3NameFromToken(db, pId);
94104 if( !zLeft ) return;
94105 if( minusFlag ){
94106 zRight = sqlite3MPrintf(db, "-%T", pValue);
94107 }else{
94108 zRight = sqlite3NameFromToken(db, pValue);
94111 assert( pId2 );
94112 zDb = pId2->n>0 ? pDb->zName : 0;
94113 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
94114 goto pragma_out;
94117 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
94118 ** connection. If it returns SQLITE_OK, then assume that the VFS
94119 ** handled the pragma and generate a no-op prepared statement.
94121 aFcntl[0] = 0;
94122 aFcntl[1] = zLeft;
94123 aFcntl[2] = zRight;
94124 aFcntl[3] = 0;
94125 db->busyHandler.nBusy = 0;
94126 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
94127 if( rc==SQLITE_OK ){
94128 if( aFcntl[0] ){
94129 int mem = ++pParse->nMem;
94130 sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
94131 sqlite3VdbeSetNumCols(v, 1);
94132 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
94133 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
94134 sqlite3_free(aFcntl[0]);
94136 }else if( rc!=SQLITE_NOTFOUND ){
94137 if( aFcntl[0] ){
94138 sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
94139 sqlite3_free(aFcntl[0]);
94141 pParse->nErr++;
94142 pParse->rc = rc;
94143 }else
94146 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
94148 ** PRAGMA [database.]default_cache_size
94149 ** PRAGMA [database.]default_cache_size=N
94151 ** The first form reports the current persistent setting for the
94152 ** page cache size. The value returned is the maximum number of
94153 ** pages in the page cache. The second form sets both the current
94154 ** page cache size value and the persistent page cache size value
94155 ** stored in the database file.
94157 ** Older versions of SQLite would set the default cache size to a
94158 ** negative number to indicate synchronous=OFF. These days, synchronous
94159 ** is always on by default regardless of the sign of the default cache
94160 ** size. But continue to take the absolute value of the default cache
94161 ** size of historical compatibility.
94163 if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
94164 static const VdbeOpList getCacheSize[] = {
94165 { OP_Transaction, 0, 0, 0}, /* 0 */
94166 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
94167 { OP_IfPos, 1, 8, 0},
94168 { OP_Integer, 0, 2, 0},
94169 { OP_Subtract, 1, 2, 1},
94170 { OP_IfPos, 1, 8, 0},
94171 { OP_Integer, 0, 1, 0}, /* 6 */
94172 { OP_Noop, 0, 0, 0},
94173 { OP_ResultRow, 1, 1, 0},
94175 int addr;
94176 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94177 sqlite3VdbeUsesBtree(v, iDb);
94178 if( !zRight ){
94179 sqlite3VdbeSetNumCols(v, 1);
94180 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
94181 pParse->nMem += 2;
94182 addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
94183 sqlite3VdbeChangeP1(v, addr, iDb);
94184 sqlite3VdbeChangeP1(v, addr+1, iDb);
94185 sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
94186 }else{
94187 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
94188 sqlite3BeginWriteOperation(pParse, 0, iDb);
94189 sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
94190 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
94191 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94192 pDb->pSchema->cache_size = size;
94193 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
94195 }else
94196 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
94198 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
94200 ** PRAGMA [database.]page_size
94201 ** PRAGMA [database.]page_size=N
94203 ** The first form reports the current setting for the
94204 ** database page size in bytes. The second form sets the
94205 ** database page size value. The value can only be set if
94206 ** the database has not yet been created.
94208 if( sqlite3StrICmp(zLeft,"page_size")==0 ){
94209 Btree *pBt = pDb->pBt;
94210 assert( pBt!=0 );
94211 if( !zRight ){
94212 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
94213 returnSingleInt(pParse, "page_size", size);
94214 }else{
94215 /* Malloc may fail when setting the page-size, as there is an internal
94216 ** buffer that the pager module resizes using sqlite3_realloc().
94218 db->nextPagesize = sqlite3Atoi(zRight);
94219 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
94220 db->mallocFailed = 1;
94223 }else
94226 ** PRAGMA [database.]secure_delete
94227 ** PRAGMA [database.]secure_delete=ON/OFF
94229 ** The first form reports the current setting for the
94230 ** secure_delete flag. The second form changes the secure_delete
94231 ** flag setting and reports thenew value.
94233 if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
94234 Btree *pBt = pDb->pBt;
94235 int b = -1;
94236 assert( pBt!=0 );
94237 if( zRight ){
94238 b = sqlite3GetBoolean(zRight, 0);
94240 if( pId2->n==0 && b>=0 ){
94241 int ii;
94242 for(ii=0; ii<db->nDb; ii++){
94243 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
94246 b = sqlite3BtreeSecureDelete(pBt, b);
94247 returnSingleInt(pParse, "secure_delete", b);
94248 }else
94251 ** PRAGMA [database.]max_page_count
94252 ** PRAGMA [database.]max_page_count=N
94254 ** The first form reports the current setting for the
94255 ** maximum number of pages in the database file. The
94256 ** second form attempts to change this setting. Both
94257 ** forms return the current setting.
94259 ** The absolute value of N is used. This is undocumented and might
94260 ** change. The only purpose is to provide an easy way to test
94261 ** the sqlite3AbsInt32() function.
94263 ** PRAGMA [database.]page_count
94265 ** Return the number of pages in the specified database.
94267 if( sqlite3StrICmp(zLeft,"page_count")==0
94268 || sqlite3StrICmp(zLeft,"max_page_count")==0
94270 int iReg;
94271 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94272 sqlite3CodeVerifySchema(pParse, iDb);
94273 iReg = ++pParse->nMem;
94274 if( sqlite3Tolower(zLeft[0])=='p' ){
94275 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
94276 }else{
94277 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
94278 sqlite3AbsInt32(sqlite3Atoi(zRight)));
94280 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
94281 sqlite3VdbeSetNumCols(v, 1);
94282 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
94283 }else
94286 ** PRAGMA [database.]locking_mode
94287 ** PRAGMA [database.]locking_mode = (normal|exclusive)
94289 if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
94290 const char *zRet = "normal";
94291 int eMode = getLockingMode(zRight);
94293 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
94294 /* Simple "PRAGMA locking_mode;" statement. This is a query for
94295 ** the current default locking mode (which may be different to
94296 ** the locking-mode of the main database).
94298 eMode = db->dfltLockMode;
94299 }else{
94300 Pager *pPager;
94301 if( pId2->n==0 ){
94302 /* This indicates that no database name was specified as part
94303 ** of the PRAGMA command. In this case the locking-mode must be
94304 ** set on all attached databases, as well as the main db file.
94306 ** Also, the sqlite3.dfltLockMode variable is set so that
94307 ** any subsequently attached databases also use the specified
94308 ** locking mode.
94310 int ii;
94311 assert(pDb==&db->aDb[0]);
94312 for(ii=2; ii<db->nDb; ii++){
94313 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
94314 sqlite3PagerLockingMode(pPager, eMode);
94316 db->dfltLockMode = (u8)eMode;
94318 pPager = sqlite3BtreePager(pDb->pBt);
94319 eMode = sqlite3PagerLockingMode(pPager, eMode);
94322 assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
94323 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
94324 zRet = "exclusive";
94326 sqlite3VdbeSetNumCols(v, 1);
94327 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
94328 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
94329 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94330 }else
94333 ** PRAGMA [database.]journal_mode
94334 ** PRAGMA [database.]journal_mode =
94335 ** (delete|persist|off|truncate|memory|wal|off)
94337 if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
94338 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
94339 int ii; /* Loop counter */
94341 /* Force the schema to be loaded on all databases. This causes all
94342 ** database files to be opened and the journal_modes set. This is
94343 ** necessary because subsequent processing must know if the databases
94344 ** are in WAL mode. */
94345 if( sqlite3ReadSchema(pParse) ){
94346 goto pragma_out;
94349 sqlite3VdbeSetNumCols(v, 1);
94350 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
94352 if( zRight==0 ){
94353 /* If there is no "=MODE" part of the pragma, do a query for the
94354 ** current mode */
94355 eMode = PAGER_JOURNALMODE_QUERY;
94356 }else{
94357 const char *zMode;
94358 int n = sqlite3Strlen30(zRight);
94359 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
94360 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
94362 if( !zMode ){
94363 /* If the "=MODE" part does not match any known journal mode,
94364 ** then do a query */
94365 eMode = PAGER_JOURNALMODE_QUERY;
94368 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
94369 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
94370 iDb = 0;
94371 pId2->n = 1;
94373 for(ii=db->nDb-1; ii>=0; ii--){
94374 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
94375 sqlite3VdbeUsesBtree(v, ii);
94376 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
94379 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94380 }else
94383 ** PRAGMA [database.]journal_size_limit
94384 ** PRAGMA [database.]journal_size_limit=N
94386 ** Get or set the size limit on rollback journal files.
94388 if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
94389 Pager *pPager = sqlite3BtreePager(pDb->pBt);
94390 i64 iLimit = -2;
94391 if( zRight ){
94392 sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
94393 if( iLimit<-1 ) iLimit = -1;
94395 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
94396 returnSingleInt(pParse, "journal_size_limit", iLimit);
94397 }else
94399 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
94402 ** PRAGMA [database.]auto_vacuum
94403 ** PRAGMA [database.]auto_vacuum=N
94405 ** Get or set the value of the database 'auto-vacuum' parameter.
94406 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
94408 #ifndef SQLITE_OMIT_AUTOVACUUM
94409 if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
94410 Btree *pBt = pDb->pBt;
94411 assert( pBt!=0 );
94412 if( sqlite3ReadSchema(pParse) ){
94413 goto pragma_out;
94415 if( !zRight ){
94416 int auto_vacuum;
94417 if( ALWAYS(pBt) ){
94418 auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
94419 }else{
94420 auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
94422 returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
94423 }else{
94424 int eAuto = getAutoVacuum(zRight);
94425 assert( eAuto>=0 && eAuto<=2 );
94426 db->nextAutovac = (u8)eAuto;
94427 if( ALWAYS(eAuto>=0) ){
94428 /* Call SetAutoVacuum() to set initialize the internal auto and
94429 ** incr-vacuum flags. This is required in case this connection
94430 ** creates the database file. It is important that it is created
94431 ** as an auto-vacuum capable db.
94433 rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
94434 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
94435 /* When setting the auto_vacuum mode to either "full" or
94436 ** "incremental", write the value of meta[6] in the database
94437 ** file. Before writing to meta[6], check that meta[3] indicates
94438 ** that this really is an auto-vacuum capable database.
94440 static const VdbeOpList setMeta6[] = {
94441 { OP_Transaction, 0, 1, 0}, /* 0 */
94442 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
94443 { OP_If, 1, 0, 0}, /* 2 */
94444 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
94445 { OP_Integer, 0, 1, 0}, /* 4 */
94446 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
94448 int iAddr;
94449 iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
94450 sqlite3VdbeChangeP1(v, iAddr, iDb);
94451 sqlite3VdbeChangeP1(v, iAddr+1, iDb);
94452 sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
94453 sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
94454 sqlite3VdbeChangeP1(v, iAddr+5, iDb);
94455 sqlite3VdbeUsesBtree(v, iDb);
94459 }else
94460 #endif
94463 ** PRAGMA [database.]incremental_vacuum(N)
94465 ** Do N steps of incremental vacuuming on a database.
94467 #ifndef SQLITE_OMIT_AUTOVACUUM
94468 if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
94469 int iLimit, addr;
94470 if( sqlite3ReadSchema(pParse) ){
94471 goto pragma_out;
94473 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
94474 iLimit = 0x7fffffff;
94476 sqlite3BeginWriteOperation(pParse, 0, iDb);
94477 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
94478 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
94479 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
94480 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
94481 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
94482 sqlite3VdbeJumpHere(v, addr);
94483 }else
94484 #endif
94486 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
94488 ** PRAGMA [database.]cache_size
94489 ** PRAGMA [database.]cache_size=N
94491 ** The first form reports the current local setting for the
94492 ** page cache size. The second form sets the local
94493 ** page cache size value. If N is positive then that is the
94494 ** number of pages in the cache. If N is negative, then the
94495 ** number of pages is adjusted so that the cache uses -N kibibytes
94496 ** of memory.
94498 if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
94499 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94500 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94501 if( !zRight ){
94502 returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
94503 }else{
94504 int size = sqlite3Atoi(zRight);
94505 pDb->pSchema->cache_size = size;
94506 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
94508 }else
94511 ** PRAGMA [database.]mmap_size(N)
94513 ** Used to set mapping size limit. The mapping size limit is
94514 ** used to limit the aggregate size of all memory mapped regions of the
94515 ** database file. If this parameter is set to zero, then memory mapping
94516 ** is not used at all. If N is negative, then the default memory map
94517 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
94518 ** The parameter N is measured in bytes.
94520 ** This value is advisory. The underlying VFS is free to memory map
94521 ** as little or as much as it wants. Except, if N is set to 0 then the
94522 ** upper layers will never invoke the xFetch interfaces to the VFS.
94524 if( sqlite3StrICmp(zLeft,"mmap_size")==0 ){
94525 sqlite3_int64 sz;
94526 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94527 if( zRight ){
94528 int ii;
94529 sqlite3Atoi64(zRight, &sz, 1000, SQLITE_UTF8);
94530 if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
94531 if( pId2->n==0 ) db->szMmap = sz;
94532 for(ii=db->nDb-1; ii>=0; ii--){
94533 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
94534 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
94538 sz = -1;
94539 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
94540 #if SQLITE_MAX_MMAP_SIZE==0
94541 sz = 0;
94542 #endif
94543 if( rc==SQLITE_OK ){
94544 returnSingleInt(pParse, "mmap_size", sz);
94545 }else if( rc!=SQLITE_NOTFOUND ){
94546 pParse->nErr++;
94547 pParse->rc = rc;
94549 }else
94552 ** PRAGMA temp_store
94553 ** PRAGMA temp_store = "default"|"memory"|"file"
94555 ** Return or set the local value of the temp_store flag. Changing
94556 ** the local value does not make changes to the disk file and the default
94557 ** value will be restored the next time the database is opened.
94559 ** Note that it is possible for the library compile-time options to
94560 ** override this setting
94562 if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
94563 if( !zRight ){
94564 returnSingleInt(pParse, "temp_store", db->temp_store);
94565 }else{
94566 changeTempStorage(pParse, zRight);
94568 }else
94571 ** PRAGMA temp_store_directory
94572 ** PRAGMA temp_store_directory = ""|"directory_name"
94574 ** Return or set the local value of the temp_store_directory flag. Changing
94575 ** the value sets a specific directory to be used for temporary files.
94576 ** Setting to a null string reverts to the default temporary directory search.
94577 ** If temporary directory is changed, then invalidateTempStorage.
94580 if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
94581 if( !zRight ){
94582 if( sqlite3_temp_directory ){
94583 sqlite3VdbeSetNumCols(v, 1);
94584 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
94585 "temp_store_directory", SQLITE_STATIC);
94586 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
94587 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94589 }else{
94590 #ifndef SQLITE_OMIT_WSD
94591 if( zRight[0] ){
94592 int res;
94593 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
94594 if( rc!=SQLITE_OK || res==0 ){
94595 sqlite3ErrorMsg(pParse, "not a writable directory");
94596 goto pragma_out;
94599 if( SQLITE_TEMP_STORE==0
94600 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
94601 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
94603 invalidateTempStorage(pParse);
94605 sqlite3_free(sqlite3_temp_directory);
94606 if( zRight[0] ){
94607 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
94608 }else{
94609 sqlite3_temp_directory = 0;
94611 #endif /* SQLITE_OMIT_WSD */
94613 }else
94615 #if SQLITE_OS_WIN
94617 ** PRAGMA data_store_directory
94618 ** PRAGMA data_store_directory = ""|"directory_name"
94620 ** Return or set the local value of the data_store_directory flag. Changing
94621 ** the value sets a specific directory to be used for database files that
94622 ** were specified with a relative pathname. Setting to a null string reverts
94623 ** to the default database directory, which for database files specified with
94624 ** a relative path will probably be based on the current directory for the
94625 ** process. Database file specified with an absolute path are not impacted
94626 ** by this setting, regardless of its value.
94629 if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
94630 if( !zRight ){
94631 if( sqlite3_data_directory ){
94632 sqlite3VdbeSetNumCols(v, 1);
94633 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
94634 "data_store_directory", SQLITE_STATIC);
94635 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
94636 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94638 }else{
94639 #ifndef SQLITE_OMIT_WSD
94640 if( zRight[0] ){
94641 int res;
94642 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
94643 if( rc!=SQLITE_OK || res==0 ){
94644 sqlite3ErrorMsg(pParse, "not a writable directory");
94645 goto pragma_out;
94648 sqlite3_free(sqlite3_data_directory);
94649 if( zRight[0] ){
94650 sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
94651 }else{
94652 sqlite3_data_directory = 0;
94654 #endif /* SQLITE_OMIT_WSD */
94656 }else
94657 #endif
94659 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
94660 # if defined(__APPLE__)
94661 # define SQLITE_ENABLE_LOCKING_STYLE 1
94662 # else
94663 # define SQLITE_ENABLE_LOCKING_STYLE 0
94664 # endif
94665 #endif
94666 #if SQLITE_ENABLE_LOCKING_STYLE
94668 ** PRAGMA [database.]lock_proxy_file
94669 ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
94671 ** Return or set the value of the lock_proxy_file flag. Changing
94672 ** the value sets a specific file to be used for database access locks.
94675 if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
94676 if( !zRight ){
94677 Pager *pPager = sqlite3BtreePager(pDb->pBt);
94678 char *proxy_file_path = NULL;
94679 sqlite3_file *pFile = sqlite3PagerFile(pPager);
94680 sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
94681 &proxy_file_path);
94683 if( proxy_file_path ){
94684 sqlite3VdbeSetNumCols(v, 1);
94685 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
94686 "lock_proxy_file", SQLITE_STATIC);
94687 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
94688 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94690 }else{
94691 Pager *pPager = sqlite3BtreePager(pDb->pBt);
94692 sqlite3_file *pFile = sqlite3PagerFile(pPager);
94693 int res;
94694 if( zRight[0] ){
94695 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
94696 zRight);
94697 } else {
94698 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
94699 NULL);
94701 if( res!=SQLITE_OK ){
94702 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
94703 goto pragma_out;
94706 }else
94707 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
94710 ** PRAGMA [database.]synchronous
94711 ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
94713 ** Return or set the local value of the synchronous flag. Changing
94714 ** the local value does not make changes to the disk file and the
94715 ** default value will be restored the next time the database is
94716 ** opened.
94718 if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
94719 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94720 if( !zRight ){
94721 returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
94722 }else{
94723 if( !db->autoCommit ){
94724 sqlite3ErrorMsg(pParse,
94725 "Safety level may not be changed inside a transaction");
94726 }else{
94727 pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
94728 setAllPagerFlags(db);
94731 }else
94732 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
94734 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
94735 if( flagPragma(pParse, zLeft, zRight) ){
94736 setAllPagerFlags(db);
94737 }else
94738 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
94740 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
94742 ** PRAGMA table_info(<table>)
94744 ** Return a single row for each column of the named table. The columns of
94745 ** the returned data set are:
94747 ** cid: Column id (numbered from left to right, starting at 0)
94748 ** name: Column name
94749 ** type: Column declaration type.
94750 ** notnull: True if 'NOT NULL' is part of column declaration
94751 ** dflt_value: The default value for the column, if any.
94753 if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
94754 Table *pTab;
94755 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94756 pTab = sqlite3FindTable(db, zRight, zDb);
94757 if( pTab ){
94758 int i, k;
94759 int nHidden = 0;
94760 Column *pCol;
94761 Index *pPk;
94762 for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
94763 sqlite3VdbeSetNumCols(v, 6);
94764 pParse->nMem = 6;
94765 sqlite3CodeVerifySchema(pParse, iDb);
94766 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
94767 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94768 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
94769 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
94770 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
94771 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
94772 sqlite3ViewGetColumnNames(pParse, pTab);
94773 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
94774 if( IsHiddenColumn(pCol) ){
94775 nHidden++;
94776 continue;
94778 sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
94779 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
94780 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94781 pCol->zType ? pCol->zType : "", 0);
94782 sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
94783 if( pCol->zDflt ){
94784 sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
94785 }else{
94786 sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
94788 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
94789 k = 0;
94790 }else if( pPk==0 ){
94791 k = 1;
94792 }else{
94793 for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
94795 sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
94796 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
94799 }else
94801 if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
94802 Index *pIdx;
94803 Table *pTab;
94804 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94805 pIdx = sqlite3FindIndex(db, zRight, zDb);
94806 if( pIdx ){
94807 int i;
94808 pTab = pIdx->pTable;
94809 sqlite3VdbeSetNumCols(v, 3);
94810 pParse->nMem = 3;
94811 sqlite3CodeVerifySchema(pParse, iDb);
94812 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
94813 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
94814 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
94815 for(i=0; i<pIdx->nColumn; i++){
94816 int cnum = pIdx->aiColumn[i];
94817 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94818 sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
94819 assert( pTab->nCol>cnum );
94820 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
94821 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94824 }else
94826 if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
94827 Index *pIdx;
94828 Table *pTab;
94829 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94830 pTab = sqlite3FindTable(db, zRight, zDb);
94831 if( pTab ){
94832 v = sqlite3GetVdbe(pParse);
94833 pIdx = pTab->pIndex;
94834 if( pIdx ){
94835 int i = 0;
94836 sqlite3VdbeSetNumCols(v, 3);
94837 pParse->nMem = 3;
94838 sqlite3CodeVerifySchema(pParse, iDb);
94839 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94840 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94841 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
94842 while(pIdx){
94843 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94844 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
94845 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
94846 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94847 ++i;
94848 pIdx = pIdx->pNext;
94852 }else
94854 if( sqlite3StrICmp(zLeft, "database_list")==0 ){
94855 int i;
94856 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94857 sqlite3VdbeSetNumCols(v, 3);
94858 pParse->nMem = 3;
94859 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94860 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94861 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
94862 for(i=0; i<db->nDb; i++){
94863 if( db->aDb[i].pBt==0 ) continue;
94864 assert( db->aDb[i].zName!=0 );
94865 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94866 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
94867 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94868 sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
94869 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94871 }else
94873 if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
94874 int i = 0;
94875 HashElem *p;
94876 sqlite3VdbeSetNumCols(v, 2);
94877 pParse->nMem = 2;
94878 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94879 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94880 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
94881 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
94882 sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
94883 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
94884 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
94886 }else
94887 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
94889 #ifndef SQLITE_OMIT_FOREIGN_KEY
94890 if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
94891 FKey *pFK;
94892 Table *pTab;
94893 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94894 pTab = sqlite3FindTable(db, zRight, zDb);
94895 if( pTab ){
94896 v = sqlite3GetVdbe(pParse);
94897 pFK = pTab->pFKey;
94898 if( pFK ){
94899 int i = 0;
94900 sqlite3VdbeSetNumCols(v, 8);
94901 pParse->nMem = 8;
94902 sqlite3CodeVerifySchema(pParse, iDb);
94903 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
94904 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
94905 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
94906 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
94907 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
94908 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
94909 sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
94910 sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
94911 while(pFK){
94912 int j;
94913 for(j=0; j<pFK->nCol; j++){
94914 char *zCol = pFK->aCol[j].zCol;
94915 char *zOnDelete = (char *)actionName(pFK->aAction[0]);
94916 char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
94917 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94918 sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
94919 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
94920 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
94921 pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
94922 sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
94923 sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
94924 sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
94925 sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
94926 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
94928 ++i;
94929 pFK = pFK->pNextFrom;
94933 }else
94934 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
94936 #ifndef SQLITE_OMIT_FOREIGN_KEY
94937 #ifndef SQLITE_OMIT_TRIGGER
94938 if( sqlite3StrICmp(zLeft, "foreign_key_check")==0 ){
94939 FKey *pFK; /* A foreign key constraint */
94940 Table *pTab; /* Child table contain "REFERENCES" keyword */
94941 Table *pParent; /* Parent table that child points to */
94942 Index *pIdx; /* Index in the parent table */
94943 int i; /* Loop counter: Foreign key number for pTab */
94944 int j; /* Loop counter: Field of the foreign key */
94945 HashElem *k; /* Loop counter: Next table in schema */
94946 int x; /* result variable */
94947 int regResult; /* 3 registers to hold a result row */
94948 int regKey; /* Register to hold key for checking the FK */
94949 int regRow; /* Registers to hold a row from pTab */
94950 int addrTop; /* Top of a loop checking foreign keys */
94951 int addrOk; /* Jump here if the key is OK */
94952 int *aiCols; /* child to parent column mapping */
94954 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94955 regResult = pParse->nMem+1;
94956 pParse->nMem += 4;
94957 regKey = ++pParse->nMem;
94958 regRow = ++pParse->nMem;
94959 v = sqlite3GetVdbe(pParse);
94960 sqlite3VdbeSetNumCols(v, 4);
94961 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
94962 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
94963 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
94964 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
94965 sqlite3CodeVerifySchema(pParse, iDb);
94966 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
94967 while( k ){
94968 if( zRight ){
94969 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
94970 k = 0;
94971 }else{
94972 pTab = (Table*)sqliteHashData(k);
94973 k = sqliteHashNext(k);
94975 if( pTab==0 || pTab->pFKey==0 ) continue;
94976 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
94977 if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
94978 sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
94979 sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
94980 P4_TRANSIENT);
94981 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
94982 pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
94983 if( pParent==0 ) break;
94984 pIdx = 0;
94985 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
94986 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
94987 if( x==0 ){
94988 if( pIdx==0 ){
94989 sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
94990 }else{
94991 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
94992 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
94993 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
94995 }else{
94996 k = 0;
94997 break;
95000 if( pFK ) break;
95001 if( pParse->nTab<i ) pParse->nTab = i;
95002 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
95003 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
95004 pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
95005 assert( pParent!=0 );
95006 pIdx = 0;
95007 aiCols = 0;
95008 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
95009 assert( x==0 );
95010 addrOk = sqlite3VdbeMakeLabel(v);
95011 if( pIdx==0 ){
95012 int iKey = pFK->aCol[0].iFrom;
95013 assert( iKey>=0 && iKey<pTab->nCol );
95014 if( iKey!=pTab->iPKey ){
95015 sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
95016 sqlite3ColumnDefault(v, pTab, iKey, regRow);
95017 sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
95018 sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
95019 sqlite3VdbeCurrentAddr(v)+3);
95020 }else{
95021 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
95023 sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
95024 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
95025 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
95026 }else{
95027 for(j=0; j<pFK->nCol; j++){
95028 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
95029 aiCols ? aiCols[j] : pFK->aCol[0].iFrom, regRow+j);
95030 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
95032 sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
95033 sqlite3VdbeChangeP4(v, -1,
95034 sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
95035 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
95037 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
95038 sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
95039 pFK->zTo, P4_TRANSIENT);
95040 sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
95041 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
95042 sqlite3VdbeResolveLabel(v, addrOk);
95043 sqlite3DbFree(db, aiCols);
95045 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
95046 sqlite3VdbeJumpHere(v, addrTop);
95048 }else
95049 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
95050 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
95052 #ifndef NDEBUG
95053 if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
95054 if( zRight ){
95055 if( sqlite3GetBoolean(zRight, 0) ){
95056 sqlite3ParserTrace(stderr, "parser: ");
95057 }else{
95058 sqlite3ParserTrace(0, 0);
95061 }else
95062 #endif
95064 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
95065 ** used will be case sensitive or not depending on the RHS.
95067 if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
95068 if( zRight ){
95069 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
95071 }else
95073 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
95074 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
95075 #endif
95077 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
95078 /* Pragma "quick_check" is reduced version of
95079 ** integrity_check designed to detect most database corruption
95080 ** without most of the overhead of a full integrity-check.
95082 if( sqlite3StrICmp(zLeft, "integrity_check")==0
95083 || sqlite3StrICmp(zLeft, "quick_check")==0
95085 int i, j, addr, mxErr;
95087 /* Code that appears at the end of the integrity check. If no error
95088 ** messages have been generated, output OK. Otherwise output the
95089 ** error message
95091 static const VdbeOpList endCode[] = {
95092 { OP_AddImm, 1, 0, 0}, /* 0 */
95093 { OP_IfNeg, 1, 0, 0}, /* 1 */
95094 { OP_String8, 0, 3, 0}, /* 2 */
95095 { OP_ResultRow, 3, 1, 0},
95098 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
95100 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
95101 ** then iDb is set to the index of the database identified by <db>.
95102 ** In this case, the integrity of database iDb only is verified by
95103 ** the VDBE created below.
95105 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
95106 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
95107 ** to -1 here, to indicate that the VDBE should verify the integrity
95108 ** of all attached databases. */
95109 assert( iDb>=0 );
95110 assert( iDb==0 || pId2->z );
95111 if( pId2->z==0 ) iDb = -1;
95113 /* Initialize the VDBE program */
95114 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
95115 pParse->nMem = 6;
95116 sqlite3VdbeSetNumCols(v, 1);
95117 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
95119 /* Set the maximum error count */
95120 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
95121 if( zRight ){
95122 sqlite3GetInt32(zRight, &mxErr);
95123 if( mxErr<=0 ){
95124 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
95127 sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
95129 /* Do an integrity check on each database file */
95130 for(i=0; i<db->nDb; i++){
95131 HashElem *x;
95132 Hash *pTbls;
95133 int cnt = 0;
95135 if( OMIT_TEMPDB && i==1 ) continue;
95136 if( iDb>=0 && i!=iDb ) continue;
95138 sqlite3CodeVerifySchema(pParse, i);
95139 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
95140 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
95141 sqlite3VdbeJumpHere(v, addr);
95143 /* Do an integrity check of the B-Tree
95145 ** Begin by filling registers 2, 3, ... with the root pages numbers
95146 ** for all tables and indices in the database.
95148 assert( sqlite3SchemaMutexHeld(db, i, 0) );
95149 pTbls = &db->aDb[i].pSchema->tblHash;
95150 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
95151 Table *pTab = sqliteHashData(x);
95152 Index *pIdx;
95153 sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
95154 cnt++;
95155 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95156 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
95157 cnt++;
95161 /* Make sure sufficient number of registers have been allocated */
95162 pParse->nMem = MAX( pParse->nMem, cnt+7 );
95164 /* Do the b-tree integrity checks */
95165 sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
95166 sqlite3VdbeChangeP5(v, (u8)i);
95167 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
95168 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
95169 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
95170 P4_DYNAMIC);
95171 sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
95172 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
95173 sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
95174 sqlite3VdbeJumpHere(v, addr);
95176 /* Make sure all the indices are constructed correctly.
95178 for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
95179 Table *pTab = sqliteHashData(x);
95180 Index *pIdx;
95181 int loopTop;
95183 if( pTab->pIndex==0 ) continue;
95184 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
95185 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
95186 sqlite3VdbeJumpHere(v, addr);
95187 sqlite3ExprCacheClear(pParse);
95188 sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
95189 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
95190 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7+j); /* index entries counter */
95192 pParse->nMem = MAX(pParse->nMem, 7+j);
95193 loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0) + 1;
95194 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
95195 int jmp2, jmp3;
95196 int r1;
95197 static const VdbeOpList idxErr[] = {
95198 { OP_AddImm, 1, -1, 0},
95199 { OP_String8, 0, 3, 0}, /* 1 */
95200 { OP_Rowid, 1, 4, 0},
95201 { OP_String8, 0, 5, 0}, /* 3 */
95202 { OP_String8, 0, 6, 0}, /* 4 */
95203 { OP_Concat, 4, 3, 3},
95204 { OP_Concat, 5, 3, 3},
95205 { OP_Concat, 6, 3, 3},
95206 { OP_ResultRow, 3, 1, 0},
95207 { OP_IfPos, 1, 0, 0}, /* 9 */
95208 { OP_Halt, 0, 0, 0},
95210 r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0, &jmp3);
95211 sqlite3VdbeAddOp2(v, OP_AddImm, 7+j, 1); /* increment entry count */
95212 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
95213 addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
95214 sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
95215 sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
95216 sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
95217 sqlite3VdbeJumpHere(v, addr+9);
95218 sqlite3VdbeJumpHere(v, jmp2);
95219 sqlite3VdbeResolveLabel(v, jmp3);
95221 sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop);
95222 sqlite3VdbeJumpHere(v, loopTop-1);
95223 #ifndef SQLITE_OMIT_BTREECOUNT
95224 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
95225 "wrong # of entries in index ", P4_STATIC);
95226 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
95227 addr = sqlite3VdbeCurrentAddr(v);
95228 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2);
95229 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
95230 sqlite3VdbeAddOp2(v, OP_Count, j+2, 3);
95231 sqlite3VdbeAddOp3(v, OP_Eq, 7+j, addr+8, 3);
95232 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
95233 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
95234 sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
95235 sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
95237 #endif /* SQLITE_OMIT_BTREECOUNT */
95240 addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
95241 sqlite3VdbeChangeP2(v, addr, -mxErr);
95242 sqlite3VdbeJumpHere(v, addr+1);
95243 sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
95244 }else
95245 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
95247 #ifndef SQLITE_OMIT_UTF16
95249 ** PRAGMA encoding
95250 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
95252 ** In its first form, this pragma returns the encoding of the main
95253 ** database. If the database is not initialized, it is initialized now.
95255 ** The second form of this pragma is a no-op if the main database file
95256 ** has not already been initialized. In this case it sets the default
95257 ** encoding that will be used for the main database file if a new file
95258 ** is created. If an existing main database file is opened, then the
95259 ** default text encoding for the existing database is used.
95261 ** In all cases new databases created using the ATTACH command are
95262 ** created to use the same default text encoding as the main database. If
95263 ** the main database has not been initialized and/or created when ATTACH
95264 ** is executed, this is done before the ATTACH operation.
95266 ** In the second form this pragma sets the text encoding to be used in
95267 ** new database files created using this database handle. It is only
95268 ** useful if invoked immediately after the main database i
95270 if( sqlite3StrICmp(zLeft, "encoding")==0 ){
95271 static const struct EncName {
95272 char *zName;
95273 u8 enc;
95274 } encnames[] = {
95275 { "UTF8", SQLITE_UTF8 },
95276 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
95277 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
95278 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
95279 { "UTF16le", SQLITE_UTF16LE },
95280 { "UTF16be", SQLITE_UTF16BE },
95281 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
95282 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
95283 { 0, 0 }
95285 const struct EncName *pEnc;
95286 if( !zRight ){ /* "PRAGMA encoding" */
95287 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
95288 sqlite3VdbeSetNumCols(v, 1);
95289 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
95290 sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
95291 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
95292 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
95293 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
95294 sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
95295 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
95296 }else{ /* "PRAGMA encoding = XXX" */
95297 /* Only change the value of sqlite.enc if the database handle is not
95298 ** initialized. If the main database exists, the new sqlite.enc value
95299 ** will be overwritten when the schema is next loaded. If it does not
95300 ** already exists, it will be created to use the new encoding value.
95302 if(
95303 !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
95304 DbHasProperty(db, 0, DB_Empty)
95306 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
95307 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
95308 ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
95309 break;
95312 if( !pEnc->zName ){
95313 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
95317 }else
95318 #endif /* SQLITE_OMIT_UTF16 */
95320 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
95322 ** PRAGMA [database.]schema_version
95323 ** PRAGMA [database.]schema_version = <integer>
95325 ** PRAGMA [database.]user_version
95326 ** PRAGMA [database.]user_version = <integer>
95328 ** PRAGMA [database.]freelist_count = <integer>
95330 ** PRAGMA [database.]application_id
95331 ** PRAGMA [database.]application_id = <integer>
95333 ** The pragma's schema_version and user_version are used to set or get
95334 ** the value of the schema-version and user-version, respectively. Both
95335 ** the schema-version and the user-version are 32-bit signed integers
95336 ** stored in the database header.
95338 ** The schema-cookie is usually only manipulated internally by SQLite. It
95339 ** is incremented by SQLite whenever the database schema is modified (by
95340 ** creating or dropping a table or index). The schema version is used by
95341 ** SQLite each time a query is executed to ensure that the internal cache
95342 ** of the schema used when compiling the SQL query matches the schema of
95343 ** the database against which the compiled query is actually executed.
95344 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
95345 ** the schema-version is potentially dangerous and may lead to program
95346 ** crashes or database corruption. Use with caution!
95348 ** The user-version is not used internally by SQLite. It may be used by
95349 ** applications for any purpose.
95351 if( sqlite3StrICmp(zLeft, "schema_version")==0
95352 || sqlite3StrICmp(zLeft, "user_version")==0
95353 || sqlite3StrICmp(zLeft, "freelist_count")==0
95354 || sqlite3StrICmp(zLeft, "application_id")==0
95356 int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
95357 sqlite3VdbeUsesBtree(v, iDb);
95358 switch( zLeft[0] ){
95359 case 'a': case 'A':
95360 iCookie = BTREE_APPLICATION_ID;
95361 break;
95362 case 'f': case 'F':
95363 iCookie = BTREE_FREE_PAGE_COUNT;
95364 break;
95365 case 's': case 'S':
95366 iCookie = BTREE_SCHEMA_VERSION;
95367 break;
95368 default:
95369 iCookie = BTREE_USER_VERSION;
95370 break;
95373 if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
95374 /* Write the specified cookie value */
95375 static const VdbeOpList setCookie[] = {
95376 { OP_Transaction, 0, 1, 0}, /* 0 */
95377 { OP_Integer, 0, 1, 0}, /* 1 */
95378 { OP_SetCookie, 0, 0, 1}, /* 2 */
95380 int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
95381 sqlite3VdbeChangeP1(v, addr, iDb);
95382 sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
95383 sqlite3VdbeChangeP1(v, addr+2, iDb);
95384 sqlite3VdbeChangeP2(v, addr+2, iCookie);
95385 }else{
95386 /* Read the specified cookie value */
95387 static const VdbeOpList readCookie[] = {
95388 { OP_Transaction, 0, 0, 0}, /* 0 */
95389 { OP_ReadCookie, 0, 1, 0}, /* 1 */
95390 { OP_ResultRow, 1, 1, 0}
95392 int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
95393 sqlite3VdbeChangeP1(v, addr, iDb);
95394 sqlite3VdbeChangeP1(v, addr+1, iDb);
95395 sqlite3VdbeChangeP3(v, addr+1, iCookie);
95396 sqlite3VdbeSetNumCols(v, 1);
95397 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
95399 }else
95400 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
95402 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95404 ** PRAGMA compile_options
95406 ** Return the names of all compile-time options used in this build,
95407 ** one option per row.
95409 if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
95410 int i = 0;
95411 const char *zOpt;
95412 sqlite3VdbeSetNumCols(v, 1);
95413 pParse->nMem = 1;
95414 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
95415 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
95416 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
95417 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
95419 }else
95420 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
95422 #ifndef SQLITE_OMIT_WAL
95424 ** PRAGMA [database.]wal_checkpoint = passive|full|restart
95426 ** Checkpoint the database.
95428 if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
95429 int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
95430 int eMode = SQLITE_CHECKPOINT_PASSIVE;
95431 if( zRight ){
95432 if( sqlite3StrICmp(zRight, "full")==0 ){
95433 eMode = SQLITE_CHECKPOINT_FULL;
95434 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
95435 eMode = SQLITE_CHECKPOINT_RESTART;
95438 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
95439 sqlite3VdbeSetNumCols(v, 3);
95440 pParse->nMem = 3;
95441 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
95442 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
95443 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
95445 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
95446 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
95447 }else
95450 ** PRAGMA wal_autocheckpoint
95451 ** PRAGMA wal_autocheckpoint = N
95453 ** Configure a database connection to automatically checkpoint a database
95454 ** after accumulating N frames in the log. Or query for the current value
95455 ** of N.
95457 if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
95458 if( zRight ){
95459 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
95461 returnSingleInt(pParse, "wal_autocheckpoint",
95462 db->xWalCallback==sqlite3WalDefaultHook ?
95463 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
95464 }else
95465 #endif
95468 ** PRAGMA shrink_memory
95470 ** This pragma attempts to free as much memory as possible from the
95471 ** current database connection.
95473 if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
95474 sqlite3_db_release_memory(db);
95475 }else
95478 ** PRAGMA busy_timeout
95479 ** PRAGMA busy_timeout = N
95481 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
95482 ** if one is set. If no busy handler or a different busy handler is set
95483 ** then 0 is returned. Setting the busy_timeout to 0 or negative
95484 ** disables the timeout.
95486 if( sqlite3StrICmp(zLeft, "busy_timeout")==0 ){
95487 if( zRight ){
95488 sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
95490 returnSingleInt(pParse, "timeout", db->busyTimeout);
95491 }else
95493 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
95495 ** Report the current state of file logs for all databases
95497 if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
95498 static const char *const azLockName[] = {
95499 "unlocked", "shared", "reserved", "pending", "exclusive"
95501 int i;
95502 sqlite3VdbeSetNumCols(v, 2);
95503 pParse->nMem = 2;
95504 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
95505 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
95506 for(i=0; i<db->nDb; i++){
95507 Btree *pBt;
95508 const char *zState = "unknown";
95509 int j;
95510 if( db->aDb[i].zName==0 ) continue;
95511 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
95512 pBt = db->aDb[i].pBt;
95513 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
95514 zState = "closed";
95515 }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
95516 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
95517 zState = azLockName[j];
95519 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
95520 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
95523 }else
95524 #endif
95526 #ifdef SQLITE_HAS_CODEC
95527 if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
95528 sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
95529 }else
95530 if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
95531 sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
95532 }else
95533 if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
95534 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
95535 int i, h1, h2;
95536 char zKey[40];
95537 for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
95538 h1 += 9*(1&(h1>>6));
95539 h2 += 9*(1&(h2>>6));
95540 zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
95542 if( (zLeft[3] & 0xf)==0xb ){
95543 sqlite3_key_v2(db, zDb, zKey, i/2);
95544 }else{
95545 sqlite3_rekey_v2(db, zDb, zKey, i/2);
95547 }else
95548 #endif
95549 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
95550 if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
95551 #ifdef SQLITE_HAS_CODEC
95552 if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
95553 sqlite3_activate_see(&zRight[4]);
95555 #endif
95556 #ifdef SQLITE_ENABLE_CEROD
95557 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
95558 sqlite3_activate_cerod(&zRight[6]);
95560 #endif
95561 }else
95562 #endif
95565 {/* Empty ELSE clause */}
95567 pragma_out:
95568 sqlite3DbFree(db, zLeft);
95569 sqlite3DbFree(db, zRight);
95572 #endif /* SQLITE_OMIT_PRAGMA */
95574 /************** End of pragma.c **********************************************/
95575 /************** Begin file prepare.c *****************************************/
95577 ** 2005 May 25
95579 ** The author disclaims copyright to this source code. In place of
95580 ** a legal notice, here is a blessing:
95582 ** May you do good and not evil.
95583 ** May you find forgiveness for yourself and forgive others.
95584 ** May you share freely, never taking more than you give.
95586 *************************************************************************
95587 ** This file contains the implementation of the sqlite3_prepare()
95588 ** interface, and routines that contribute to loading the database schema
95589 ** from disk.
95593 ** Fill the InitData structure with an error message that indicates
95594 ** that the database is corrupt.
95596 static void corruptSchema(
95597 InitData *pData, /* Initialization context */
95598 const char *zObj, /* Object being parsed at the point of error */
95599 const char *zExtra /* Error information */
95601 sqlite3 *db = pData->db;
95602 if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
95603 if( zObj==0 ) zObj = "?";
95604 sqlite3SetString(pData->pzErrMsg, db,
95605 "malformed database schema (%s)", zObj);
95606 if( zExtra ){
95607 *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
95608 "%s - %s", *pData->pzErrMsg, zExtra);
95611 pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
95615 ** This is the callback routine for the code that initializes the
95616 ** database. See sqlite3Init() below for additional information.
95617 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
95619 ** Each callback contains the following information:
95621 ** argv[0] = name of thing being created
95622 ** argv[1] = root page number for table or index. 0 for trigger or view.
95623 ** argv[2] = SQL text for the CREATE statement.
95626 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
95627 InitData *pData = (InitData*)pInit;
95628 sqlite3 *db = pData->db;
95629 int iDb = pData->iDb;
95631 assert( argc==3 );
95632 UNUSED_PARAMETER2(NotUsed, argc);
95633 assert( sqlite3_mutex_held(db->mutex) );
95634 DbClearProperty(db, iDb, DB_Empty);
95635 if( db->mallocFailed ){
95636 corruptSchema(pData, argv[0], 0);
95637 return 1;
95640 assert( iDb>=0 && iDb<db->nDb );
95641 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
95642 if( argv[1]==0 ){
95643 corruptSchema(pData, argv[0], 0);
95644 }else if( argv[2] && argv[2][0] ){
95645 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
95646 ** But because db->init.busy is set to 1, no VDBE code is generated
95647 ** or executed. All the parser does is build the internal data
95648 ** structures that describe the table, index, or view.
95650 int rc;
95651 sqlite3_stmt *pStmt;
95652 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
95654 assert( db->init.busy );
95655 db->init.iDb = iDb;
95656 db->init.newTnum = sqlite3Atoi(argv[1]);
95657 db->init.orphanTrigger = 0;
95658 TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
95659 rc = db->errCode;
95660 assert( (rc&0xFF)==(rcp&0xFF) );
95661 db->init.iDb = 0;
95662 if( SQLITE_OK!=rc ){
95663 if( db->init.orphanTrigger ){
95664 assert( iDb==1 );
95665 }else{
95666 pData->rc = rc;
95667 if( rc==SQLITE_NOMEM ){
95668 db->mallocFailed = 1;
95669 }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
95670 corruptSchema(pData, argv[0], sqlite3_errmsg(db));
95674 sqlite3_finalize(pStmt);
95675 }else if( argv[0]==0 ){
95676 corruptSchema(pData, 0, 0);
95677 }else{
95678 /* If the SQL column is blank it means this is an index that
95679 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
95680 ** constraint for a CREATE TABLE. The index should have already
95681 ** been created when we processed the CREATE TABLE. All we have
95682 ** to do here is record the root page number for that index.
95684 Index *pIndex;
95685 pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
95686 if( pIndex==0 ){
95687 /* This can occur if there exists an index on a TEMP table which
95688 ** has the same name as another index on a permanent index. Since
95689 ** the permanent table is hidden by the TEMP table, we can also
95690 ** safely ignore the index on the permanent table.
95692 /* Do Nothing */;
95693 }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
95694 corruptSchema(pData, argv[0], "invalid rootpage");
95697 return 0;
95701 ** Attempt to read the database schema and initialize internal
95702 ** data structures for a single database file. The index of the
95703 ** database file is given by iDb. iDb==0 is used for the main
95704 ** database. iDb==1 should never be used. iDb>=2 is used for
95705 ** auxiliary databases. Return one of the SQLITE_ error codes to
95706 ** indicate success or failure.
95708 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
95709 int rc;
95710 int i;
95711 #ifndef SQLITE_OMIT_DEPRECATED
95712 int size;
95713 #endif
95714 Table *pTab;
95715 Db *pDb;
95716 char const *azArg[4];
95717 int meta[5];
95718 InitData initData;
95719 char const *zMasterSchema;
95720 char const *zMasterName;
95721 int openedTransaction = 0;
95724 ** The master database table has a structure like this
95726 static const char master_schema[] =
95727 "CREATE TABLE sqlite_master(\n"
95728 " type text,\n"
95729 " name text,\n"
95730 " tbl_name text,\n"
95731 " rootpage integer,\n"
95732 " sql text\n"
95735 #ifndef SQLITE_OMIT_TEMPDB
95736 static const char temp_master_schema[] =
95737 "CREATE TEMP TABLE sqlite_temp_master(\n"
95738 " type text,\n"
95739 " name text,\n"
95740 " tbl_name text,\n"
95741 " rootpage integer,\n"
95742 " sql text\n"
95745 #else
95746 #define temp_master_schema 0
95747 #endif
95749 assert( iDb>=0 && iDb<db->nDb );
95750 assert( db->aDb[iDb].pSchema );
95751 assert( sqlite3_mutex_held(db->mutex) );
95752 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
95754 /* zMasterSchema and zInitScript are set to point at the master schema
95755 ** and initialisation script appropriate for the database being
95756 ** initialized. zMasterName is the name of the master table.
95758 if( !OMIT_TEMPDB && iDb==1 ){
95759 zMasterSchema = temp_master_schema;
95760 }else{
95761 zMasterSchema = master_schema;
95763 zMasterName = SCHEMA_TABLE(iDb);
95765 /* Construct the schema tables. */
95766 azArg[0] = zMasterName;
95767 azArg[1] = "1";
95768 azArg[2] = zMasterSchema;
95769 azArg[3] = 0;
95770 initData.db = db;
95771 initData.iDb = iDb;
95772 initData.rc = SQLITE_OK;
95773 initData.pzErrMsg = pzErrMsg;
95774 sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
95775 if( initData.rc ){
95776 rc = initData.rc;
95777 goto error_out;
95779 pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
95780 if( ALWAYS(pTab) ){
95781 pTab->tabFlags |= TF_Readonly;
95784 /* Create a cursor to hold the database open
95786 pDb = &db->aDb[iDb];
95787 if( pDb->pBt==0 ){
95788 if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
95789 DbSetProperty(db, 1, DB_SchemaLoaded);
95791 return SQLITE_OK;
95794 /* If there is not already a read-only (or read-write) transaction opened
95795 ** on the b-tree database, open one now. If a transaction is opened, it
95796 ** will be closed before this function returns. */
95797 sqlite3BtreeEnter(pDb->pBt);
95798 if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
95799 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
95800 if( rc!=SQLITE_OK ){
95801 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
95802 goto initone_error_out;
95804 openedTransaction = 1;
95807 /* Get the database meta information.
95809 ** Meta values are as follows:
95810 ** meta[0] Schema cookie. Changes with each schema change.
95811 ** meta[1] File format of schema layer.
95812 ** meta[2] Size of the page cache.
95813 ** meta[3] Largest rootpage (auto/incr_vacuum mode)
95814 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
95815 ** meta[5] User version
95816 ** meta[6] Incremental vacuum mode
95817 ** meta[7] unused
95818 ** meta[8] unused
95819 ** meta[9] unused
95821 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
95822 ** the possible values of meta[4].
95824 for(i=0; i<ArraySize(meta); i++){
95825 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
95827 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
95829 /* If opening a non-empty database, check the text encoding. For the
95830 ** main database, set sqlite3.enc to the encoding of the main database.
95831 ** For an attached db, it is an error if the encoding is not the same
95832 ** as sqlite3.enc.
95834 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
95835 if( iDb==0 ){
95836 #ifndef SQLITE_OMIT_UTF16
95837 u8 encoding;
95838 /* If opening the main database, set ENC(db). */
95839 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
95840 if( encoding==0 ) encoding = SQLITE_UTF8;
95841 ENC(db) = encoding;
95842 #else
95843 ENC(db) = SQLITE_UTF8;
95844 #endif
95845 }else{
95846 /* If opening an attached database, the encoding much match ENC(db) */
95847 if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
95848 sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
95849 " text encoding as main database");
95850 rc = SQLITE_ERROR;
95851 goto initone_error_out;
95854 }else{
95855 DbSetProperty(db, iDb, DB_Empty);
95857 pDb->pSchema->enc = ENC(db);
95859 if( pDb->pSchema->cache_size==0 ){
95860 #ifndef SQLITE_OMIT_DEPRECATED
95861 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
95862 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
95863 pDb->pSchema->cache_size = size;
95864 #else
95865 pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
95866 #endif
95867 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
95871 ** file_format==1 Version 3.0.0.
95872 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
95873 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
95874 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
95876 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
95877 if( pDb->pSchema->file_format==0 ){
95878 pDb->pSchema->file_format = 1;
95880 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
95881 sqlite3SetString(pzErrMsg, db, "unsupported file format");
95882 rc = SQLITE_ERROR;
95883 goto initone_error_out;
95886 /* Ticket #2804: When we open a database in the newer file format,
95887 ** clear the legacy_file_format pragma flag so that a VACUUM will
95888 ** not downgrade the database and thus invalidate any descending
95889 ** indices that the user might have created.
95891 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
95892 db->flags &= ~SQLITE_LegacyFileFmt;
95895 /* Read the schema information out of the schema tables
95897 assert( db->init.busy );
95899 char *zSql;
95900 zSql = sqlite3MPrintf(db,
95901 "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
95902 db->aDb[iDb].zName, zMasterName);
95903 #ifndef SQLITE_OMIT_AUTHORIZATION
95905 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
95906 xAuth = db->xAuth;
95907 db->xAuth = 0;
95908 #endif
95909 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
95910 #ifndef SQLITE_OMIT_AUTHORIZATION
95911 db->xAuth = xAuth;
95913 #endif
95914 if( rc==SQLITE_OK ) rc = initData.rc;
95915 sqlite3DbFree(db, zSql);
95916 #ifndef SQLITE_OMIT_ANALYZE
95917 if( rc==SQLITE_OK ){
95918 sqlite3AnalysisLoad(db, iDb);
95920 #endif
95922 if( db->mallocFailed ){
95923 rc = SQLITE_NOMEM;
95924 sqlite3ResetAllSchemasOfConnection(db);
95926 if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
95927 /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
95928 ** the schema loaded, even if errors occurred. In this situation the
95929 ** current sqlite3_prepare() operation will fail, but the following one
95930 ** will attempt to compile the supplied statement against whatever subset
95931 ** of the schema was loaded before the error occurred. The primary
95932 ** purpose of this is to allow access to the sqlite_master table
95933 ** even when its contents have been corrupted.
95935 DbSetProperty(db, iDb, DB_SchemaLoaded);
95936 rc = SQLITE_OK;
95939 /* Jump here for an error that occurs after successfully allocating
95940 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
95941 ** before that point, jump to error_out.
95943 initone_error_out:
95944 if( openedTransaction ){
95945 sqlite3BtreeCommit(pDb->pBt);
95947 sqlite3BtreeLeave(pDb->pBt);
95949 error_out:
95950 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
95951 db->mallocFailed = 1;
95953 return rc;
95957 ** Initialize all database files - the main database file, the file
95958 ** used to store temporary tables, and any additional database files
95959 ** created using ATTACH statements. Return a success code. If an
95960 ** error occurs, write an error message into *pzErrMsg.
95962 ** After a database is initialized, the DB_SchemaLoaded bit is set
95963 ** bit is set in the flags field of the Db structure. If the database
95964 ** file was of zero-length, then the DB_Empty flag is also set.
95966 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
95967 int i, rc;
95968 int commit_internal = !(db->flags&SQLITE_InternChanges);
95970 assert( sqlite3_mutex_held(db->mutex) );
95971 rc = SQLITE_OK;
95972 db->init.busy = 1;
95973 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
95974 if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
95975 rc = sqlite3InitOne(db, i, pzErrMsg);
95976 if( rc ){
95977 sqlite3ResetOneSchema(db, i);
95981 /* Once all the other databases have been initialized, load the schema
95982 ** for the TEMP database. This is loaded last, as the TEMP database
95983 ** schema may contain references to objects in other databases.
95985 #ifndef SQLITE_OMIT_TEMPDB
95986 if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
95987 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
95988 rc = sqlite3InitOne(db, 1, pzErrMsg);
95989 if( rc ){
95990 sqlite3ResetOneSchema(db, 1);
95993 #endif
95995 db->init.busy = 0;
95996 if( rc==SQLITE_OK && commit_internal ){
95997 sqlite3CommitInternalChanges(db);
96000 return rc;
96004 ** This routine is a no-op if the database schema is already initialized.
96005 ** Otherwise, the schema is loaded. An error code is returned.
96007 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
96008 int rc = SQLITE_OK;
96009 sqlite3 *db = pParse->db;
96010 assert( sqlite3_mutex_held(db->mutex) );
96011 if( !db->init.busy ){
96012 rc = sqlite3Init(db, &pParse->zErrMsg);
96014 if( rc!=SQLITE_OK ){
96015 pParse->rc = rc;
96016 pParse->nErr++;
96018 return rc;
96023 ** Check schema cookies in all databases. If any cookie is out
96024 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
96025 ** make no changes to pParse->rc.
96027 static void schemaIsValid(Parse *pParse){
96028 sqlite3 *db = pParse->db;
96029 int iDb;
96030 int rc;
96031 int cookie;
96033 assert( pParse->checkSchema );
96034 assert( sqlite3_mutex_held(db->mutex) );
96035 for(iDb=0; iDb<db->nDb; iDb++){
96036 int openedTransaction = 0; /* True if a transaction is opened */
96037 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
96038 if( pBt==0 ) continue;
96040 /* If there is not already a read-only (or read-write) transaction opened
96041 ** on the b-tree database, open one now. If a transaction is opened, it
96042 ** will be closed immediately after reading the meta-value. */
96043 if( !sqlite3BtreeIsInReadTrans(pBt) ){
96044 rc = sqlite3BtreeBeginTrans(pBt, 0);
96045 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
96046 db->mallocFailed = 1;
96048 if( rc!=SQLITE_OK ) return;
96049 openedTransaction = 1;
96052 /* Read the schema cookie from the database. If it does not match the
96053 ** value stored as part of the in-memory schema representation,
96054 ** set Parse.rc to SQLITE_SCHEMA. */
96055 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
96056 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96057 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
96058 sqlite3ResetOneSchema(db, iDb);
96059 pParse->rc = SQLITE_SCHEMA;
96062 /* Close the transaction, if one was opened. */
96063 if( openedTransaction ){
96064 sqlite3BtreeCommit(pBt);
96070 ** Convert a schema pointer into the iDb index that indicates
96071 ** which database file in db->aDb[] the schema refers to.
96073 ** If the same database is attached more than once, the first
96074 ** attached database is returned.
96076 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
96077 int i = -1000000;
96079 /* If pSchema is NULL, then return -1000000. This happens when code in
96080 ** expr.c is trying to resolve a reference to a transient table (i.e. one
96081 ** created by a sub-select). In this case the return value of this
96082 ** function should never be used.
96084 ** We return -1000000 instead of the more usual -1 simply because using
96085 ** -1000000 as the incorrect index into db->aDb[] is much
96086 ** more likely to cause a segfault than -1 (of course there are assert()
96087 ** statements too, but it never hurts to play the odds).
96089 assert( sqlite3_mutex_held(db->mutex) );
96090 if( pSchema ){
96091 for(i=0; ALWAYS(i<db->nDb); i++){
96092 if( db->aDb[i].pSchema==pSchema ){
96093 break;
96096 assert( i>=0 && i<db->nDb );
96098 return i;
96102 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
96104 static int sqlite3Prepare(
96105 sqlite3 *db, /* Database handle. */
96106 const char *zSql, /* UTF-8 encoded SQL statement. */
96107 int nBytes, /* Length of zSql in bytes. */
96108 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
96109 Vdbe *pReprepare, /* VM being reprepared */
96110 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
96111 const char **pzTail /* OUT: End of parsed string */
96113 Parse *pParse; /* Parsing context */
96114 char *zErrMsg = 0; /* Error message */
96115 int rc = SQLITE_OK; /* Result code */
96116 int i; /* Loop counter */
96118 /* Allocate the parsing context */
96119 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
96120 if( pParse==0 ){
96121 rc = SQLITE_NOMEM;
96122 goto end_prepare;
96124 pParse->pReprepare = pReprepare;
96125 assert( ppStmt && *ppStmt==0 );
96126 assert( !db->mallocFailed );
96127 assert( sqlite3_mutex_held(db->mutex) );
96129 /* Check to verify that it is possible to get a read lock on all
96130 ** database schemas. The inability to get a read lock indicates that
96131 ** some other database connection is holding a write-lock, which in
96132 ** turn means that the other connection has made uncommitted changes
96133 ** to the schema.
96135 ** Were we to proceed and prepare the statement against the uncommitted
96136 ** schema changes and if those schema changes are subsequently rolled
96137 ** back and different changes are made in their place, then when this
96138 ** prepared statement goes to run the schema cookie would fail to detect
96139 ** the schema change. Disaster would follow.
96141 ** This thread is currently holding mutexes on all Btrees (because
96142 ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
96143 ** is not possible for another thread to start a new schema change
96144 ** while this routine is running. Hence, we do not need to hold
96145 ** locks on the schema, we just need to make sure nobody else is
96146 ** holding them.
96148 ** Note that setting READ_UNCOMMITTED overrides most lock detection,
96149 ** but it does *not* override schema lock detection, so this all still
96150 ** works even if READ_UNCOMMITTED is set.
96152 for(i=0; i<db->nDb; i++) {
96153 Btree *pBt = db->aDb[i].pBt;
96154 if( pBt ){
96155 assert( sqlite3BtreeHoldsMutex(pBt) );
96156 rc = sqlite3BtreeSchemaLocked(pBt);
96157 if( rc ){
96158 const char *zDb = db->aDb[i].zName;
96159 sqlite3Error(db, rc, "database schema is locked: %s", zDb);
96160 testcase( db->flags & SQLITE_ReadUncommitted );
96161 goto end_prepare;
96166 sqlite3VtabUnlockList(db);
96168 pParse->db = db;
96169 pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
96170 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
96171 char *zSqlCopy;
96172 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
96173 testcase( nBytes==mxLen );
96174 testcase( nBytes==mxLen+1 );
96175 if( nBytes>mxLen ){
96176 sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
96177 rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
96178 goto end_prepare;
96180 zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
96181 if( zSqlCopy ){
96182 sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
96183 sqlite3DbFree(db, zSqlCopy);
96184 pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
96185 }else{
96186 pParse->zTail = &zSql[nBytes];
96188 }else{
96189 sqlite3RunParser(pParse, zSql, &zErrMsg);
96191 assert( 0==pParse->nQueryLoop );
96193 if( db->mallocFailed ){
96194 pParse->rc = SQLITE_NOMEM;
96196 if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
96197 if( pParse->checkSchema ){
96198 schemaIsValid(pParse);
96200 if( db->mallocFailed ){
96201 pParse->rc = SQLITE_NOMEM;
96203 if( pzTail ){
96204 *pzTail = pParse->zTail;
96206 rc = pParse->rc;
96208 #ifndef SQLITE_OMIT_EXPLAIN
96209 if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
96210 static const char * const azColName[] = {
96211 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
96212 "selectid", "order", "from", "detail"
96214 int iFirst, mx;
96215 if( pParse->explain==2 ){
96216 sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
96217 iFirst = 8;
96218 mx = 12;
96219 }else{
96220 sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
96221 iFirst = 0;
96222 mx = 8;
96224 for(i=iFirst; i<mx; i++){
96225 sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
96226 azColName[i], SQLITE_STATIC);
96229 #endif
96231 if( db->init.busy==0 ){
96232 Vdbe *pVdbe = pParse->pVdbe;
96233 sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
96235 if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
96236 sqlite3VdbeFinalize(pParse->pVdbe);
96237 assert(!(*ppStmt));
96238 }else{
96239 *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
96242 if( zErrMsg ){
96243 sqlite3Error(db, rc, "%s", zErrMsg);
96244 sqlite3DbFree(db, zErrMsg);
96245 }else{
96246 sqlite3Error(db, rc, 0);
96249 /* Delete any TriggerPrg structures allocated while parsing this statement. */
96250 while( pParse->pTriggerPrg ){
96251 TriggerPrg *pT = pParse->pTriggerPrg;
96252 pParse->pTriggerPrg = pT->pNext;
96253 sqlite3DbFree(db, pT);
96256 end_prepare:
96258 sqlite3StackFree(db, pParse);
96259 rc = sqlite3ApiExit(db, rc);
96260 assert( (rc&db->errMask)==rc );
96261 return rc;
96263 static int sqlite3LockAndPrepare(
96264 sqlite3 *db, /* Database handle. */
96265 const char *zSql, /* UTF-8 encoded SQL statement. */
96266 int nBytes, /* Length of zSql in bytes. */
96267 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
96268 Vdbe *pOld, /* VM being reprepared */
96269 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
96270 const char **pzTail /* OUT: End of parsed string */
96272 int rc;
96273 assert( ppStmt!=0 );
96274 *ppStmt = 0;
96275 if( !sqlite3SafetyCheckOk(db) ){
96276 return SQLITE_MISUSE_BKPT;
96278 sqlite3_mutex_enter(db->mutex);
96279 sqlite3BtreeEnterAll(db);
96280 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
96281 if( rc==SQLITE_SCHEMA ){
96282 sqlite3_finalize(*ppStmt);
96283 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
96285 sqlite3BtreeLeaveAll(db);
96286 sqlite3_mutex_leave(db->mutex);
96287 assert( rc==SQLITE_OK || *ppStmt==0 );
96288 return rc;
96292 ** Rerun the compilation of a statement after a schema change.
96294 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
96295 ** if the statement cannot be recompiled because another connection has
96296 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
96297 ** occurs, return SQLITE_SCHEMA.
96299 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
96300 int rc;
96301 sqlite3_stmt *pNew;
96302 const char *zSql;
96303 sqlite3 *db;
96305 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
96306 zSql = sqlite3_sql((sqlite3_stmt *)p);
96307 assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
96308 db = sqlite3VdbeDb(p);
96309 assert( sqlite3_mutex_held(db->mutex) );
96310 rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
96311 if( rc ){
96312 if( rc==SQLITE_NOMEM ){
96313 db->mallocFailed = 1;
96315 assert( pNew==0 );
96316 return rc;
96317 }else{
96318 assert( pNew!=0 );
96320 sqlite3VdbeSwap((Vdbe*)pNew, p);
96321 sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
96322 sqlite3VdbeResetStepResult((Vdbe*)pNew);
96323 sqlite3VdbeFinalize((Vdbe*)pNew);
96324 return SQLITE_OK;
96329 ** Two versions of the official API. Legacy and new use. In the legacy
96330 ** version, the original SQL text is not saved in the prepared statement
96331 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
96332 ** sqlite3_step(). In the new version, the original SQL text is retained
96333 ** and the statement is automatically recompiled if an schema change
96334 ** occurs.
96336 SQLITE_API int sqlite3_prepare(
96337 sqlite3 *db, /* Database handle. */
96338 const char *zSql, /* UTF-8 encoded SQL statement. */
96339 int nBytes, /* Length of zSql in bytes. */
96340 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
96341 const char **pzTail /* OUT: End of parsed string */
96343 int rc;
96344 rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
96345 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
96346 return rc;
96348 SQLITE_API int sqlite3_prepare_v2(
96349 sqlite3 *db, /* Database handle. */
96350 const char *zSql, /* UTF-8 encoded SQL statement. */
96351 int nBytes, /* Length of zSql in bytes. */
96352 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
96353 const char **pzTail /* OUT: End of parsed string */
96355 int rc;
96356 rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
96357 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
96358 return rc;
96362 #ifndef SQLITE_OMIT_UTF16
96364 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
96366 static int sqlite3Prepare16(
96367 sqlite3 *db, /* Database handle. */
96368 const void *zSql, /* UTF-16 encoded SQL statement. */
96369 int nBytes, /* Length of zSql in bytes. */
96370 int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
96371 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
96372 const void **pzTail /* OUT: End of parsed string */
96374 /* This function currently works by first transforming the UTF-16
96375 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
96376 ** tricky bit is figuring out the pointer to return in *pzTail.
96378 char *zSql8;
96379 const char *zTail8 = 0;
96380 int rc = SQLITE_OK;
96382 assert( ppStmt );
96383 *ppStmt = 0;
96384 if( !sqlite3SafetyCheckOk(db) ){
96385 return SQLITE_MISUSE_BKPT;
96387 if( nBytes>=0 ){
96388 int sz;
96389 const char *z = (const char*)zSql;
96390 for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
96391 nBytes = sz;
96393 sqlite3_mutex_enter(db->mutex);
96394 zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
96395 if( zSql8 ){
96396 rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
96399 if( zTail8 && pzTail ){
96400 /* If sqlite3_prepare returns a tail pointer, we calculate the
96401 ** equivalent pointer into the UTF-16 string by counting the unicode
96402 ** characters between zSql8 and zTail8, and then returning a pointer
96403 ** the same number of characters into the UTF-16 string.
96405 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
96406 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
96408 sqlite3DbFree(db, zSql8);
96409 rc = sqlite3ApiExit(db, rc);
96410 sqlite3_mutex_leave(db->mutex);
96411 return rc;
96415 ** Two versions of the official API. Legacy and new use. In the legacy
96416 ** version, the original SQL text is not saved in the prepared statement
96417 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
96418 ** sqlite3_step(). In the new version, the original SQL text is retained
96419 ** and the statement is automatically recompiled if an schema change
96420 ** occurs.
96422 SQLITE_API int sqlite3_prepare16(
96423 sqlite3 *db, /* Database handle. */
96424 const void *zSql, /* UTF-16 encoded SQL statement. */
96425 int nBytes, /* Length of zSql in bytes. */
96426 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
96427 const void **pzTail /* OUT: End of parsed string */
96429 int rc;
96430 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
96431 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
96432 return rc;
96434 SQLITE_API int sqlite3_prepare16_v2(
96435 sqlite3 *db, /* Database handle. */
96436 const void *zSql, /* UTF-16 encoded SQL statement. */
96437 int nBytes, /* Length of zSql in bytes. */
96438 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
96439 const void **pzTail /* OUT: End of parsed string */
96441 int rc;
96442 rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
96443 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
96444 return rc;
96447 #endif /* SQLITE_OMIT_UTF16 */
96449 /************** End of prepare.c *********************************************/
96450 /************** Begin file select.c ******************************************/
96452 ** 2001 September 15
96454 ** The author disclaims copyright to this source code. In place of
96455 ** a legal notice, here is a blessing:
96457 ** May you do good and not evil.
96458 ** May you find forgiveness for yourself and forgive others.
96459 ** May you share freely, never taking more than you give.
96461 *************************************************************************
96462 ** This file contains C code routines that are called by the parser
96463 ** to handle SELECT statements in SQLite.
96468 ** Delete all the content of a Select structure but do not deallocate
96469 ** the select structure itself.
96471 static void clearSelect(sqlite3 *db, Select *p){
96472 sqlite3ExprListDelete(db, p->pEList);
96473 sqlite3SrcListDelete(db, p->pSrc);
96474 sqlite3ExprDelete(db, p->pWhere);
96475 sqlite3ExprListDelete(db, p->pGroupBy);
96476 sqlite3ExprDelete(db, p->pHaving);
96477 sqlite3ExprListDelete(db, p->pOrderBy);
96478 sqlite3SelectDelete(db, p->pPrior);
96479 sqlite3ExprDelete(db, p->pLimit);
96480 sqlite3ExprDelete(db, p->pOffset);
96484 ** Initialize a SelectDest structure.
96486 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
96487 pDest->eDest = (u8)eDest;
96488 pDest->iSDParm = iParm;
96489 pDest->affSdst = 0;
96490 pDest->iSdst = 0;
96491 pDest->nSdst = 0;
96496 ** Allocate a new Select structure and return a pointer to that
96497 ** structure.
96499 SQLITE_PRIVATE Select *sqlite3SelectNew(
96500 Parse *pParse, /* Parsing context */
96501 ExprList *pEList, /* which columns to include in the result */
96502 SrcList *pSrc, /* the FROM clause -- which tables to scan */
96503 Expr *pWhere, /* the WHERE clause */
96504 ExprList *pGroupBy, /* the GROUP BY clause */
96505 Expr *pHaving, /* the HAVING clause */
96506 ExprList *pOrderBy, /* the ORDER BY clause */
96507 u16 selFlags, /* Flag parameters, such as SF_Distinct */
96508 Expr *pLimit, /* LIMIT value. NULL means not used */
96509 Expr *pOffset /* OFFSET value. NULL means no offset */
96511 Select *pNew;
96512 Select standin;
96513 sqlite3 *db = pParse->db;
96514 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
96515 assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
96516 if( pNew==0 ){
96517 assert( db->mallocFailed );
96518 pNew = &standin;
96519 memset(pNew, 0, sizeof(*pNew));
96521 if( pEList==0 ){
96522 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
96524 pNew->pEList = pEList;
96525 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
96526 pNew->pSrc = pSrc;
96527 pNew->pWhere = pWhere;
96528 pNew->pGroupBy = pGroupBy;
96529 pNew->pHaving = pHaving;
96530 pNew->pOrderBy = pOrderBy;
96531 pNew->selFlags = selFlags;
96532 pNew->op = TK_SELECT;
96533 pNew->pLimit = pLimit;
96534 pNew->pOffset = pOffset;
96535 assert( pOffset==0 || pLimit!=0 );
96536 pNew->addrOpenEphm[0] = -1;
96537 pNew->addrOpenEphm[1] = -1;
96538 pNew->addrOpenEphm[2] = -1;
96539 if( db->mallocFailed ) {
96540 clearSelect(db, pNew);
96541 if( pNew!=&standin ) sqlite3DbFree(db, pNew);
96542 pNew = 0;
96543 }else{
96544 assert( pNew->pSrc!=0 || pParse->nErr>0 );
96546 assert( pNew!=&standin );
96547 return pNew;
96551 ** Delete the given Select structure and all of its substructures.
96553 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
96554 if( p ){
96555 clearSelect(db, p);
96556 sqlite3DbFree(db, p);
96561 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
96562 ** type of join. Return an integer constant that expresses that type
96563 ** in terms of the following bit values:
96565 ** JT_INNER
96566 ** JT_CROSS
96567 ** JT_OUTER
96568 ** JT_NATURAL
96569 ** JT_LEFT
96570 ** JT_RIGHT
96572 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
96574 ** If an illegal or unsupported join type is seen, then still return
96575 ** a join type, but put an error in the pParse structure.
96577 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
96578 int jointype = 0;
96579 Token *apAll[3];
96580 Token *p;
96581 /* 0123456789 123456789 123456789 123 */
96582 static const char zKeyText[] = "naturaleftouterightfullinnercross";
96583 static const struct {
96584 u8 i; /* Beginning of keyword text in zKeyText[] */
96585 u8 nChar; /* Length of the keyword in characters */
96586 u8 code; /* Join type mask */
96587 } aKeyword[] = {
96588 /* natural */ { 0, 7, JT_NATURAL },
96589 /* left */ { 6, 4, JT_LEFT|JT_OUTER },
96590 /* outer */ { 10, 5, JT_OUTER },
96591 /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
96592 /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
96593 /* inner */ { 23, 5, JT_INNER },
96594 /* cross */ { 28, 5, JT_INNER|JT_CROSS },
96596 int i, j;
96597 apAll[0] = pA;
96598 apAll[1] = pB;
96599 apAll[2] = pC;
96600 for(i=0; i<3 && apAll[i]; i++){
96601 p = apAll[i];
96602 for(j=0; j<ArraySize(aKeyword); j++){
96603 if( p->n==aKeyword[j].nChar
96604 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
96605 jointype |= aKeyword[j].code;
96606 break;
96609 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
96610 if( j>=ArraySize(aKeyword) ){
96611 jointype |= JT_ERROR;
96612 break;
96616 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
96617 (jointype & JT_ERROR)!=0
96619 const char *zSp = " ";
96620 assert( pB!=0 );
96621 if( pC==0 ){ zSp++; }
96622 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
96623 "%T %T%s%T", pA, pB, zSp, pC);
96624 jointype = JT_INNER;
96625 }else if( (jointype & JT_OUTER)!=0
96626 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
96627 sqlite3ErrorMsg(pParse,
96628 "RIGHT and FULL OUTER JOINs are not currently supported");
96629 jointype = JT_INNER;
96631 return jointype;
96635 ** Return the index of a column in a table. Return -1 if the column
96636 ** is not contained in the table.
96638 static int columnIndex(Table *pTab, const char *zCol){
96639 int i;
96640 for(i=0; i<pTab->nCol; i++){
96641 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
96643 return -1;
96647 ** Search the first N tables in pSrc, from left to right, looking for a
96648 ** table that has a column named zCol.
96650 ** When found, set *piTab and *piCol to the table index and column index
96651 ** of the matching column and return TRUE.
96653 ** If not found, return FALSE.
96655 static int tableAndColumnIndex(
96656 SrcList *pSrc, /* Array of tables to search */
96657 int N, /* Number of tables in pSrc->a[] to search */
96658 const char *zCol, /* Name of the column we are looking for */
96659 int *piTab, /* Write index of pSrc->a[] here */
96660 int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
96662 int i; /* For looping over tables in pSrc */
96663 int iCol; /* Index of column matching zCol */
96665 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
96666 for(i=0; i<N; i++){
96667 iCol = columnIndex(pSrc->a[i].pTab, zCol);
96668 if( iCol>=0 ){
96669 if( piTab ){
96670 *piTab = i;
96671 *piCol = iCol;
96673 return 1;
96676 return 0;
96680 ** This function is used to add terms implied by JOIN syntax to the
96681 ** WHERE clause expression of a SELECT statement. The new term, which
96682 ** is ANDed with the existing WHERE clause, is of the form:
96684 ** (tab1.col1 = tab2.col2)
96686 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
96687 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
96688 ** column iColRight of tab2.
96690 static void addWhereTerm(
96691 Parse *pParse, /* Parsing context */
96692 SrcList *pSrc, /* List of tables in FROM clause */
96693 int iLeft, /* Index of first table to join in pSrc */
96694 int iColLeft, /* Index of column in first table */
96695 int iRight, /* Index of second table in pSrc */
96696 int iColRight, /* Index of column in second table */
96697 int isOuterJoin, /* True if this is an OUTER join */
96698 Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
96700 sqlite3 *db = pParse->db;
96701 Expr *pE1;
96702 Expr *pE2;
96703 Expr *pEq;
96705 assert( iLeft<iRight );
96706 assert( pSrc->nSrc>iRight );
96707 assert( pSrc->a[iLeft].pTab );
96708 assert( pSrc->a[iRight].pTab );
96710 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
96711 pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
96713 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
96714 if( pEq && isOuterJoin ){
96715 ExprSetProperty(pEq, EP_FromJoin);
96716 assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
96717 ExprSetIrreducible(pEq);
96718 pEq->iRightJoinTable = (i16)pE2->iTable;
96720 *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
96724 ** Set the EP_FromJoin property on all terms of the given expression.
96725 ** And set the Expr.iRightJoinTable to iTable for every term in the
96726 ** expression.
96728 ** The EP_FromJoin property is used on terms of an expression to tell
96729 ** the LEFT OUTER JOIN processing logic that this term is part of the
96730 ** join restriction specified in the ON or USING clause and not a part
96731 ** of the more general WHERE clause. These terms are moved over to the
96732 ** WHERE clause during join processing but we need to remember that they
96733 ** originated in the ON or USING clause.
96735 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
96736 ** expression depends on table iRightJoinTable even if that table is not
96737 ** explicitly mentioned in the expression. That information is needed
96738 ** for cases like this:
96740 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
96742 ** The where clause needs to defer the handling of the t1.x=5
96743 ** term until after the t2 loop of the join. In that way, a
96744 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
96745 ** defer the handling of t1.x=5, it will be processed immediately
96746 ** after the t1 loop and rows with t1.x!=5 will never appear in
96747 ** the output, which is incorrect.
96749 static void setJoinExpr(Expr *p, int iTable){
96750 while( p ){
96751 ExprSetProperty(p, EP_FromJoin);
96752 assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
96753 ExprSetIrreducible(p);
96754 p->iRightJoinTable = (i16)iTable;
96755 setJoinExpr(p->pLeft, iTable);
96756 p = p->pRight;
96761 ** This routine processes the join information for a SELECT statement.
96762 ** ON and USING clauses are converted into extra terms of the WHERE clause.
96763 ** NATURAL joins also create extra WHERE clause terms.
96765 ** The terms of a FROM clause are contained in the Select.pSrc structure.
96766 ** The left most table is the first entry in Select.pSrc. The right-most
96767 ** table is the last entry. The join operator is held in the entry to
96768 ** the left. Thus entry 0 contains the join operator for the join between
96769 ** entries 0 and 1. Any ON or USING clauses associated with the join are
96770 ** also attached to the left entry.
96772 ** This routine returns the number of errors encountered.
96774 static int sqliteProcessJoin(Parse *pParse, Select *p){
96775 SrcList *pSrc; /* All tables in the FROM clause */
96776 int i, j; /* Loop counters */
96777 struct SrcList_item *pLeft; /* Left table being joined */
96778 struct SrcList_item *pRight; /* Right table being joined */
96780 pSrc = p->pSrc;
96781 pLeft = &pSrc->a[0];
96782 pRight = &pLeft[1];
96783 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
96784 Table *pLeftTab = pLeft->pTab;
96785 Table *pRightTab = pRight->pTab;
96786 int isOuter;
96788 if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
96789 isOuter = (pRight->jointype & JT_OUTER)!=0;
96791 /* When the NATURAL keyword is present, add WHERE clause terms for
96792 ** every column that the two tables have in common.
96794 if( pRight->jointype & JT_NATURAL ){
96795 if( pRight->pOn || pRight->pUsing ){
96796 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
96797 "an ON or USING clause", 0);
96798 return 1;
96800 for(j=0; j<pRightTab->nCol; j++){
96801 char *zName; /* Name of column in the right table */
96802 int iLeft; /* Matching left table */
96803 int iLeftCol; /* Matching column in the left table */
96805 zName = pRightTab->aCol[j].zName;
96806 if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
96807 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
96808 isOuter, &p->pWhere);
96813 /* Disallow both ON and USING clauses in the same join
96815 if( pRight->pOn && pRight->pUsing ){
96816 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
96817 "clauses in the same join");
96818 return 1;
96821 /* Add the ON clause to the end of the WHERE clause, connected by
96822 ** an AND operator.
96824 if( pRight->pOn ){
96825 if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
96826 p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
96827 pRight->pOn = 0;
96830 /* Create extra terms on the WHERE clause for each column named
96831 ** in the USING clause. Example: If the two tables to be joined are
96832 ** A and B and the USING clause names X, Y, and Z, then add this
96833 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
96834 ** Report an error if any column mentioned in the USING clause is
96835 ** not contained in both tables to be joined.
96837 if( pRight->pUsing ){
96838 IdList *pList = pRight->pUsing;
96839 for(j=0; j<pList->nId; j++){
96840 char *zName; /* Name of the term in the USING clause */
96841 int iLeft; /* Table on the left with matching column name */
96842 int iLeftCol; /* Column number of matching column on the left */
96843 int iRightCol; /* Column number of matching column on the right */
96845 zName = pList->a[j].zName;
96846 iRightCol = columnIndex(pRightTab, zName);
96847 if( iRightCol<0
96848 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
96850 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
96851 "not present in both tables", zName);
96852 return 1;
96854 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
96855 isOuter, &p->pWhere);
96859 return 0;
96863 ** Insert code into "v" that will push the record on the top of the
96864 ** stack into the sorter.
96866 static void pushOntoSorter(
96867 Parse *pParse, /* Parser context */
96868 ExprList *pOrderBy, /* The ORDER BY clause */
96869 Select *pSelect, /* The whole SELECT statement */
96870 int regData /* Register holding data to be sorted */
96872 Vdbe *v = pParse->pVdbe;
96873 int nExpr = pOrderBy->nExpr;
96874 int regBase = sqlite3GetTempRange(pParse, nExpr+2);
96875 int regRecord = sqlite3GetTempReg(pParse);
96876 int op;
96877 sqlite3ExprCacheClear(pParse);
96878 sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
96879 sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
96880 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
96881 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
96882 if( pSelect->selFlags & SF_UseSorter ){
96883 op = OP_SorterInsert;
96884 }else{
96885 op = OP_IdxInsert;
96887 sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
96888 sqlite3ReleaseTempReg(pParse, regRecord);
96889 sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
96890 if( pSelect->iLimit ){
96891 int addr1, addr2;
96892 int iLimit;
96893 if( pSelect->iOffset ){
96894 iLimit = pSelect->iOffset+1;
96895 }else{
96896 iLimit = pSelect->iLimit;
96898 addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
96899 sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
96900 addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
96901 sqlite3VdbeJumpHere(v, addr1);
96902 sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
96903 sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
96904 sqlite3VdbeJumpHere(v, addr2);
96909 ** Add code to implement the OFFSET
96911 static void codeOffset(
96912 Vdbe *v, /* Generate code into this VM */
96913 Select *p, /* The SELECT statement being coded */
96914 int iContinue /* Jump here to skip the current record */
96916 if( p->iOffset && iContinue!=0 ){
96917 int addr;
96918 sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
96919 addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
96920 sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
96921 VdbeComment((v, "skip OFFSET records"));
96922 sqlite3VdbeJumpHere(v, addr);
96927 ** Add code that will check to make sure the N registers starting at iMem
96928 ** form a distinct entry. iTab is a sorting index that holds previously
96929 ** seen combinations of the N values. A new entry is made in iTab
96930 ** if the current N values are new.
96932 ** A jump to addrRepeat is made and the N+1 values are popped from the
96933 ** stack if the top N elements are not distinct.
96935 static void codeDistinct(
96936 Parse *pParse, /* Parsing and code generating context */
96937 int iTab, /* A sorting index used to test for distinctness */
96938 int addrRepeat, /* Jump to here if not distinct */
96939 int N, /* Number of elements */
96940 int iMem /* First element */
96942 Vdbe *v;
96943 int r1;
96945 v = pParse->pVdbe;
96946 r1 = sqlite3GetTempReg(pParse);
96947 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
96948 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
96949 sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
96950 sqlite3ReleaseTempReg(pParse, r1);
96953 #ifndef SQLITE_OMIT_SUBQUERY
96955 ** Generate an error message when a SELECT is used within a subexpression
96956 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
96957 ** column. We do this in a subroutine because the error used to occur
96958 ** in multiple places. (The error only occurs in one place now, but we
96959 ** retain the subroutine to minimize code disruption.)
96961 static int checkForMultiColumnSelectError(
96962 Parse *pParse, /* Parse context. */
96963 SelectDest *pDest, /* Destination of SELECT results */
96964 int nExpr /* Number of result columns returned by SELECT */
96966 int eDest = pDest->eDest;
96967 if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
96968 sqlite3ErrorMsg(pParse, "only a single result allowed for "
96969 "a SELECT that is part of an expression");
96970 return 1;
96971 }else{
96972 return 0;
96975 #endif
96978 ** An instance of the following object is used to record information about
96979 ** how to process the DISTINCT keyword, to simplify passing that information
96980 ** into the selectInnerLoop() routine.
96982 typedef struct DistinctCtx DistinctCtx;
96983 struct DistinctCtx {
96984 u8 isTnct; /* True if the DISTINCT keyword is present */
96985 u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
96986 int tabTnct; /* Ephemeral table used for DISTINCT processing */
96987 int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
96991 ** This routine generates the code for the inside of the inner loop
96992 ** of a SELECT.
96994 ** If srcTab and nColumn are both zero, then the pEList expressions
96995 ** are evaluated in order to get the data for this row. If nColumn>0
96996 ** then data is pulled from srcTab and pEList is used only to get the
96997 ** datatypes for each column.
96999 static void selectInnerLoop(
97000 Parse *pParse, /* The parser context */
97001 Select *p, /* The complete select statement being coded */
97002 ExprList *pEList, /* List of values being extracted */
97003 int srcTab, /* Pull data from this table */
97004 int nColumn, /* Number of columns in the source table */
97005 ExprList *pOrderBy, /* If not NULL, sort results using this key */
97006 DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
97007 SelectDest *pDest, /* How to dispose of the results */
97008 int iContinue, /* Jump here to continue with next row */
97009 int iBreak /* Jump here to break out of the inner loop */
97011 Vdbe *v = pParse->pVdbe;
97012 int i;
97013 int hasDistinct; /* True if the DISTINCT keyword is present */
97014 int regResult; /* Start of memory holding result set */
97015 int eDest = pDest->eDest; /* How to dispose of results */
97016 int iParm = pDest->iSDParm; /* First argument to disposal method */
97017 int nResultCol; /* Number of result columns */
97019 assert( v );
97020 if( NEVER(v==0) ) return;
97021 assert( pEList!=0 );
97022 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
97023 if( pOrderBy==0 && !hasDistinct ){
97024 codeOffset(v, p, iContinue);
97027 /* Pull the requested columns.
97029 if( nColumn>0 ){
97030 nResultCol = nColumn;
97031 }else{
97032 nResultCol = pEList->nExpr;
97034 if( pDest->iSdst==0 ){
97035 pDest->iSdst = pParse->nMem+1;
97036 pDest->nSdst = nResultCol;
97037 pParse->nMem += nResultCol;
97038 }else{
97039 assert( pDest->nSdst==nResultCol );
97041 regResult = pDest->iSdst;
97042 if( nColumn>0 ){
97043 for(i=0; i<nColumn; i++){
97044 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
97046 }else if( eDest!=SRT_Exists ){
97047 /* If the destination is an EXISTS(...) expression, the actual
97048 ** values returned by the SELECT are not required.
97050 sqlite3ExprCacheClear(pParse);
97051 sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
97053 nColumn = nResultCol;
97055 /* If the DISTINCT keyword was present on the SELECT statement
97056 ** and this row has been seen before, then do not make this row
97057 ** part of the result.
97059 if( hasDistinct ){
97060 assert( pEList!=0 );
97061 assert( pEList->nExpr==nColumn );
97062 switch( pDistinct->eTnctType ){
97063 case WHERE_DISTINCT_ORDERED: {
97064 VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
97065 int iJump; /* Jump destination */
97066 int regPrev; /* Previous row content */
97068 /* Allocate space for the previous row */
97069 regPrev = pParse->nMem+1;
97070 pParse->nMem += nColumn;
97072 /* Change the OP_OpenEphemeral coded earlier to an OP_Null
97073 ** sets the MEM_Cleared bit on the first register of the
97074 ** previous value. This will cause the OP_Ne below to always
97075 ** fail on the first iteration of the loop even if the first
97076 ** row is all NULLs.
97078 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
97079 pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
97080 pOp->opcode = OP_Null;
97081 pOp->p1 = 1;
97082 pOp->p2 = regPrev;
97084 iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
97085 for(i=0; i<nColumn; i++){
97086 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
97087 if( i<nColumn-1 ){
97088 sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
97089 }else{
97090 sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
97092 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
97093 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
97095 assert( sqlite3VdbeCurrentAddr(v)==iJump );
97096 sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
97097 break;
97100 case WHERE_DISTINCT_UNIQUE: {
97101 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
97102 break;
97105 default: {
97106 assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
97107 codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
97108 break;
97111 if( pOrderBy==0 ){
97112 codeOffset(v, p, iContinue);
97116 switch( eDest ){
97117 /* In this mode, write each query result to the key of the temporary
97118 ** table iParm.
97120 #ifndef SQLITE_OMIT_COMPOUND_SELECT
97121 case SRT_Union: {
97122 int r1;
97123 r1 = sqlite3GetTempReg(pParse);
97124 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
97125 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
97126 sqlite3ReleaseTempReg(pParse, r1);
97127 break;
97130 /* Construct a record from the query result, but instead of
97131 ** saving that record, use it as a key to delete elements from
97132 ** the temporary table iParm.
97134 case SRT_Except: {
97135 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
97136 break;
97138 #endif
97140 /* Store the result as data using a unique key.
97142 case SRT_Table:
97143 case SRT_EphemTab: {
97144 int r1 = sqlite3GetTempReg(pParse);
97145 testcase( eDest==SRT_Table );
97146 testcase( eDest==SRT_EphemTab );
97147 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
97148 if( pOrderBy ){
97149 pushOntoSorter(pParse, pOrderBy, p, r1);
97150 }else{
97151 int r2 = sqlite3GetTempReg(pParse);
97152 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
97153 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
97154 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
97155 sqlite3ReleaseTempReg(pParse, r2);
97157 sqlite3ReleaseTempReg(pParse, r1);
97158 break;
97161 #ifndef SQLITE_OMIT_SUBQUERY
97162 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
97163 ** then there should be a single item on the stack. Write this
97164 ** item into the set table with bogus data.
97166 case SRT_Set: {
97167 assert( nColumn==1 );
97168 pDest->affSdst =
97169 sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
97170 if( pOrderBy ){
97171 /* At first glance you would think we could optimize out the
97172 ** ORDER BY in this case since the order of entries in the set
97173 ** does not matter. But there might be a LIMIT clause, in which
97174 ** case the order does matter */
97175 pushOntoSorter(pParse, pOrderBy, p, regResult);
97176 }else{
97177 int r1 = sqlite3GetTempReg(pParse);
97178 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
97179 sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
97180 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
97181 sqlite3ReleaseTempReg(pParse, r1);
97183 break;
97186 /* If any row exist in the result set, record that fact and abort.
97188 case SRT_Exists: {
97189 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
97190 /* The LIMIT clause will terminate the loop for us */
97191 break;
97194 /* If this is a scalar select that is part of an expression, then
97195 ** store the results in the appropriate memory cell and break out
97196 ** of the scan loop.
97198 case SRT_Mem: {
97199 assert( nColumn==1 );
97200 if( pOrderBy ){
97201 pushOntoSorter(pParse, pOrderBy, p, regResult);
97202 }else{
97203 sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
97204 /* The LIMIT clause will jump out of the loop for us */
97206 break;
97208 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
97210 /* Send the data to the callback function or to a subroutine. In the
97211 ** case of a subroutine, the subroutine itself is responsible for
97212 ** popping the data from the stack.
97214 case SRT_Coroutine:
97215 case SRT_Output: {
97216 testcase( eDest==SRT_Coroutine );
97217 testcase( eDest==SRT_Output );
97218 if( pOrderBy ){
97219 int r1 = sqlite3GetTempReg(pParse);
97220 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
97221 pushOntoSorter(pParse, pOrderBy, p, r1);
97222 sqlite3ReleaseTempReg(pParse, r1);
97223 }else if( eDest==SRT_Coroutine ){
97224 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
97225 }else{
97226 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
97227 sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
97229 break;
97232 #if !defined(SQLITE_OMIT_TRIGGER)
97233 /* Discard the results. This is used for SELECT statements inside
97234 ** the body of a TRIGGER. The purpose of such selects is to call
97235 ** user-defined functions that have side effects. We do not care
97236 ** about the actual results of the select.
97238 default: {
97239 assert( eDest==SRT_Discard );
97240 break;
97242 #endif
97245 /* Jump to the end of the loop if the LIMIT is reached. Except, if
97246 ** there is a sorter, in which case the sorter has already limited
97247 ** the output for us.
97249 if( pOrderBy==0 && p->iLimit ){
97250 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
97255 ** Allocate a KeyInfo object sufficient for an index of N columns.
97257 ** Actually, always allocate one extra column for the rowid at the end
97258 ** of the index. So the KeyInfo returned will have space sufficient for
97259 ** N+1 columns.
97261 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){
97262 KeyInfo *p = sqlite3DbMallocZero(db,
97263 sizeof(KeyInfo) + (N+1)*(sizeof(CollSeq*)+1));
97264 if( p ){
97265 p->aSortOrder = (u8*)&p->aColl[N+1];
97266 p->nField = (u16)N;
97267 p->enc = ENC(db);
97268 p->db = db;
97270 return p;
97274 ** Given an expression list, generate a KeyInfo structure that records
97275 ** the collating sequence for each expression in that expression list.
97277 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
97278 ** KeyInfo structure is appropriate for initializing a virtual index to
97279 ** implement that clause. If the ExprList is the result set of a SELECT
97280 ** then the KeyInfo structure is appropriate for initializing a virtual
97281 ** index to implement a DISTINCT test.
97283 ** Space to hold the KeyInfo structure is obtain from malloc. The calling
97284 ** function is responsible for seeing that this structure is eventually
97285 ** freed. Add the KeyInfo structure to the P4 field of an opcode using
97286 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
97288 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
97289 int nExpr;
97290 KeyInfo *pInfo;
97291 struct ExprList_item *pItem;
97292 sqlite3 *db = pParse->db;
97293 int i;
97295 nExpr = pList->nExpr;
97296 pInfo = sqlite3KeyInfoAlloc(db, nExpr);
97297 if( pInfo ){
97298 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
97299 CollSeq *pColl;
97300 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
97301 if( !pColl ) pColl = db->pDfltColl;
97302 pInfo->aColl[i] = pColl;
97303 pInfo->aSortOrder[i] = pItem->sortOrder;
97306 return pInfo;
97309 #ifndef SQLITE_OMIT_COMPOUND_SELECT
97311 ** Name of the connection operator, used for error messages.
97313 static const char *selectOpName(int id){
97314 char *z;
97315 switch( id ){
97316 case TK_ALL: z = "UNION ALL"; break;
97317 case TK_INTERSECT: z = "INTERSECT"; break;
97318 case TK_EXCEPT: z = "EXCEPT"; break;
97319 default: z = "UNION"; break;
97321 return z;
97323 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
97325 #ifndef SQLITE_OMIT_EXPLAIN
97327 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
97328 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
97329 ** where the caption is of the form:
97331 ** "USE TEMP B-TREE FOR xxx"
97333 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
97334 ** is determined by the zUsage argument.
97336 static void explainTempTable(Parse *pParse, const char *zUsage){
97337 if( pParse->explain==2 ){
97338 Vdbe *v = pParse->pVdbe;
97339 char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
97340 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
97345 ** Assign expression b to lvalue a. A second, no-op, version of this macro
97346 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
97347 ** in sqlite3Select() to assign values to structure member variables that
97348 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
97349 ** code with #ifndef directives.
97351 # define explainSetInteger(a, b) a = b
97353 #else
97354 /* No-op versions of the explainXXX() functions and macros. */
97355 # define explainTempTable(y,z)
97356 # define explainSetInteger(y,z)
97357 #endif
97359 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
97361 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
97362 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
97363 ** where the caption is of one of the two forms:
97365 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
97366 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
97368 ** where iSub1 and iSub2 are the integers passed as the corresponding
97369 ** function parameters, and op is the text representation of the parameter
97370 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
97371 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
97372 ** false, or the second form if it is true.
97374 static void explainComposite(
97375 Parse *pParse, /* Parse context */
97376 int op, /* One of TK_UNION, TK_EXCEPT etc. */
97377 int iSub1, /* Subquery id 1 */
97378 int iSub2, /* Subquery id 2 */
97379 int bUseTmp /* True if a temp table was used */
97381 assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
97382 if( pParse->explain==2 ){
97383 Vdbe *v = pParse->pVdbe;
97384 char *zMsg = sqlite3MPrintf(
97385 pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
97386 bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
97388 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
97391 #else
97392 /* No-op versions of the explainXXX() functions and macros. */
97393 # define explainComposite(v,w,x,y,z)
97394 #endif
97397 ** If the inner loop was generated using a non-null pOrderBy argument,
97398 ** then the results were placed in a sorter. After the loop is terminated
97399 ** we need to run the sorter and output the results. The following
97400 ** routine generates the code needed to do that.
97402 static void generateSortTail(
97403 Parse *pParse, /* Parsing context */
97404 Select *p, /* The SELECT statement */
97405 Vdbe *v, /* Generate code into this VDBE */
97406 int nColumn, /* Number of columns of data */
97407 SelectDest *pDest /* Write the sorted results here */
97409 int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
97410 int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
97411 int addr;
97412 int iTab;
97413 int pseudoTab = 0;
97414 ExprList *pOrderBy = p->pOrderBy;
97416 int eDest = pDest->eDest;
97417 int iParm = pDest->iSDParm;
97419 int regRow;
97420 int regRowid;
97422 iTab = pOrderBy->iECursor;
97423 regRow = sqlite3GetTempReg(pParse);
97424 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
97425 pseudoTab = pParse->nTab++;
97426 sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
97427 regRowid = 0;
97428 }else{
97429 regRowid = sqlite3GetTempReg(pParse);
97431 if( p->selFlags & SF_UseSorter ){
97432 int regSortOut = ++pParse->nMem;
97433 int ptab2 = pParse->nTab++;
97434 sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
97435 addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
97436 codeOffset(v, p, addrContinue);
97437 sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
97438 sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
97439 sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
97440 }else{
97441 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
97442 codeOffset(v, p, addrContinue);
97443 sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
97445 switch( eDest ){
97446 case SRT_Table:
97447 case SRT_EphemTab: {
97448 testcase( eDest==SRT_Table );
97449 testcase( eDest==SRT_EphemTab );
97450 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
97451 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
97452 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
97453 break;
97455 #ifndef SQLITE_OMIT_SUBQUERY
97456 case SRT_Set: {
97457 assert( nColumn==1 );
97458 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
97459 &pDest->affSdst, 1);
97460 sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
97461 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
97462 break;
97464 case SRT_Mem: {
97465 assert( nColumn==1 );
97466 sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
97467 /* The LIMIT clause will terminate the loop for us */
97468 break;
97470 #endif
97471 default: {
97472 int i;
97473 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
97474 testcase( eDest==SRT_Output );
97475 testcase( eDest==SRT_Coroutine );
97476 for(i=0; i<nColumn; i++){
97477 assert( regRow!=pDest->iSdst+i );
97478 sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
97479 if( i==0 ){
97480 sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
97483 if( eDest==SRT_Output ){
97484 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
97485 sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
97486 }else{
97487 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
97489 break;
97492 sqlite3ReleaseTempReg(pParse, regRow);
97493 sqlite3ReleaseTempReg(pParse, regRowid);
97495 /* The bottom of the loop
97497 sqlite3VdbeResolveLabel(v, addrContinue);
97498 if( p->selFlags & SF_UseSorter ){
97499 sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
97500 }else{
97501 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
97503 sqlite3VdbeResolveLabel(v, addrBreak);
97504 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
97505 sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
97510 ** Return a pointer to a string containing the 'declaration type' of the
97511 ** expression pExpr. The string may be treated as static by the caller.
97513 ** The declaration type is the exact datatype definition extracted from the
97514 ** original CREATE TABLE statement if the expression is a column. The
97515 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
97516 ** is considered a column can be complex in the presence of subqueries. The
97517 ** result-set expression in all of the following SELECT statements is
97518 ** considered a column by this function.
97520 ** SELECT col FROM tbl;
97521 ** SELECT (SELECT col FROM tbl;
97522 ** SELECT (SELECT col FROM tbl);
97523 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
97525 ** The declaration type for any expression other than a column is NULL.
97527 static const char *columnType(
97528 NameContext *pNC,
97529 Expr *pExpr,
97530 const char **pzOriginDb,
97531 const char **pzOriginTab,
97532 const char **pzOriginCol
97534 char const *zType = 0;
97535 char const *zOriginDb = 0;
97536 char const *zOriginTab = 0;
97537 char const *zOriginCol = 0;
97538 int j;
97539 if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
97541 switch( pExpr->op ){
97542 case TK_AGG_COLUMN:
97543 case TK_COLUMN: {
97544 /* The expression is a column. Locate the table the column is being
97545 ** extracted from in NameContext.pSrcList. This table may be real
97546 ** database table or a subquery.
97548 Table *pTab = 0; /* Table structure column is extracted from */
97549 Select *pS = 0; /* Select the column is extracted from */
97550 int iCol = pExpr->iColumn; /* Index of column in pTab */
97551 testcase( pExpr->op==TK_AGG_COLUMN );
97552 testcase( pExpr->op==TK_COLUMN );
97553 while( pNC && !pTab ){
97554 SrcList *pTabList = pNC->pSrcList;
97555 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
97556 if( j<pTabList->nSrc ){
97557 pTab = pTabList->a[j].pTab;
97558 pS = pTabList->a[j].pSelect;
97559 }else{
97560 pNC = pNC->pNext;
97564 if( pTab==0 ){
97565 /* At one time, code such as "SELECT new.x" within a trigger would
97566 ** cause this condition to run. Since then, we have restructured how
97567 ** trigger code is generated and so this condition is no longer
97568 ** possible. However, it can still be true for statements like
97569 ** the following:
97571 ** CREATE TABLE t1(col INTEGER);
97572 ** SELECT (SELECT t1.col) FROM FROM t1;
97574 ** when columnType() is called on the expression "t1.col" in the
97575 ** sub-select. In this case, set the column type to NULL, even
97576 ** though it should really be "INTEGER".
97578 ** This is not a problem, as the column type of "t1.col" is never
97579 ** used. When columnType() is called on the expression
97580 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
97581 ** branch below. */
97582 break;
97585 assert( pTab && pExpr->pTab==pTab );
97586 if( pS ){
97587 /* The "table" is actually a sub-select or a view in the FROM clause
97588 ** of the SELECT statement. Return the declaration type and origin
97589 ** data for the result-set column of the sub-select.
97591 if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
97592 /* If iCol is less than zero, then the expression requests the
97593 ** rowid of the sub-select or view. This expression is legal (see
97594 ** test case misc2.2.2) - it always evaluates to NULL.
97596 NameContext sNC;
97597 Expr *p = pS->pEList->a[iCol].pExpr;
97598 sNC.pSrcList = pS->pSrc;
97599 sNC.pNext = pNC;
97600 sNC.pParse = pNC->pParse;
97601 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
97603 }else if( ALWAYS(pTab->pSchema) ){
97604 /* A real table */
97605 assert( !pS );
97606 if( iCol<0 ) iCol = pTab->iPKey;
97607 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
97608 if( iCol<0 ){
97609 zType = "INTEGER";
97610 zOriginCol = "rowid";
97611 }else{
97612 zType = pTab->aCol[iCol].zType;
97613 zOriginCol = pTab->aCol[iCol].zName;
97615 zOriginTab = pTab->zName;
97616 if( pNC->pParse ){
97617 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
97618 zOriginDb = pNC->pParse->db->aDb[iDb].zName;
97621 break;
97623 #ifndef SQLITE_OMIT_SUBQUERY
97624 case TK_SELECT: {
97625 /* The expression is a sub-select. Return the declaration type and
97626 ** origin info for the single column in the result set of the SELECT
97627 ** statement.
97629 NameContext sNC;
97630 Select *pS = pExpr->x.pSelect;
97631 Expr *p = pS->pEList->a[0].pExpr;
97632 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
97633 sNC.pSrcList = pS->pSrc;
97634 sNC.pNext = pNC;
97635 sNC.pParse = pNC->pParse;
97636 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
97637 break;
97639 #endif
97642 if( pzOriginDb ){
97643 assert( pzOriginTab && pzOriginCol );
97644 *pzOriginDb = zOriginDb;
97645 *pzOriginTab = zOriginTab;
97646 *pzOriginCol = zOriginCol;
97648 return zType;
97652 ** Generate code that will tell the VDBE the declaration types of columns
97653 ** in the result set.
97655 static void generateColumnTypes(
97656 Parse *pParse, /* Parser context */
97657 SrcList *pTabList, /* List of tables */
97658 ExprList *pEList /* Expressions defining the result set */
97660 #ifndef SQLITE_OMIT_DECLTYPE
97661 Vdbe *v = pParse->pVdbe;
97662 int i;
97663 NameContext sNC;
97664 sNC.pSrcList = pTabList;
97665 sNC.pParse = pParse;
97666 for(i=0; i<pEList->nExpr; i++){
97667 Expr *p = pEList->a[i].pExpr;
97668 const char *zType;
97669 #ifdef SQLITE_ENABLE_COLUMN_METADATA
97670 const char *zOrigDb = 0;
97671 const char *zOrigTab = 0;
97672 const char *zOrigCol = 0;
97673 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
97675 /* The vdbe must make its own copy of the column-type and other
97676 ** column specific strings, in case the schema is reset before this
97677 ** virtual machine is deleted.
97679 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
97680 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
97681 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
97682 #else
97683 zType = columnType(&sNC, p, 0, 0, 0);
97684 #endif
97685 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
97687 #endif /* SQLITE_OMIT_DECLTYPE */
97691 ** Generate code that will tell the VDBE the names of columns
97692 ** in the result set. This information is used to provide the
97693 ** azCol[] values in the callback.
97695 static void generateColumnNames(
97696 Parse *pParse, /* Parser context */
97697 SrcList *pTabList, /* List of tables */
97698 ExprList *pEList /* Expressions defining the result set */
97700 Vdbe *v = pParse->pVdbe;
97701 int i, j;
97702 sqlite3 *db = pParse->db;
97703 int fullNames, shortNames;
97705 #ifndef SQLITE_OMIT_EXPLAIN
97706 /* If this is an EXPLAIN, skip this step */
97707 if( pParse->explain ){
97708 return;
97710 #endif
97712 if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
97713 pParse->colNamesSet = 1;
97714 fullNames = (db->flags & SQLITE_FullColNames)!=0;
97715 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
97716 sqlite3VdbeSetNumCols(v, pEList->nExpr);
97717 for(i=0; i<pEList->nExpr; i++){
97718 Expr *p;
97719 p = pEList->a[i].pExpr;
97720 if( NEVER(p==0) ) continue;
97721 if( pEList->a[i].zName ){
97722 char *zName = pEList->a[i].zName;
97723 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
97724 }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
97725 Table *pTab;
97726 char *zCol;
97727 int iCol = p->iColumn;
97728 for(j=0; ALWAYS(j<pTabList->nSrc); j++){
97729 if( pTabList->a[j].iCursor==p->iTable ) break;
97731 assert( j<pTabList->nSrc );
97732 pTab = pTabList->a[j].pTab;
97733 if( iCol<0 ) iCol = pTab->iPKey;
97734 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
97735 if( iCol<0 ){
97736 zCol = "rowid";
97737 }else{
97738 zCol = pTab->aCol[iCol].zName;
97740 if( !shortNames && !fullNames ){
97741 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
97742 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
97743 }else if( fullNames ){
97744 char *zName = 0;
97745 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
97746 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
97747 }else{
97748 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
97750 }else{
97751 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
97752 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
97755 generateColumnTypes(pParse, pTabList, pEList);
97759 ** Given a an expression list (which is really the list of expressions
97760 ** that form the result set of a SELECT statement) compute appropriate
97761 ** column names for a table that would hold the expression list.
97763 ** All column names will be unique.
97765 ** Only the column names are computed. Column.zType, Column.zColl,
97766 ** and other fields of Column are zeroed.
97768 ** Return SQLITE_OK on success. If a memory allocation error occurs,
97769 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
97771 static int selectColumnsFromExprList(
97772 Parse *pParse, /* Parsing context */
97773 ExprList *pEList, /* Expr list from which to derive column names */
97774 i16 *pnCol, /* Write the number of columns here */
97775 Column **paCol /* Write the new column list here */
97777 sqlite3 *db = pParse->db; /* Database connection */
97778 int i, j; /* Loop counters */
97779 int cnt; /* Index added to make the name unique */
97780 Column *aCol, *pCol; /* For looping over result columns */
97781 int nCol; /* Number of columns in the result set */
97782 Expr *p; /* Expression for a single result column */
97783 char *zName; /* Column name */
97784 int nName; /* Size of name in zName[] */
97786 if( pEList ){
97787 nCol = pEList->nExpr;
97788 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
97789 testcase( aCol==0 );
97790 }else{
97791 nCol = 0;
97792 aCol = 0;
97794 *pnCol = nCol;
97795 *paCol = aCol;
97797 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
97798 /* Get an appropriate name for the column
97800 p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
97801 if( (zName = pEList->a[i].zName)!=0 ){
97802 /* If the column contains an "AS <name>" phrase, use <name> as the name */
97803 zName = sqlite3DbStrDup(db, zName);
97804 }else{
97805 Expr *pColExpr = p; /* The expression that is the result column name */
97806 Table *pTab; /* Table associated with this expression */
97807 while( pColExpr->op==TK_DOT ){
97808 pColExpr = pColExpr->pRight;
97809 assert( pColExpr!=0 );
97811 if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
97812 /* For columns use the column name name */
97813 int iCol = pColExpr->iColumn;
97814 pTab = pColExpr->pTab;
97815 if( iCol<0 ) iCol = pTab->iPKey;
97816 zName = sqlite3MPrintf(db, "%s",
97817 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
97818 }else if( pColExpr->op==TK_ID ){
97819 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
97820 zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
97821 }else{
97822 /* Use the original text of the column expression as its name */
97823 zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
97826 if( db->mallocFailed ){
97827 sqlite3DbFree(db, zName);
97828 break;
97831 /* Make sure the column name is unique. If the name is not unique,
97832 ** append a integer to the name so that it becomes unique.
97834 nName = sqlite3Strlen30(zName);
97835 for(j=cnt=0; j<i; j++){
97836 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
97837 char *zNewName;
97838 int k;
97839 for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
97840 if( zName[k]==':' ) nName = k;
97841 zName[nName] = 0;
97842 zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
97843 sqlite3DbFree(db, zName);
97844 zName = zNewName;
97845 j = -1;
97846 if( zName==0 ) break;
97849 pCol->zName = zName;
97851 if( db->mallocFailed ){
97852 for(j=0; j<i; j++){
97853 sqlite3DbFree(db, aCol[j].zName);
97855 sqlite3DbFree(db, aCol);
97856 *paCol = 0;
97857 *pnCol = 0;
97858 return SQLITE_NOMEM;
97860 return SQLITE_OK;
97864 ** Add type and collation information to a column list based on
97865 ** a SELECT statement.
97867 ** The column list presumably came from selectColumnNamesFromExprList().
97868 ** The column list has only names, not types or collations. This
97869 ** routine goes through and adds the types and collations.
97871 ** This routine requires that all identifiers in the SELECT
97872 ** statement be resolved.
97874 static void selectAddColumnTypeAndCollation(
97875 Parse *pParse, /* Parsing contexts */
97876 int nCol, /* Number of columns */
97877 Column *aCol, /* List of columns */
97878 Select *pSelect /* SELECT used to determine types and collations */
97880 sqlite3 *db = pParse->db;
97881 NameContext sNC;
97882 Column *pCol;
97883 CollSeq *pColl;
97884 int i;
97885 Expr *p;
97886 struct ExprList_item *a;
97888 assert( pSelect!=0 );
97889 assert( (pSelect->selFlags & SF_Resolved)!=0 );
97890 assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
97891 if( db->mallocFailed ) return;
97892 memset(&sNC, 0, sizeof(sNC));
97893 sNC.pSrcList = pSelect->pSrc;
97894 a = pSelect->pEList->a;
97895 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
97896 p = a[i].pExpr;
97897 pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
97898 pCol->affinity = sqlite3ExprAffinity(p);
97899 if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
97900 pColl = sqlite3ExprCollSeq(pParse, p);
97901 if( pColl ){
97902 pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
97908 ** Given a SELECT statement, generate a Table structure that describes
97909 ** the result set of that SELECT.
97911 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
97912 Table *pTab;
97913 sqlite3 *db = pParse->db;
97914 int savedFlags;
97916 savedFlags = db->flags;
97917 db->flags &= ~SQLITE_FullColNames;
97918 db->flags |= SQLITE_ShortColNames;
97919 sqlite3SelectPrep(pParse, pSelect, 0);
97920 if( pParse->nErr ) return 0;
97921 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
97922 db->flags = savedFlags;
97923 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
97924 if( pTab==0 ){
97925 return 0;
97927 /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
97928 ** is disabled */
97929 assert( db->lookaside.bEnabled==0 );
97930 pTab->nRef = 1;
97931 pTab->zName = 0;
97932 pTab->nRowEst = 1000000;
97933 selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
97934 selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
97935 pTab->iPKey = -1;
97936 if( db->mallocFailed ){
97937 sqlite3DeleteTable(db, pTab);
97938 return 0;
97940 return pTab;
97944 ** Get a VDBE for the given parser context. Create a new one if necessary.
97945 ** If an error occurs, return NULL and leave a message in pParse.
97947 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
97948 Vdbe *v = pParse->pVdbe;
97949 if( v==0 ){
97950 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
97951 #ifndef SQLITE_OMIT_TRACE
97952 if( v ){
97953 sqlite3VdbeAddOp0(v, OP_Trace);
97955 #endif
97957 return v;
97962 ** Compute the iLimit and iOffset fields of the SELECT based on the
97963 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
97964 ** that appear in the original SQL statement after the LIMIT and OFFSET
97965 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
97966 ** are the integer memory register numbers for counters used to compute
97967 ** the limit and offset. If there is no limit and/or offset, then
97968 ** iLimit and iOffset are negative.
97970 ** This routine changes the values of iLimit and iOffset only if
97971 ** a limit or offset is defined by pLimit and pOffset. iLimit and
97972 ** iOffset should have been preset to appropriate default values
97973 ** (usually but not always -1) prior to calling this routine.
97974 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
97975 ** redefined. The UNION ALL operator uses this property to force
97976 ** the reuse of the same limit and offset registers across multiple
97977 ** SELECT statements.
97979 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
97980 Vdbe *v = 0;
97981 int iLimit = 0;
97982 int iOffset;
97983 int addr1, n;
97984 if( p->iLimit ) return;
97987 ** "LIMIT -1" always shows all rows. There is some
97988 ** controversy about what the correct behavior should be.
97989 ** The current implementation interprets "LIMIT 0" to mean
97990 ** no rows.
97992 sqlite3ExprCacheClear(pParse);
97993 assert( p->pOffset==0 || p->pLimit!=0 );
97994 if( p->pLimit ){
97995 p->iLimit = iLimit = ++pParse->nMem;
97996 v = sqlite3GetVdbe(pParse);
97997 if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
97998 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
97999 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
98000 VdbeComment((v, "LIMIT counter"));
98001 if( n==0 ){
98002 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
98003 }else if( n>=0 && p->nSelectRow>(u64)n ){
98004 p->nSelectRow = n;
98006 }else{
98007 sqlite3ExprCode(pParse, p->pLimit, iLimit);
98008 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
98009 VdbeComment((v, "LIMIT counter"));
98010 sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
98012 if( p->pOffset ){
98013 p->iOffset = iOffset = ++pParse->nMem;
98014 pParse->nMem++; /* Allocate an extra register for limit+offset */
98015 sqlite3ExprCode(pParse, p->pOffset, iOffset);
98016 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
98017 VdbeComment((v, "OFFSET counter"));
98018 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
98019 sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
98020 sqlite3VdbeJumpHere(v, addr1);
98021 sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
98022 VdbeComment((v, "LIMIT+OFFSET"));
98023 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
98024 sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
98025 sqlite3VdbeJumpHere(v, addr1);
98030 #ifndef SQLITE_OMIT_COMPOUND_SELECT
98032 ** Return the appropriate collating sequence for the iCol-th column of
98033 ** the result set for the compound-select statement "p". Return NULL if
98034 ** the column has no default collating sequence.
98036 ** The collating sequence for the compound select is taken from the
98037 ** left-most term of the select that has a collating sequence.
98039 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
98040 CollSeq *pRet;
98041 if( p->pPrior ){
98042 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
98043 }else{
98044 pRet = 0;
98046 assert( iCol>=0 );
98047 if( pRet==0 && iCol<p->pEList->nExpr ){
98048 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
98050 return pRet;
98052 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
98054 /* Forward reference */
98055 static int multiSelectOrderBy(
98056 Parse *pParse, /* Parsing context */
98057 Select *p, /* The right-most of SELECTs to be coded */
98058 SelectDest *pDest /* What to do with query results */
98062 #ifndef SQLITE_OMIT_COMPOUND_SELECT
98064 ** This routine is called to process a compound query form from
98065 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
98066 ** INTERSECT
98068 ** "p" points to the right-most of the two queries. the query on the
98069 ** left is p->pPrior. The left query could also be a compound query
98070 ** in which case this routine will be called recursively.
98072 ** The results of the total query are to be written into a destination
98073 ** of type eDest with parameter iParm.
98075 ** Example 1: Consider a three-way compound SQL statement.
98077 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
98079 ** This statement is parsed up as follows:
98081 ** SELECT c FROM t3
98082 ** |
98083 ** `-----> SELECT b FROM t2
98084 ** |
98085 ** `------> SELECT a FROM t1
98087 ** The arrows in the diagram above represent the Select.pPrior pointer.
98088 ** So if this routine is called with p equal to the t3 query, then
98089 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
98091 ** Notice that because of the way SQLite parses compound SELECTs, the
98092 ** individual selects always group from left to right.
98094 static int multiSelect(
98095 Parse *pParse, /* Parsing context */
98096 Select *p, /* The right-most of SELECTs to be coded */
98097 SelectDest *pDest /* What to do with query results */
98099 int rc = SQLITE_OK; /* Success code from a subroutine */
98100 Select *pPrior; /* Another SELECT immediately to our left */
98101 Vdbe *v; /* Generate code to this VDBE */
98102 SelectDest dest; /* Alternative data destination */
98103 Select *pDelete = 0; /* Chain of simple selects to delete */
98104 sqlite3 *db; /* Database connection */
98105 #ifndef SQLITE_OMIT_EXPLAIN
98106 int iSub1; /* EQP id of left-hand query */
98107 int iSub2; /* EQP id of right-hand query */
98108 #endif
98110 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
98111 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
98113 assert( p && p->pPrior ); /* Calling function guarantees this much */
98114 db = pParse->db;
98115 pPrior = p->pPrior;
98116 assert( pPrior->pRightmost!=pPrior );
98117 assert( pPrior->pRightmost==p->pRightmost );
98118 dest = *pDest;
98119 if( pPrior->pOrderBy ){
98120 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
98121 selectOpName(p->op));
98122 rc = 1;
98123 goto multi_select_end;
98125 if( pPrior->pLimit ){
98126 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
98127 selectOpName(p->op));
98128 rc = 1;
98129 goto multi_select_end;
98132 v = sqlite3GetVdbe(pParse);
98133 assert( v!=0 ); /* The VDBE already created by calling function */
98135 /* Create the destination temporary table if necessary
98137 if( dest.eDest==SRT_EphemTab ){
98138 assert( p->pEList );
98139 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
98140 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
98141 dest.eDest = SRT_Table;
98144 /* Make sure all SELECTs in the statement have the same number of elements
98145 ** in their result sets.
98147 assert( p->pEList && pPrior->pEList );
98148 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
98149 if( p->selFlags & SF_Values ){
98150 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
98151 }else{
98152 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
98153 " do not have the same number of result columns", selectOpName(p->op));
98155 rc = 1;
98156 goto multi_select_end;
98159 /* Compound SELECTs that have an ORDER BY clause are handled separately.
98161 if( p->pOrderBy ){
98162 return multiSelectOrderBy(pParse, p, pDest);
98165 /* Generate code for the left and right SELECT statements.
98167 switch( p->op ){
98168 case TK_ALL: {
98169 int addr = 0;
98170 int nLimit;
98171 assert( !pPrior->pLimit );
98172 pPrior->iLimit = p->iLimit;
98173 pPrior->iOffset = p->iOffset;
98174 pPrior->pLimit = p->pLimit;
98175 pPrior->pOffset = p->pOffset;
98176 explainSetInteger(iSub1, pParse->iNextSelectId);
98177 rc = sqlite3Select(pParse, pPrior, &dest);
98178 p->pLimit = 0;
98179 p->pOffset = 0;
98180 if( rc ){
98181 goto multi_select_end;
98183 p->pPrior = 0;
98184 p->iLimit = pPrior->iLimit;
98185 p->iOffset = pPrior->iOffset;
98186 if( p->iLimit ){
98187 addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
98188 VdbeComment((v, "Jump ahead if LIMIT reached"));
98190 explainSetInteger(iSub2, pParse->iNextSelectId);
98191 rc = sqlite3Select(pParse, p, &dest);
98192 testcase( rc!=SQLITE_OK );
98193 pDelete = p->pPrior;
98194 p->pPrior = pPrior;
98195 p->nSelectRow += pPrior->nSelectRow;
98196 if( pPrior->pLimit
98197 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
98198 && nLimit>0 && p->nSelectRow > (u64)nLimit
98200 p->nSelectRow = nLimit;
98202 if( addr ){
98203 sqlite3VdbeJumpHere(v, addr);
98205 break;
98207 case TK_EXCEPT:
98208 case TK_UNION: {
98209 int unionTab; /* Cursor number of the temporary table holding result */
98210 u8 op = 0; /* One of the SRT_ operations to apply to self */
98211 int priorOp; /* The SRT_ operation to apply to prior selects */
98212 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
98213 int addr;
98214 SelectDest uniondest;
98216 testcase( p->op==TK_EXCEPT );
98217 testcase( p->op==TK_UNION );
98218 priorOp = SRT_Union;
98219 if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
98220 /* We can reuse a temporary table generated by a SELECT to our
98221 ** right.
98223 assert( p->pRightmost!=p ); /* Can only happen for leftward elements
98224 ** of a 3-way or more compound */
98225 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
98226 assert( p->pOffset==0 ); /* Not allowed on leftward elements */
98227 unionTab = dest.iSDParm;
98228 }else{
98229 /* We will need to create our own temporary table to hold the
98230 ** intermediate results.
98232 unionTab = pParse->nTab++;
98233 assert( p->pOrderBy==0 );
98234 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
98235 assert( p->addrOpenEphm[0] == -1 );
98236 p->addrOpenEphm[0] = addr;
98237 p->pRightmost->selFlags |= SF_UsesEphemeral;
98238 assert( p->pEList );
98241 /* Code the SELECT statements to our left
98243 assert( !pPrior->pOrderBy );
98244 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
98245 explainSetInteger(iSub1, pParse->iNextSelectId);
98246 rc = sqlite3Select(pParse, pPrior, &uniondest);
98247 if( rc ){
98248 goto multi_select_end;
98251 /* Code the current SELECT statement
98253 if( p->op==TK_EXCEPT ){
98254 op = SRT_Except;
98255 }else{
98256 assert( p->op==TK_UNION );
98257 op = SRT_Union;
98259 p->pPrior = 0;
98260 pLimit = p->pLimit;
98261 p->pLimit = 0;
98262 pOffset = p->pOffset;
98263 p->pOffset = 0;
98264 uniondest.eDest = op;
98265 explainSetInteger(iSub2, pParse->iNextSelectId);
98266 rc = sqlite3Select(pParse, p, &uniondest);
98267 testcase( rc!=SQLITE_OK );
98268 /* Query flattening in sqlite3Select() might refill p->pOrderBy.
98269 ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
98270 sqlite3ExprListDelete(db, p->pOrderBy);
98271 pDelete = p->pPrior;
98272 p->pPrior = pPrior;
98273 p->pOrderBy = 0;
98274 if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
98275 sqlite3ExprDelete(db, p->pLimit);
98276 p->pLimit = pLimit;
98277 p->pOffset = pOffset;
98278 p->iLimit = 0;
98279 p->iOffset = 0;
98281 /* Convert the data in the temporary table into whatever form
98282 ** it is that we currently need.
98284 assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
98285 if( dest.eDest!=priorOp ){
98286 int iCont, iBreak, iStart;
98287 assert( p->pEList );
98288 if( dest.eDest==SRT_Output ){
98289 Select *pFirst = p;
98290 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
98291 generateColumnNames(pParse, 0, pFirst->pEList);
98293 iBreak = sqlite3VdbeMakeLabel(v);
98294 iCont = sqlite3VdbeMakeLabel(v);
98295 computeLimitRegisters(pParse, p, iBreak);
98296 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
98297 iStart = sqlite3VdbeCurrentAddr(v);
98298 selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
98299 0, 0, &dest, iCont, iBreak);
98300 sqlite3VdbeResolveLabel(v, iCont);
98301 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
98302 sqlite3VdbeResolveLabel(v, iBreak);
98303 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
98305 break;
98307 default: assert( p->op==TK_INTERSECT ); {
98308 int tab1, tab2;
98309 int iCont, iBreak, iStart;
98310 Expr *pLimit, *pOffset;
98311 int addr;
98312 SelectDest intersectdest;
98313 int r1;
98315 /* INTERSECT is different from the others since it requires
98316 ** two temporary tables. Hence it has its own case. Begin
98317 ** by allocating the tables we will need.
98319 tab1 = pParse->nTab++;
98320 tab2 = pParse->nTab++;
98321 assert( p->pOrderBy==0 );
98323 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
98324 assert( p->addrOpenEphm[0] == -1 );
98325 p->addrOpenEphm[0] = addr;
98326 p->pRightmost->selFlags |= SF_UsesEphemeral;
98327 assert( p->pEList );
98329 /* Code the SELECTs to our left into temporary table "tab1".
98331 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
98332 explainSetInteger(iSub1, pParse->iNextSelectId);
98333 rc = sqlite3Select(pParse, pPrior, &intersectdest);
98334 if( rc ){
98335 goto multi_select_end;
98338 /* Code the current SELECT into temporary table "tab2"
98340 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
98341 assert( p->addrOpenEphm[1] == -1 );
98342 p->addrOpenEphm[1] = addr;
98343 p->pPrior = 0;
98344 pLimit = p->pLimit;
98345 p->pLimit = 0;
98346 pOffset = p->pOffset;
98347 p->pOffset = 0;
98348 intersectdest.iSDParm = tab2;
98349 explainSetInteger(iSub2, pParse->iNextSelectId);
98350 rc = sqlite3Select(pParse, p, &intersectdest);
98351 testcase( rc!=SQLITE_OK );
98352 pDelete = p->pPrior;
98353 p->pPrior = pPrior;
98354 if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
98355 sqlite3ExprDelete(db, p->pLimit);
98356 p->pLimit = pLimit;
98357 p->pOffset = pOffset;
98359 /* Generate code to take the intersection of the two temporary
98360 ** tables.
98362 assert( p->pEList );
98363 if( dest.eDest==SRT_Output ){
98364 Select *pFirst = p;
98365 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
98366 generateColumnNames(pParse, 0, pFirst->pEList);
98368 iBreak = sqlite3VdbeMakeLabel(v);
98369 iCont = sqlite3VdbeMakeLabel(v);
98370 computeLimitRegisters(pParse, p, iBreak);
98371 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
98372 r1 = sqlite3GetTempReg(pParse);
98373 iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
98374 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
98375 sqlite3ReleaseTempReg(pParse, r1);
98376 selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
98377 0, 0, &dest, iCont, iBreak);
98378 sqlite3VdbeResolveLabel(v, iCont);
98379 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
98380 sqlite3VdbeResolveLabel(v, iBreak);
98381 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
98382 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
98383 break;
98387 explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
98389 /* Compute collating sequences used by
98390 ** temporary tables needed to implement the compound select.
98391 ** Attach the KeyInfo structure to all temporary tables.
98393 ** This section is run by the right-most SELECT statement only.
98394 ** SELECT statements to the left always skip this part. The right-most
98395 ** SELECT might also skip this part if it has no ORDER BY clause and
98396 ** no temp tables are required.
98398 if( p->selFlags & SF_UsesEphemeral ){
98399 int i; /* Loop counter */
98400 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
98401 Select *pLoop; /* For looping through SELECT statements */
98402 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
98403 int nCol; /* Number of columns in result set */
98405 assert( p->pRightmost==p );
98406 nCol = p->pEList->nExpr;
98407 pKeyInfo = sqlite3KeyInfoAlloc(db, nCol);
98408 if( !pKeyInfo ){
98409 rc = SQLITE_NOMEM;
98410 goto multi_select_end;
98412 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
98413 *apColl = multiSelectCollSeq(pParse, p, i);
98414 if( 0==*apColl ){
98415 *apColl = db->pDfltColl;
98419 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
98420 for(i=0; i<2; i++){
98421 int addr = pLoop->addrOpenEphm[i];
98422 if( addr<0 ){
98423 /* If [0] is unused then [1] is also unused. So we can
98424 ** always safely abort as soon as the first unused slot is found */
98425 assert( pLoop->addrOpenEphm[1]<0 );
98426 break;
98428 sqlite3VdbeChangeP2(v, addr, nCol);
98429 sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
98430 pLoop->addrOpenEphm[i] = -1;
98433 sqlite3DbFree(db, pKeyInfo);
98436 multi_select_end:
98437 pDest->iSdst = dest.iSdst;
98438 pDest->nSdst = dest.nSdst;
98439 sqlite3SelectDelete(db, pDelete);
98440 return rc;
98442 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
98445 ** Code an output subroutine for a coroutine implementation of a
98446 ** SELECT statment.
98448 ** The data to be output is contained in pIn->iSdst. There are
98449 ** pIn->nSdst columns to be output. pDest is where the output should
98450 ** be sent.
98452 ** regReturn is the number of the register holding the subroutine
98453 ** return address.
98455 ** If regPrev>0 then it is the first register in a vector that
98456 ** records the previous output. mem[regPrev] is a flag that is false
98457 ** if there has been no previous output. If regPrev>0 then code is
98458 ** generated to suppress duplicates. pKeyInfo is used for comparing
98459 ** keys.
98461 ** If the LIMIT found in p->iLimit is reached, jump immediately to
98462 ** iBreak.
98464 static int generateOutputSubroutine(
98465 Parse *pParse, /* Parsing context */
98466 Select *p, /* The SELECT statement */
98467 SelectDest *pIn, /* Coroutine supplying data */
98468 SelectDest *pDest, /* Where to send the data */
98469 int regReturn, /* The return address register */
98470 int regPrev, /* Previous result register. No uniqueness if 0 */
98471 KeyInfo *pKeyInfo, /* For comparing with previous entry */
98472 int p4type, /* The p4 type for pKeyInfo */
98473 int iBreak /* Jump here if we hit the LIMIT */
98475 Vdbe *v = pParse->pVdbe;
98476 int iContinue;
98477 int addr;
98479 addr = sqlite3VdbeCurrentAddr(v);
98480 iContinue = sqlite3VdbeMakeLabel(v);
98482 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
98484 if( regPrev ){
98485 int j1, j2;
98486 j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
98487 j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
98488 (char*)pKeyInfo, p4type);
98489 sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
98490 sqlite3VdbeJumpHere(v, j1);
98491 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
98492 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
98494 if( pParse->db->mallocFailed ) return 0;
98496 /* Suppress the first OFFSET entries if there is an OFFSET clause
98498 codeOffset(v, p, iContinue);
98500 switch( pDest->eDest ){
98501 /* Store the result as data using a unique key.
98503 case SRT_Table:
98504 case SRT_EphemTab: {
98505 int r1 = sqlite3GetTempReg(pParse);
98506 int r2 = sqlite3GetTempReg(pParse);
98507 testcase( pDest->eDest==SRT_Table );
98508 testcase( pDest->eDest==SRT_EphemTab );
98509 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
98510 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
98511 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
98512 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
98513 sqlite3ReleaseTempReg(pParse, r2);
98514 sqlite3ReleaseTempReg(pParse, r1);
98515 break;
98518 #ifndef SQLITE_OMIT_SUBQUERY
98519 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
98520 ** then there should be a single item on the stack. Write this
98521 ** item into the set table with bogus data.
98523 case SRT_Set: {
98524 int r1;
98525 assert( pIn->nSdst==1 );
98526 pDest->affSdst =
98527 sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
98528 r1 = sqlite3GetTempReg(pParse);
98529 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
98530 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
98531 sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
98532 sqlite3ReleaseTempReg(pParse, r1);
98533 break;
98536 #if 0 /* Never occurs on an ORDER BY query */
98537 /* If any row exist in the result set, record that fact and abort.
98539 case SRT_Exists: {
98540 sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
98541 /* The LIMIT clause will terminate the loop for us */
98542 break;
98544 #endif
98546 /* If this is a scalar select that is part of an expression, then
98547 ** store the results in the appropriate memory cell and break out
98548 ** of the scan loop.
98550 case SRT_Mem: {
98551 assert( pIn->nSdst==1 );
98552 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
98553 /* The LIMIT clause will jump out of the loop for us */
98554 break;
98556 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
98558 /* The results are stored in a sequence of registers
98559 ** starting at pDest->iSdst. Then the co-routine yields.
98561 case SRT_Coroutine: {
98562 if( pDest->iSdst==0 ){
98563 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
98564 pDest->nSdst = pIn->nSdst;
98566 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
98567 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
98568 break;
98571 /* If none of the above, then the result destination must be
98572 ** SRT_Output. This routine is never called with any other
98573 ** destination other than the ones handled above or SRT_Output.
98575 ** For SRT_Output, results are stored in a sequence of registers.
98576 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
98577 ** return the next row of result.
98579 default: {
98580 assert( pDest->eDest==SRT_Output );
98581 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
98582 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
98583 break;
98587 /* Jump to the end of the loop if the LIMIT is reached.
98589 if( p->iLimit ){
98590 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
98593 /* Generate the subroutine return
98595 sqlite3VdbeResolveLabel(v, iContinue);
98596 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
98598 return addr;
98602 ** Alternative compound select code generator for cases when there
98603 ** is an ORDER BY clause.
98605 ** We assume a query of the following form:
98607 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
98609 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
98610 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
98611 ** co-routines. Then run the co-routines in parallel and merge the results
98612 ** into the output. In addition to the two coroutines (called selectA and
98613 ** selectB) there are 7 subroutines:
98615 ** outA: Move the output of the selectA coroutine into the output
98616 ** of the compound query.
98618 ** outB: Move the output of the selectB coroutine into the output
98619 ** of the compound query. (Only generated for UNION and
98620 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
98621 ** appears only in B.)
98623 ** AltB: Called when there is data from both coroutines and A<B.
98625 ** AeqB: Called when there is data from both coroutines and A==B.
98627 ** AgtB: Called when there is data from both coroutines and A>B.
98629 ** EofA: Called when data is exhausted from selectA.
98631 ** EofB: Called when data is exhausted from selectB.
98633 ** The implementation of the latter five subroutines depend on which
98634 ** <operator> is used:
98637 ** UNION ALL UNION EXCEPT INTERSECT
98638 ** ------------- ----------------- -------------- -----------------
98639 ** AltB: outA, nextA outA, nextA outA, nextA nextA
98641 ** AeqB: outA, nextA nextA nextA outA, nextA
98643 ** AgtB: outB, nextB outB, nextB nextB nextB
98645 ** EofA: outB, nextB outB, nextB halt halt
98647 ** EofB: outA, nextA outA, nextA outA, nextA halt
98649 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
98650 ** causes an immediate jump to EofA and an EOF on B following nextB causes
98651 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
98652 ** following nextX causes a jump to the end of the select processing.
98654 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
98655 ** within the output subroutine. The regPrev register set holds the previously
98656 ** output value. A comparison is made against this value and the output
98657 ** is skipped if the next results would be the same as the previous.
98659 ** The implementation plan is to implement the two coroutines and seven
98660 ** subroutines first, then put the control logic at the bottom. Like this:
98662 ** goto Init
98663 ** coA: coroutine for left query (A)
98664 ** coB: coroutine for right query (B)
98665 ** outA: output one row of A
98666 ** outB: output one row of B (UNION and UNION ALL only)
98667 ** EofA: ...
98668 ** EofB: ...
98669 ** AltB: ...
98670 ** AeqB: ...
98671 ** AgtB: ...
98672 ** Init: initialize coroutine registers
98673 ** yield coA
98674 ** if eof(A) goto EofA
98675 ** yield coB
98676 ** if eof(B) goto EofB
98677 ** Cmpr: Compare A, B
98678 ** Jump AltB, AeqB, AgtB
98679 ** End: ...
98681 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
98682 ** actually called using Gosub and they do not Return. EofA and EofB loop
98683 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
98684 ** and AgtB jump to either L2 or to one of EofA or EofB.
98686 #ifndef SQLITE_OMIT_COMPOUND_SELECT
98687 static int multiSelectOrderBy(
98688 Parse *pParse, /* Parsing context */
98689 Select *p, /* The right-most of SELECTs to be coded */
98690 SelectDest *pDest /* What to do with query results */
98692 int i, j; /* Loop counters */
98693 Select *pPrior; /* Another SELECT immediately to our left */
98694 Vdbe *v; /* Generate code to this VDBE */
98695 SelectDest destA; /* Destination for coroutine A */
98696 SelectDest destB; /* Destination for coroutine B */
98697 int regAddrA; /* Address register for select-A coroutine */
98698 int regEofA; /* Flag to indicate when select-A is complete */
98699 int regAddrB; /* Address register for select-B coroutine */
98700 int regEofB; /* Flag to indicate when select-B is complete */
98701 int addrSelectA; /* Address of the select-A coroutine */
98702 int addrSelectB; /* Address of the select-B coroutine */
98703 int regOutA; /* Address register for the output-A subroutine */
98704 int regOutB; /* Address register for the output-B subroutine */
98705 int addrOutA; /* Address of the output-A subroutine */
98706 int addrOutB = 0; /* Address of the output-B subroutine */
98707 int addrEofA; /* Address of the select-A-exhausted subroutine */
98708 int addrEofB; /* Address of the select-B-exhausted subroutine */
98709 int addrAltB; /* Address of the A<B subroutine */
98710 int addrAeqB; /* Address of the A==B subroutine */
98711 int addrAgtB; /* Address of the A>B subroutine */
98712 int regLimitA; /* Limit register for select-A */
98713 int regLimitB; /* Limit register for select-A */
98714 int regPrev; /* A range of registers to hold previous output */
98715 int savedLimit; /* Saved value of p->iLimit */
98716 int savedOffset; /* Saved value of p->iOffset */
98717 int labelCmpr; /* Label for the start of the merge algorithm */
98718 int labelEnd; /* Label for the end of the overall SELECT stmt */
98719 int j1; /* Jump instructions that get retargetted */
98720 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
98721 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
98722 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
98723 sqlite3 *db; /* Database connection */
98724 ExprList *pOrderBy; /* The ORDER BY clause */
98725 int nOrderBy; /* Number of terms in the ORDER BY clause */
98726 int *aPermute; /* Mapping from ORDER BY terms to result set columns */
98727 #ifndef SQLITE_OMIT_EXPLAIN
98728 int iSub1; /* EQP id of left-hand query */
98729 int iSub2; /* EQP id of right-hand query */
98730 #endif
98732 assert( p->pOrderBy!=0 );
98733 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
98734 db = pParse->db;
98735 v = pParse->pVdbe;
98736 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
98737 labelEnd = sqlite3VdbeMakeLabel(v);
98738 labelCmpr = sqlite3VdbeMakeLabel(v);
98741 /* Patch up the ORDER BY clause
98743 op = p->op;
98744 pPrior = p->pPrior;
98745 assert( pPrior->pOrderBy==0 );
98746 pOrderBy = p->pOrderBy;
98747 assert( pOrderBy );
98748 nOrderBy = pOrderBy->nExpr;
98750 /* For operators other than UNION ALL we have to make sure that
98751 ** the ORDER BY clause covers every term of the result set. Add
98752 ** terms to the ORDER BY clause as necessary.
98754 if( op!=TK_ALL ){
98755 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
98756 struct ExprList_item *pItem;
98757 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
98758 assert( pItem->iOrderByCol>0 );
98759 if( pItem->iOrderByCol==i ) break;
98761 if( j==nOrderBy ){
98762 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
98763 if( pNew==0 ) return SQLITE_NOMEM;
98764 pNew->flags |= EP_IntValue;
98765 pNew->u.iValue = i;
98766 pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
98767 if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
98772 /* Compute the comparison permutation and keyinfo that is used with
98773 ** the permutation used to determine if the next
98774 ** row of results comes from selectA or selectB. Also add explicit
98775 ** collations to the ORDER BY clause terms so that when the subqueries
98776 ** to the right and the left are evaluated, they use the correct
98777 ** collation.
98779 aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
98780 if( aPermute ){
98781 struct ExprList_item *pItem;
98782 for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
98783 assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr );
98784 aPermute[i] = pItem->iOrderByCol - 1;
98786 pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy);
98787 if( pKeyMerge ){
98788 for(i=0; i<nOrderBy; i++){
98789 CollSeq *pColl;
98790 Expr *pTerm = pOrderBy->a[i].pExpr;
98791 if( pTerm->flags & EP_Collate ){
98792 pColl = sqlite3ExprCollSeq(pParse, pTerm);
98793 }else{
98794 pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
98795 if( pColl==0 ) pColl = db->pDfltColl;
98796 pOrderBy->a[i].pExpr =
98797 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
98799 pKeyMerge->aColl[i] = pColl;
98800 pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
98803 }else{
98804 pKeyMerge = 0;
98807 /* Reattach the ORDER BY clause to the query.
98809 p->pOrderBy = pOrderBy;
98810 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
98812 /* Allocate a range of temporary registers and the KeyInfo needed
98813 ** for the logic that removes duplicate result rows when the
98814 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
98816 if( op==TK_ALL ){
98817 regPrev = 0;
98818 }else{
98819 int nExpr = p->pEList->nExpr;
98820 assert( nOrderBy>=nExpr || db->mallocFailed );
98821 regPrev = pParse->nMem+1;
98822 pParse->nMem += nExpr+1;
98823 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
98824 pKeyDup = sqlite3KeyInfoAlloc(db, nExpr);
98825 if( pKeyDup ){
98826 for(i=0; i<nExpr; i++){
98827 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
98828 pKeyDup->aSortOrder[i] = 0;
98833 /* Separate the left and the right query from one another
98835 p->pPrior = 0;
98836 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
98837 if( pPrior->pPrior==0 ){
98838 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
98841 /* Compute the limit registers */
98842 computeLimitRegisters(pParse, p, labelEnd);
98843 if( p->iLimit && op==TK_ALL ){
98844 regLimitA = ++pParse->nMem;
98845 regLimitB = ++pParse->nMem;
98846 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
98847 regLimitA);
98848 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
98849 }else{
98850 regLimitA = regLimitB = 0;
98852 sqlite3ExprDelete(db, p->pLimit);
98853 p->pLimit = 0;
98854 sqlite3ExprDelete(db, p->pOffset);
98855 p->pOffset = 0;
98857 regAddrA = ++pParse->nMem;
98858 regEofA = ++pParse->nMem;
98859 regAddrB = ++pParse->nMem;
98860 regEofB = ++pParse->nMem;
98861 regOutA = ++pParse->nMem;
98862 regOutB = ++pParse->nMem;
98863 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
98864 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
98866 /* Jump past the various subroutines and coroutines to the main
98867 ** merge loop
98869 j1 = sqlite3VdbeAddOp0(v, OP_Goto);
98870 addrSelectA = sqlite3VdbeCurrentAddr(v);
98873 /* Generate a coroutine to evaluate the SELECT statement to the
98874 ** left of the compound operator - the "A" select.
98876 VdbeNoopComment((v, "Begin coroutine for left SELECT"));
98877 pPrior->iLimit = regLimitA;
98878 explainSetInteger(iSub1, pParse->iNextSelectId);
98879 sqlite3Select(pParse, pPrior, &destA);
98880 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
98881 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98882 VdbeNoopComment((v, "End coroutine for left SELECT"));
98884 /* Generate a coroutine to evaluate the SELECT statement on
98885 ** the right - the "B" select
98887 addrSelectB = sqlite3VdbeCurrentAddr(v);
98888 VdbeNoopComment((v, "Begin coroutine for right SELECT"));
98889 savedLimit = p->iLimit;
98890 savedOffset = p->iOffset;
98891 p->iLimit = regLimitB;
98892 p->iOffset = 0;
98893 explainSetInteger(iSub2, pParse->iNextSelectId);
98894 sqlite3Select(pParse, p, &destB);
98895 p->iLimit = savedLimit;
98896 p->iOffset = savedOffset;
98897 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
98898 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98899 VdbeNoopComment((v, "End coroutine for right SELECT"));
98901 /* Generate a subroutine that outputs the current row of the A
98902 ** select as the next output row of the compound select.
98904 VdbeNoopComment((v, "Output routine for A"));
98905 addrOutA = generateOutputSubroutine(pParse,
98906 p, &destA, pDest, regOutA,
98907 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
98909 /* Generate a subroutine that outputs the current row of the B
98910 ** select as the next output row of the compound select.
98912 if( op==TK_ALL || op==TK_UNION ){
98913 VdbeNoopComment((v, "Output routine for B"));
98914 addrOutB = generateOutputSubroutine(pParse,
98915 p, &destB, pDest, regOutB,
98916 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
98919 /* Generate a subroutine to run when the results from select A
98920 ** are exhausted and only data in select B remains.
98922 VdbeNoopComment((v, "eof-A subroutine"));
98923 if( op==TK_EXCEPT || op==TK_INTERSECT ){
98924 addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
98925 }else{
98926 addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
98927 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
98928 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98929 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
98930 p->nSelectRow += pPrior->nSelectRow;
98933 /* Generate a subroutine to run when the results from select B
98934 ** are exhausted and only data in select A remains.
98936 if( op==TK_INTERSECT ){
98937 addrEofB = addrEofA;
98938 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
98939 }else{
98940 VdbeNoopComment((v, "eof-B subroutine"));
98941 addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
98942 sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
98943 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98944 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
98947 /* Generate code to handle the case of A<B
98949 VdbeNoopComment((v, "A-lt-B subroutine"));
98950 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
98951 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98952 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98953 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98955 /* Generate code to handle the case of A==B
98957 if( op==TK_ALL ){
98958 addrAeqB = addrAltB;
98959 }else if( op==TK_INTERSECT ){
98960 addrAeqB = addrAltB;
98961 addrAltB++;
98962 }else{
98963 VdbeNoopComment((v, "A-eq-B subroutine"));
98964 addrAeqB =
98965 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98966 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98967 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98970 /* Generate code to handle the case of A>B
98972 VdbeNoopComment((v, "A-gt-B subroutine"));
98973 addrAgtB = sqlite3VdbeCurrentAddr(v);
98974 if( op==TK_ALL || op==TK_UNION ){
98975 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
98977 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98978 sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
98979 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98981 /* This code runs once to initialize everything.
98983 sqlite3VdbeJumpHere(v, j1);
98984 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
98985 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
98986 sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
98987 sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
98988 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98989 sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
98991 /* Implement the main merge loop
98993 sqlite3VdbeResolveLabel(v, labelCmpr);
98994 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
98995 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
98996 (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
98997 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
98998 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
99000 /* Jump to the this point in order to terminate the query.
99002 sqlite3VdbeResolveLabel(v, labelEnd);
99004 /* Set the number of output columns
99006 if( pDest->eDest==SRT_Output ){
99007 Select *pFirst = pPrior;
99008 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
99009 generateColumnNames(pParse, 0, pFirst->pEList);
99012 /* Reassembly the compound query so that it will be freed correctly
99013 ** by the calling function */
99014 if( p->pPrior ){
99015 sqlite3SelectDelete(db, p->pPrior);
99017 p->pPrior = pPrior;
99019 /*** TBD: Insert subroutine calls to close cursors on incomplete
99020 **** subqueries ****/
99021 explainComposite(pParse, p->op, iSub1, iSub2, 0);
99022 return SQLITE_OK;
99024 #endif
99026 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
99027 /* Forward Declarations */
99028 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
99029 static void substSelect(sqlite3*, Select *, int, ExprList *);
99032 ** Scan through the expression pExpr. Replace every reference to
99033 ** a column in table number iTable with a copy of the iColumn-th
99034 ** entry in pEList. (But leave references to the ROWID column
99035 ** unchanged.)
99037 ** This routine is part of the flattening procedure. A subquery
99038 ** whose result set is defined by pEList appears as entry in the
99039 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
99040 ** FORM clause entry is iTable. This routine make the necessary
99041 ** changes to pExpr so that it refers directly to the source table
99042 ** of the subquery rather the result set of the subquery.
99044 static Expr *substExpr(
99045 sqlite3 *db, /* Report malloc errors to this connection */
99046 Expr *pExpr, /* Expr in which substitution occurs */
99047 int iTable, /* Table to be substituted */
99048 ExprList *pEList /* Substitute expressions */
99050 if( pExpr==0 ) return 0;
99051 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
99052 if( pExpr->iColumn<0 ){
99053 pExpr->op = TK_NULL;
99054 }else{
99055 Expr *pNew;
99056 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
99057 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
99058 pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
99059 sqlite3ExprDelete(db, pExpr);
99060 pExpr = pNew;
99062 }else{
99063 pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
99064 pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
99065 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
99066 substSelect(db, pExpr->x.pSelect, iTable, pEList);
99067 }else{
99068 substExprList(db, pExpr->x.pList, iTable, pEList);
99071 return pExpr;
99073 static void substExprList(
99074 sqlite3 *db, /* Report malloc errors here */
99075 ExprList *pList, /* List to scan and in which to make substitutes */
99076 int iTable, /* Table to be substituted */
99077 ExprList *pEList /* Substitute values */
99079 int i;
99080 if( pList==0 ) return;
99081 for(i=0; i<pList->nExpr; i++){
99082 pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
99085 static void substSelect(
99086 sqlite3 *db, /* Report malloc errors here */
99087 Select *p, /* SELECT statement in which to make substitutions */
99088 int iTable, /* Table to be replaced */
99089 ExprList *pEList /* Substitute values */
99091 SrcList *pSrc;
99092 struct SrcList_item *pItem;
99093 int i;
99094 if( !p ) return;
99095 substExprList(db, p->pEList, iTable, pEList);
99096 substExprList(db, p->pGroupBy, iTable, pEList);
99097 substExprList(db, p->pOrderBy, iTable, pEList);
99098 p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
99099 p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
99100 substSelect(db, p->pPrior, iTable, pEList);
99101 pSrc = p->pSrc;
99102 assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
99103 if( ALWAYS(pSrc) ){
99104 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
99105 substSelect(db, pItem->pSelect, iTable, pEList);
99109 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
99111 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
99113 ** This routine attempts to flatten subqueries as a performance optimization.
99114 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
99116 ** To understand the concept of flattening, consider the following
99117 ** query:
99119 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
99121 ** The default way of implementing this query is to execute the
99122 ** subquery first and store the results in a temporary table, then
99123 ** run the outer query on that temporary table. This requires two
99124 ** passes over the data. Furthermore, because the temporary table
99125 ** has no indices, the WHERE clause on the outer query cannot be
99126 ** optimized.
99128 ** This routine attempts to rewrite queries such as the above into
99129 ** a single flat select, like this:
99131 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
99133 ** The code generated for this simpification gives the same result
99134 ** but only has to scan the data once. And because indices might
99135 ** exist on the table t1, a complete scan of the data might be
99136 ** avoided.
99138 ** Flattening is only attempted if all of the following are true:
99140 ** (1) The subquery and the outer query do not both use aggregates.
99142 ** (2) The subquery is not an aggregate or the outer query is not a join.
99144 ** (3) The subquery is not the right operand of a left outer join
99145 ** (Originally ticket #306. Strengthened by ticket #3300)
99147 ** (4) The subquery is not DISTINCT.
99149 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
99150 ** sub-queries that were excluded from this optimization. Restriction
99151 ** (4) has since been expanded to exclude all DISTINCT subqueries.
99153 ** (6) The subquery does not use aggregates or the outer query is not
99154 ** DISTINCT.
99156 ** (7) The subquery has a FROM clause. TODO: For subqueries without
99157 ** A FROM clause, consider adding a FROM close with the special
99158 ** table sqlite_once that consists of a single row containing a
99159 ** single NULL.
99161 ** (8) The subquery does not use LIMIT or the outer query is not a join.
99163 ** (9) The subquery does not use LIMIT or the outer query does not use
99164 ** aggregates.
99166 ** (10) The subquery does not use aggregates or the outer query does not
99167 ** use LIMIT.
99169 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
99171 ** (**) Not implemented. Subsumed into restriction (3). Was previously
99172 ** a separate restriction deriving from ticket #350.
99174 ** (13) The subquery and outer query do not both use LIMIT.
99176 ** (14) The subquery does not use OFFSET.
99178 ** (15) The outer query is not part of a compound select or the
99179 ** subquery does not have a LIMIT clause.
99180 ** (See ticket #2339 and ticket [02a8e81d44]).
99182 ** (16) The outer query is not an aggregate or the subquery does
99183 ** not contain ORDER BY. (Ticket #2942) This used to not matter
99184 ** until we introduced the group_concat() function.
99186 ** (17) The sub-query is not a compound select, or it is a UNION ALL
99187 ** compound clause made up entirely of non-aggregate queries, and
99188 ** the parent query:
99190 ** * is not itself part of a compound select,
99191 ** * is not an aggregate or DISTINCT query, and
99192 ** * is not a join
99194 ** The parent and sub-query may contain WHERE clauses. Subject to
99195 ** rules (11), (13) and (14), they may also contain ORDER BY,
99196 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
99197 ** operator other than UNION ALL because all the other compound
99198 ** operators have an implied DISTINCT which is disallowed by
99199 ** restriction (4).
99201 ** Also, each component of the sub-query must return the same number
99202 ** of result columns. This is actually a requirement for any compound
99203 ** SELECT statement, but all the code here does is make sure that no
99204 ** such (illegal) sub-query is flattened. The caller will detect the
99205 ** syntax error and return a detailed message.
99207 ** (18) If the sub-query is a compound select, then all terms of the
99208 ** ORDER by clause of the parent must be simple references to
99209 ** columns of the sub-query.
99211 ** (19) The subquery does not use LIMIT or the outer query does not
99212 ** have a WHERE clause.
99214 ** (20) If the sub-query is a compound select, then it must not use
99215 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
99216 ** somewhat by saying that the terms of the ORDER BY clause must
99217 ** appear as unmodified result columns in the outer query. But we
99218 ** have other optimizations in mind to deal with that case.
99220 ** (21) The subquery does not use LIMIT or the outer query is not
99221 ** DISTINCT. (See ticket [752e1646fc]).
99223 ** In this routine, the "p" parameter is a pointer to the outer query.
99224 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
99225 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
99227 ** If flattening is not attempted, this routine is a no-op and returns 0.
99228 ** If flattening is attempted this routine returns 1.
99230 ** All of the expression analysis must occur on both the outer query and
99231 ** the subquery before this routine runs.
99233 static int flattenSubquery(
99234 Parse *pParse, /* Parsing context */
99235 Select *p, /* The parent or outer SELECT statement */
99236 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
99237 int isAgg, /* True if outer SELECT uses aggregate functions */
99238 int subqueryIsAgg /* True if the subquery uses aggregate functions */
99240 const char *zSavedAuthContext = pParse->zAuthContext;
99241 Select *pParent;
99242 Select *pSub; /* The inner query or "subquery" */
99243 Select *pSub1; /* Pointer to the rightmost select in sub-query */
99244 SrcList *pSrc; /* The FROM clause of the outer query */
99245 SrcList *pSubSrc; /* The FROM clause of the subquery */
99246 ExprList *pList; /* The result set of the outer query */
99247 int iParent; /* VDBE cursor number of the pSub result set temp table */
99248 int i; /* Loop counter */
99249 Expr *pWhere; /* The WHERE clause */
99250 struct SrcList_item *pSubitem; /* The subquery */
99251 sqlite3 *db = pParse->db;
99253 /* Check to see if flattening is permitted. Return 0 if not.
99255 assert( p!=0 );
99256 assert( p->pPrior==0 ); /* Unable to flatten compound queries */
99257 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
99258 pSrc = p->pSrc;
99259 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
99260 pSubitem = &pSrc->a[iFrom];
99261 iParent = pSubitem->iCursor;
99262 pSub = pSubitem->pSelect;
99263 assert( pSub!=0 );
99264 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
99265 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
99266 pSubSrc = pSub->pSrc;
99267 assert( pSubSrc );
99268 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
99269 ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
99270 ** because they could be computed at compile-time. But when LIMIT and OFFSET
99271 ** became arbitrary expressions, we were forced to add restrictions (13)
99272 ** and (14). */
99273 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
99274 if( pSub->pOffset ) return 0; /* Restriction (14) */
99275 if( p->pRightmost && pSub->pLimit ){
99276 return 0; /* Restriction (15) */
99278 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
99279 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
99280 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
99281 return 0; /* Restrictions (8)(9) */
99283 if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
99284 return 0; /* Restriction (6) */
99286 if( p->pOrderBy && pSub->pOrderBy ){
99287 return 0; /* Restriction (11) */
99289 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
99290 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
99291 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
99292 return 0; /* Restriction (21) */
99295 /* OBSOLETE COMMENT 1:
99296 ** Restriction 3: If the subquery is a join, make sure the subquery is
99297 ** not used as the right operand of an outer join. Examples of why this
99298 ** is not allowed:
99300 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
99302 ** If we flatten the above, we would get
99304 ** (t1 LEFT OUTER JOIN t2) JOIN t3
99306 ** which is not at all the same thing.
99308 ** OBSOLETE COMMENT 2:
99309 ** Restriction 12: If the subquery is the right operand of a left outer
99310 ** join, make sure the subquery has no WHERE clause.
99311 ** An examples of why this is not allowed:
99313 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
99315 ** If we flatten the above, we would get
99317 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
99319 ** But the t2.x>0 test will always fail on a NULL row of t2, which
99320 ** effectively converts the OUTER JOIN into an INNER JOIN.
99322 ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
99323 ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
99324 ** is fraught with danger. Best to avoid the whole thing. If the
99325 ** subquery is the right term of a LEFT JOIN, then do not flatten.
99327 if( (pSubitem->jointype & JT_OUTER)!=0 ){
99328 return 0;
99331 /* Restriction 17: If the sub-query is a compound SELECT, then it must
99332 ** use only the UNION ALL operator. And none of the simple select queries
99333 ** that make up the compound SELECT are allowed to be aggregate or distinct
99334 ** queries.
99336 if( pSub->pPrior ){
99337 if( pSub->pOrderBy ){
99338 return 0; /* Restriction 20 */
99340 if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
99341 return 0;
99343 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
99344 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
99345 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
99346 assert( pSub->pSrc!=0 );
99347 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
99348 || (pSub1->pPrior && pSub1->op!=TK_ALL)
99349 || pSub1->pSrc->nSrc<1
99350 || pSub->pEList->nExpr!=pSub1->pEList->nExpr
99352 return 0;
99354 testcase( pSub1->pSrc->nSrc>1 );
99357 /* Restriction 18. */
99358 if( p->pOrderBy ){
99359 int ii;
99360 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
99361 if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
99366 /***** If we reach this point, flattening is permitted. *****/
99368 /* Authorize the subquery */
99369 pParse->zAuthContext = pSubitem->zName;
99370 TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
99371 testcase( i==SQLITE_DENY );
99372 pParse->zAuthContext = zSavedAuthContext;
99374 /* If the sub-query is a compound SELECT statement, then (by restrictions
99375 ** 17 and 18 above) it must be a UNION ALL and the parent query must
99376 ** be of the form:
99378 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
99380 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
99381 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
99382 ** OFFSET clauses and joins them to the left-hand-side of the original
99383 ** using UNION ALL operators. In this case N is the number of simple
99384 ** select statements in the compound sub-query.
99386 ** Example:
99388 ** SELECT a+1 FROM (
99389 ** SELECT x FROM tab
99390 ** UNION ALL
99391 ** SELECT y FROM tab
99392 ** UNION ALL
99393 ** SELECT abs(z*2) FROM tab2
99394 ** ) WHERE a!=5 ORDER BY 1
99396 ** Transformed into:
99398 ** SELECT x+1 FROM tab WHERE x+1!=5
99399 ** UNION ALL
99400 ** SELECT y+1 FROM tab WHERE y+1!=5
99401 ** UNION ALL
99402 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
99403 ** ORDER BY 1
99405 ** We call this the "compound-subquery flattening".
99407 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
99408 Select *pNew;
99409 ExprList *pOrderBy = p->pOrderBy;
99410 Expr *pLimit = p->pLimit;
99411 Expr *pOffset = p->pOffset;
99412 Select *pPrior = p->pPrior;
99413 p->pOrderBy = 0;
99414 p->pSrc = 0;
99415 p->pPrior = 0;
99416 p->pLimit = 0;
99417 p->pOffset = 0;
99418 pNew = sqlite3SelectDup(db, p, 0);
99419 p->pOffset = pOffset;
99420 p->pLimit = pLimit;
99421 p->pOrderBy = pOrderBy;
99422 p->pSrc = pSrc;
99423 p->op = TK_ALL;
99424 p->pRightmost = 0;
99425 if( pNew==0 ){
99426 pNew = pPrior;
99427 }else{
99428 pNew->pPrior = pPrior;
99429 pNew->pRightmost = 0;
99431 p->pPrior = pNew;
99432 if( db->mallocFailed ) return 1;
99435 /* Begin flattening the iFrom-th entry of the FROM clause
99436 ** in the outer query.
99438 pSub = pSub1 = pSubitem->pSelect;
99440 /* Delete the transient table structure associated with the
99441 ** subquery
99443 sqlite3DbFree(db, pSubitem->zDatabase);
99444 sqlite3DbFree(db, pSubitem->zName);
99445 sqlite3DbFree(db, pSubitem->zAlias);
99446 pSubitem->zDatabase = 0;
99447 pSubitem->zName = 0;
99448 pSubitem->zAlias = 0;
99449 pSubitem->pSelect = 0;
99451 /* Defer deleting the Table object associated with the
99452 ** subquery until code generation is
99453 ** complete, since there may still exist Expr.pTab entries that
99454 ** refer to the subquery even after flattening. Ticket #3346.
99456 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
99458 if( ALWAYS(pSubitem->pTab!=0) ){
99459 Table *pTabToDel = pSubitem->pTab;
99460 if( pTabToDel->nRef==1 ){
99461 Parse *pToplevel = sqlite3ParseToplevel(pParse);
99462 pTabToDel->pNextZombie = pToplevel->pZombieTab;
99463 pToplevel->pZombieTab = pTabToDel;
99464 }else{
99465 pTabToDel->nRef--;
99467 pSubitem->pTab = 0;
99470 /* The following loop runs once for each term in a compound-subquery
99471 ** flattening (as described above). If we are doing a different kind
99472 ** of flattening - a flattening other than a compound-subquery flattening -
99473 ** then this loop only runs once.
99475 ** This loop moves all of the FROM elements of the subquery into the
99476 ** the FROM clause of the outer query. Before doing this, remember
99477 ** the cursor number for the original outer query FROM element in
99478 ** iParent. The iParent cursor will never be used. Subsequent code
99479 ** will scan expressions looking for iParent references and replace
99480 ** those references with expressions that resolve to the subquery FROM
99481 ** elements we are now copying in.
99483 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
99484 int nSubSrc;
99485 u8 jointype = 0;
99486 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
99487 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
99488 pSrc = pParent->pSrc; /* FROM clause of the outer query */
99490 if( pSrc ){
99491 assert( pParent==p ); /* First time through the loop */
99492 jointype = pSubitem->jointype;
99493 }else{
99494 assert( pParent!=p ); /* 2nd and subsequent times through the loop */
99495 pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
99496 if( pSrc==0 ){
99497 assert( db->mallocFailed );
99498 break;
99502 /* The subquery uses a single slot of the FROM clause of the outer
99503 ** query. If the subquery has more than one element in its FROM clause,
99504 ** then expand the outer query to make space for it to hold all elements
99505 ** of the subquery.
99507 ** Example:
99509 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
99511 ** The outer query has 3 slots in its FROM clause. One slot of the
99512 ** outer query (the middle slot) is used by the subquery. The next
99513 ** block of code will expand the out query to 4 slots. The middle
99514 ** slot is expanded to two slots in order to make space for the
99515 ** two elements in the FROM clause of the subquery.
99517 if( nSubSrc>1 ){
99518 pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
99519 if( db->mallocFailed ){
99520 break;
99524 /* Transfer the FROM clause terms from the subquery into the
99525 ** outer query.
99527 for(i=0; i<nSubSrc; i++){
99528 sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
99529 pSrc->a[i+iFrom] = pSubSrc->a[i];
99530 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
99532 pSrc->a[iFrom].jointype = jointype;
99534 /* Now begin substituting subquery result set expressions for
99535 ** references to the iParent in the outer query.
99537 ** Example:
99539 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
99540 ** \ \_____________ subquery __________/ /
99541 ** \_____________________ outer query ______________________________/
99543 ** We look at every expression in the outer query and every place we see
99544 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
99546 pList = pParent->pEList;
99547 for(i=0; i<pList->nExpr; i++){
99548 if( pList->a[i].zName==0 ){
99549 char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
99550 sqlite3Dequote(zName);
99551 pList->a[i].zName = zName;
99554 substExprList(db, pParent->pEList, iParent, pSub->pEList);
99555 if( isAgg ){
99556 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
99557 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
99559 if( pSub->pOrderBy ){
99560 assert( pParent->pOrderBy==0 );
99561 pParent->pOrderBy = pSub->pOrderBy;
99562 pSub->pOrderBy = 0;
99563 }else if( pParent->pOrderBy ){
99564 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
99566 if( pSub->pWhere ){
99567 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
99568 }else{
99569 pWhere = 0;
99571 if( subqueryIsAgg ){
99572 assert( pParent->pHaving==0 );
99573 pParent->pHaving = pParent->pWhere;
99574 pParent->pWhere = pWhere;
99575 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
99576 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
99577 sqlite3ExprDup(db, pSub->pHaving, 0));
99578 assert( pParent->pGroupBy==0 );
99579 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
99580 }else{
99581 pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
99582 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
99585 /* The flattened query is distinct if either the inner or the
99586 ** outer query is distinct.
99588 pParent->selFlags |= pSub->selFlags & SF_Distinct;
99591 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
99593 ** One is tempted to try to add a and b to combine the limits. But this
99594 ** does not work if either limit is negative.
99596 if( pSub->pLimit ){
99597 pParent->pLimit = pSub->pLimit;
99598 pSub->pLimit = 0;
99602 /* Finially, delete what is left of the subquery and return
99603 ** success.
99605 sqlite3SelectDelete(db, pSub1);
99607 return 1;
99609 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
99612 ** Based on the contents of the AggInfo structure indicated by the first
99613 ** argument, this function checks if the following are true:
99615 ** * the query contains just a single aggregate function,
99616 ** * the aggregate function is either min() or max(), and
99617 ** * the argument to the aggregate function is a column value.
99619 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
99620 ** is returned as appropriate. Also, *ppMinMax is set to point to the
99621 ** list of arguments passed to the aggregate before returning.
99623 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
99624 ** WHERE_ORDERBY_NORMAL is returned.
99626 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
99627 int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
99629 *ppMinMax = 0;
99630 if( pAggInfo->nFunc==1 ){
99631 Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
99632 ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
99634 assert( pExpr->op==TK_AGG_FUNCTION );
99635 if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
99636 const char *zFunc = pExpr->u.zToken;
99637 if( sqlite3StrICmp(zFunc, "min")==0 ){
99638 eRet = WHERE_ORDERBY_MIN;
99639 *ppMinMax = pEList;
99640 }else if( sqlite3StrICmp(zFunc, "max")==0 ){
99641 eRet = WHERE_ORDERBY_MAX;
99642 *ppMinMax = pEList;
99647 assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
99648 return eRet;
99652 ** The select statement passed as the first argument is an aggregate query.
99653 ** The second argment is the associated aggregate-info object. This
99654 ** function tests if the SELECT is of the form:
99656 ** SELECT count(*) FROM <tbl>
99658 ** where table is a database table, not a sub-select or view. If the query
99659 ** does match this pattern, then a pointer to the Table object representing
99660 ** <tbl> is returned. Otherwise, 0 is returned.
99662 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
99663 Table *pTab;
99664 Expr *pExpr;
99666 assert( !p->pGroupBy );
99668 if( p->pWhere || p->pEList->nExpr!=1
99669 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
99671 return 0;
99673 pTab = p->pSrc->a[0].pTab;
99674 pExpr = p->pEList->a[0].pExpr;
99675 assert( pTab && !pTab->pSelect && pExpr );
99677 if( IsVirtual(pTab) ) return 0;
99678 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
99679 if( NEVER(pAggInfo->nFunc==0) ) return 0;
99680 if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
99681 if( pExpr->flags&EP_Distinct ) return 0;
99683 return pTab;
99687 ** If the source-list item passed as an argument was augmented with an
99688 ** INDEXED BY clause, then try to locate the specified index. If there
99689 ** was such a clause and the named index cannot be found, return
99690 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
99691 ** pFrom->pIndex and return SQLITE_OK.
99693 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
99694 if( pFrom->pTab && pFrom->zIndex ){
99695 Table *pTab = pFrom->pTab;
99696 char *zIndex = pFrom->zIndex;
99697 Index *pIdx;
99698 for(pIdx=pTab->pIndex;
99699 pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
99700 pIdx=pIdx->pNext
99702 if( !pIdx ){
99703 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
99704 pParse->checkSchema = 1;
99705 return SQLITE_ERROR;
99707 pFrom->pIndex = pIdx;
99709 return SQLITE_OK;
99712 ** Detect compound SELECT statements that use an ORDER BY clause with
99713 ** an alternative collating sequence.
99715 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
99717 ** These are rewritten as a subquery:
99719 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
99720 ** ORDER BY ... COLLATE ...
99722 ** This transformation is necessary because the multiSelectOrderBy() routine
99723 ** above that generates the code for a compound SELECT with an ORDER BY clause
99724 ** uses a merge algorithm that requires the same collating sequence on the
99725 ** result columns as on the ORDER BY clause. See ticket
99726 ** http://www.sqlite.org/src/info/6709574d2a
99728 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
99729 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
99730 ** there are COLLATE terms in the ORDER BY.
99732 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
99733 int i;
99734 Select *pNew;
99735 Select *pX;
99736 sqlite3 *db;
99737 struct ExprList_item *a;
99738 SrcList *pNewSrc;
99739 Parse *pParse;
99740 Token dummy;
99742 if( p->pPrior==0 ) return WRC_Continue;
99743 if( p->pOrderBy==0 ) return WRC_Continue;
99744 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
99745 if( pX==0 ) return WRC_Continue;
99746 a = p->pOrderBy->a;
99747 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
99748 if( a[i].pExpr->flags & EP_Collate ) break;
99750 if( i<0 ) return WRC_Continue;
99752 /* If we reach this point, that means the transformation is required. */
99754 pParse = pWalker->pParse;
99755 db = pParse->db;
99756 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
99757 if( pNew==0 ) return WRC_Abort;
99758 memset(&dummy, 0, sizeof(dummy));
99759 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
99760 if( pNewSrc==0 ) return WRC_Abort;
99761 *pNew = *p;
99762 p->pSrc = pNewSrc;
99763 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
99764 p->op = TK_SELECT;
99765 p->pWhere = 0;
99766 pNew->pGroupBy = 0;
99767 pNew->pHaving = 0;
99768 pNew->pOrderBy = 0;
99769 p->pPrior = 0;
99770 pNew->pLimit = 0;
99771 pNew->pOffset = 0;
99772 return WRC_Continue;
99776 ** This routine is a Walker callback for "expanding" a SELECT statement.
99777 ** "Expanding" means to do the following:
99779 ** (1) Make sure VDBE cursor numbers have been assigned to every
99780 ** element of the FROM clause.
99782 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
99783 ** defines FROM clause. When views appear in the FROM clause,
99784 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
99785 ** that implements the view. A copy is made of the view's SELECT
99786 ** statement so that we can freely modify or delete that statement
99787 ** without worrying about messing up the presistent representation
99788 ** of the view.
99790 ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
99791 ** on joins and the ON and USING clause of joins.
99793 ** (4) Scan the list of columns in the result set (pEList) looking
99794 ** for instances of the "*" operator or the TABLE.* operator.
99795 ** If found, expand each "*" to be every column in every table
99796 ** and TABLE.* to be every column in TABLE.
99799 static int selectExpander(Walker *pWalker, Select *p){
99800 Parse *pParse = pWalker->pParse;
99801 int i, j, k;
99802 SrcList *pTabList;
99803 ExprList *pEList;
99804 struct SrcList_item *pFrom;
99805 sqlite3 *db = pParse->db;
99806 Expr *pE, *pRight, *pExpr;
99807 u16 selFlags = p->selFlags;
99809 p->selFlags |= SF_Expanded;
99810 if( db->mallocFailed ){
99811 return WRC_Abort;
99813 if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
99814 return WRC_Prune;
99816 pTabList = p->pSrc;
99817 pEList = p->pEList;
99819 /* Make sure cursor numbers have been assigned to all entries in
99820 ** the FROM clause of the SELECT statement.
99822 sqlite3SrcListAssignCursors(pParse, pTabList);
99824 /* Look up every table named in the FROM clause of the select. If
99825 ** an entry of the FROM clause is a subquery instead of a table or view,
99826 ** then create a transient table structure to describe the subquery.
99828 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99829 Table *pTab;
99830 if( pFrom->pTab!=0 ){
99831 /* This statement has already been prepared. There is no need
99832 ** to go further. */
99833 assert( i==0 );
99834 return WRC_Prune;
99836 if( pFrom->zName==0 ){
99837 #ifndef SQLITE_OMIT_SUBQUERY
99838 Select *pSel = pFrom->pSelect;
99839 /* A sub-query in the FROM clause of a SELECT */
99840 assert( pSel!=0 );
99841 assert( pFrom->pTab==0 );
99842 sqlite3WalkSelect(pWalker, pSel);
99843 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
99844 if( pTab==0 ) return WRC_Abort;
99845 pTab->nRef = 1;
99846 pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
99847 while( pSel->pPrior ){ pSel = pSel->pPrior; }
99848 selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
99849 pTab->iPKey = -1;
99850 pTab->nRowEst = 1000000;
99851 pTab->tabFlags |= TF_Ephemeral;
99852 #endif
99853 }else{
99854 /* An ordinary table or view name in the FROM clause */
99855 assert( pFrom->pTab==0 );
99856 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
99857 if( pTab==0 ) return WRC_Abort;
99858 if( pTab->nRef==0xffff ){
99859 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
99860 pTab->zName);
99861 pFrom->pTab = 0;
99862 return WRC_Abort;
99864 pTab->nRef++;
99865 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
99866 if( pTab->pSelect || IsVirtual(pTab) ){
99867 /* We reach here if the named table is a really a view */
99868 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
99869 assert( pFrom->pSelect==0 );
99870 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
99871 sqlite3WalkSelect(pWalker, pFrom->pSelect);
99873 #endif
99876 /* Locate the index named by the INDEXED BY clause, if any. */
99877 if( sqlite3IndexedByLookup(pParse, pFrom) ){
99878 return WRC_Abort;
99882 /* Process NATURAL keywords, and ON and USING clauses of joins.
99884 if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
99885 return WRC_Abort;
99888 /* For every "*" that occurs in the column list, insert the names of
99889 ** all columns in all tables. And for every TABLE.* insert the names
99890 ** of all columns in TABLE. The parser inserted a special expression
99891 ** with the TK_ALL operator for each "*" that it found in the column list.
99892 ** The following code just has to locate the TK_ALL expressions and expand
99893 ** each one to the list of all columns in all tables.
99895 ** The first loop just checks to see if there are any "*" operators
99896 ** that need expanding.
99898 for(k=0; k<pEList->nExpr; k++){
99899 pE = pEList->a[k].pExpr;
99900 if( pE->op==TK_ALL ) break;
99901 assert( pE->op!=TK_DOT || pE->pRight!=0 );
99902 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
99903 if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
99905 if( k<pEList->nExpr ){
99907 ** If we get here it means the result set contains one or more "*"
99908 ** operators that need to be expanded. Loop through each expression
99909 ** in the result set and expand them one by one.
99911 struct ExprList_item *a = pEList->a;
99912 ExprList *pNew = 0;
99913 int flags = pParse->db->flags;
99914 int longNames = (flags & SQLITE_FullColNames)!=0
99915 && (flags & SQLITE_ShortColNames)==0;
99917 /* When processing FROM-clause subqueries, it is always the case
99918 ** that full_column_names=OFF and short_column_names=ON. The
99919 ** sqlite3ResultSetOfSelect() routine makes it so. */
99920 assert( (p->selFlags & SF_NestedFrom)==0
99921 || ((flags & SQLITE_FullColNames)==0 &&
99922 (flags & SQLITE_ShortColNames)!=0) );
99924 for(k=0; k<pEList->nExpr; k++){
99925 pE = a[k].pExpr;
99926 pRight = pE->pRight;
99927 assert( pE->op!=TK_DOT || pRight!=0 );
99928 if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
99929 /* This particular expression does not need to be expanded.
99931 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
99932 if( pNew ){
99933 pNew->a[pNew->nExpr-1].zName = a[k].zName;
99934 pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
99935 a[k].zName = 0;
99936 a[k].zSpan = 0;
99938 a[k].pExpr = 0;
99939 }else{
99940 /* This expression is a "*" or a "TABLE.*" and needs to be
99941 ** expanded. */
99942 int tableSeen = 0; /* Set to 1 when TABLE matches */
99943 char *zTName = 0; /* text of name of TABLE */
99944 if( pE->op==TK_DOT ){
99945 assert( pE->pLeft!=0 );
99946 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
99947 zTName = pE->pLeft->u.zToken;
99949 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99950 Table *pTab = pFrom->pTab;
99951 Select *pSub = pFrom->pSelect;
99952 char *zTabName = pFrom->zAlias;
99953 const char *zSchemaName = 0;
99954 int iDb;
99955 if( zTabName==0 ){
99956 zTabName = pTab->zName;
99958 if( db->mallocFailed ) break;
99959 if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
99960 pSub = 0;
99961 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
99962 continue;
99964 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99965 zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
99967 for(j=0; j<pTab->nCol; j++){
99968 char *zName = pTab->aCol[j].zName;
99969 char *zColname; /* The computed column name */
99970 char *zToFree; /* Malloced string that needs to be freed */
99971 Token sColname; /* Computed column name as a token */
99973 assert( zName );
99974 if( zTName && pSub
99975 && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
99977 continue;
99980 /* If a column is marked as 'hidden' (currently only possible
99981 ** for virtual tables), do not include it in the expanded
99982 ** result-set list.
99984 if( IsHiddenColumn(&pTab->aCol[j]) ){
99985 assert(IsVirtual(pTab));
99986 continue;
99988 tableSeen = 1;
99990 if( i>0 && zTName==0 ){
99991 if( (pFrom->jointype & JT_NATURAL)!=0
99992 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
99994 /* In a NATURAL join, omit the join columns from the
99995 ** table to the right of the join */
99996 continue;
99998 if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
99999 /* In a join with a USING clause, omit columns in the
100000 ** using clause from the table on the right. */
100001 continue;
100004 pRight = sqlite3Expr(db, TK_ID, zName);
100005 zColname = zName;
100006 zToFree = 0;
100007 if( longNames || pTabList->nSrc>1 ){
100008 Expr *pLeft;
100009 pLeft = sqlite3Expr(db, TK_ID, zTabName);
100010 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
100011 if( zSchemaName ){
100012 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
100013 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
100015 if( longNames ){
100016 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
100017 zToFree = zColname;
100019 }else{
100020 pExpr = pRight;
100022 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
100023 sColname.z = zColname;
100024 sColname.n = sqlite3Strlen30(zColname);
100025 sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
100026 if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
100027 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
100028 if( pSub ){
100029 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
100030 testcase( pX->zSpan==0 );
100031 }else{
100032 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
100033 zSchemaName, zTabName, zColname);
100034 testcase( pX->zSpan==0 );
100036 pX->bSpanIsTab = 1;
100038 sqlite3DbFree(db, zToFree);
100041 if( !tableSeen ){
100042 if( zTName ){
100043 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
100044 }else{
100045 sqlite3ErrorMsg(pParse, "no tables specified");
100050 sqlite3ExprListDelete(db, pEList);
100051 p->pEList = pNew;
100053 #if SQLITE_MAX_COLUMN
100054 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
100055 sqlite3ErrorMsg(pParse, "too many columns in result set");
100057 #endif
100058 return WRC_Continue;
100062 ** No-op routine for the parse-tree walker.
100064 ** When this routine is the Walker.xExprCallback then expression trees
100065 ** are walked without any actions being taken at each node. Presumably,
100066 ** when this routine is used for Walker.xExprCallback then
100067 ** Walker.xSelectCallback is set to do something useful for every
100068 ** subquery in the parser tree.
100070 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
100071 UNUSED_PARAMETER2(NotUsed, NotUsed2);
100072 return WRC_Continue;
100076 ** This routine "expands" a SELECT statement and all of its subqueries.
100077 ** For additional information on what it means to "expand" a SELECT
100078 ** statement, see the comment on the selectExpand worker callback above.
100080 ** Expanding a SELECT statement is the first step in processing a
100081 ** SELECT statement. The SELECT statement must be expanded before
100082 ** name resolution is performed.
100084 ** If anything goes wrong, an error message is written into pParse.
100085 ** The calling function can detect the problem by looking at pParse->nErr
100086 ** and/or pParse->db->mallocFailed.
100088 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
100089 Walker w;
100090 memset(&w, 0, sizeof(w));
100091 w.xExprCallback = exprWalkNoop;
100092 w.pParse = pParse;
100093 if( pParse->hasCompound ){
100094 w.xSelectCallback = convertCompoundSelectToSubquery;
100095 sqlite3WalkSelect(&w, pSelect);
100097 w.xSelectCallback = selectExpander;
100098 sqlite3WalkSelect(&w, pSelect);
100102 #ifndef SQLITE_OMIT_SUBQUERY
100104 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
100105 ** interface.
100107 ** For each FROM-clause subquery, add Column.zType and Column.zColl
100108 ** information to the Table structure that represents the result set
100109 ** of that subquery.
100111 ** The Table structure that represents the result set was constructed
100112 ** by selectExpander() but the type and collation information was omitted
100113 ** at that point because identifiers had not yet been resolved. This
100114 ** routine is called after identifier resolution.
100116 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
100117 Parse *pParse;
100118 int i;
100119 SrcList *pTabList;
100120 struct SrcList_item *pFrom;
100122 assert( p->selFlags & SF_Resolved );
100123 if( (p->selFlags & SF_HasTypeInfo)==0 ){
100124 p->selFlags |= SF_HasTypeInfo;
100125 pParse = pWalker->pParse;
100126 pTabList = p->pSrc;
100127 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
100128 Table *pTab = pFrom->pTab;
100129 if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
100130 /* A sub-query in the FROM clause of a SELECT */
100131 Select *pSel = pFrom->pSelect;
100132 assert( pSel );
100133 while( pSel->pPrior ) pSel = pSel->pPrior;
100134 selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
100138 return WRC_Continue;
100140 #endif
100144 ** This routine adds datatype and collating sequence information to
100145 ** the Table structures of all FROM-clause subqueries in a
100146 ** SELECT statement.
100148 ** Use this routine after name resolution.
100150 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
100151 #ifndef SQLITE_OMIT_SUBQUERY
100152 Walker w;
100153 memset(&w, 0, sizeof(w));
100154 w.xSelectCallback = selectAddSubqueryTypeInfo;
100155 w.xExprCallback = exprWalkNoop;
100156 w.pParse = pParse;
100157 w.bSelectDepthFirst = 1;
100158 sqlite3WalkSelect(&w, pSelect);
100159 #endif
100164 ** This routine sets up a SELECT statement for processing. The
100165 ** following is accomplished:
100167 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
100168 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
100169 ** * ON and USING clauses are shifted into WHERE statements
100170 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
100171 ** * Identifiers in expression are matched to tables.
100173 ** This routine acts recursively on all subqueries within the SELECT.
100175 SQLITE_PRIVATE void sqlite3SelectPrep(
100176 Parse *pParse, /* The parser context */
100177 Select *p, /* The SELECT statement being coded. */
100178 NameContext *pOuterNC /* Name context for container */
100180 sqlite3 *db;
100181 if( NEVER(p==0) ) return;
100182 db = pParse->db;
100183 if( db->mallocFailed ) return;
100184 if( p->selFlags & SF_HasTypeInfo ) return;
100185 sqlite3SelectExpand(pParse, p);
100186 if( pParse->nErr || db->mallocFailed ) return;
100187 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
100188 if( pParse->nErr || db->mallocFailed ) return;
100189 sqlite3SelectAddTypeInfo(pParse, p);
100193 ** Reset the aggregate accumulator.
100195 ** The aggregate accumulator is a set of memory cells that hold
100196 ** intermediate results while calculating an aggregate. This
100197 ** routine generates code that stores NULLs in all of those memory
100198 ** cells.
100200 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
100201 Vdbe *v = pParse->pVdbe;
100202 int i;
100203 struct AggInfo_func *pFunc;
100204 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
100205 return;
100207 for(i=0; i<pAggInfo->nColumn; i++){
100208 sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
100210 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
100211 sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
100212 if( pFunc->iDistinct>=0 ){
100213 Expr *pE = pFunc->pExpr;
100214 assert( !ExprHasProperty(pE, EP_xIsSelect) );
100215 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
100216 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
100217 "argument");
100218 pFunc->iDistinct = -1;
100219 }else{
100220 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
100221 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
100222 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
100229 ** Invoke the OP_AggFinalize opcode for every aggregate function
100230 ** in the AggInfo structure.
100232 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
100233 Vdbe *v = pParse->pVdbe;
100234 int i;
100235 struct AggInfo_func *pF;
100236 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
100237 ExprList *pList = pF->pExpr->x.pList;
100238 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
100239 sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
100240 (void*)pF->pFunc, P4_FUNCDEF);
100245 ** Update the accumulator memory cells for an aggregate based on
100246 ** the current cursor position.
100248 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
100249 Vdbe *v = pParse->pVdbe;
100250 int i;
100251 int regHit = 0;
100252 int addrHitTest = 0;
100253 struct AggInfo_func *pF;
100254 struct AggInfo_col *pC;
100256 pAggInfo->directMode = 1;
100257 sqlite3ExprCacheClear(pParse);
100258 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
100259 int nArg;
100260 int addrNext = 0;
100261 int regAgg;
100262 ExprList *pList = pF->pExpr->x.pList;
100263 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
100264 if( pList ){
100265 nArg = pList->nExpr;
100266 regAgg = sqlite3GetTempRange(pParse, nArg);
100267 sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
100268 }else{
100269 nArg = 0;
100270 regAgg = 0;
100272 if( pF->iDistinct>=0 ){
100273 addrNext = sqlite3VdbeMakeLabel(v);
100274 assert( nArg==1 );
100275 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
100277 if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
100278 CollSeq *pColl = 0;
100279 struct ExprList_item *pItem;
100280 int j;
100281 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
100282 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
100283 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
100285 if( !pColl ){
100286 pColl = pParse->db->pDfltColl;
100288 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
100289 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
100291 sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
100292 (void*)pF->pFunc, P4_FUNCDEF);
100293 sqlite3VdbeChangeP5(v, (u8)nArg);
100294 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
100295 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
100296 if( addrNext ){
100297 sqlite3VdbeResolveLabel(v, addrNext);
100298 sqlite3ExprCacheClear(pParse);
100302 /* Before populating the accumulator registers, clear the column cache.
100303 ** Otherwise, if any of the required column values are already present
100304 ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
100305 ** to pC->iMem. But by the time the value is used, the original register
100306 ** may have been used, invalidating the underlying buffer holding the
100307 ** text or blob value. See ticket [883034dcb5].
100309 ** Another solution would be to change the OP_SCopy used to copy cached
100310 ** values to an OP_Copy.
100312 if( regHit ){
100313 addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
100315 sqlite3ExprCacheClear(pParse);
100316 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
100317 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
100319 pAggInfo->directMode = 0;
100320 sqlite3ExprCacheClear(pParse);
100321 if( addrHitTest ){
100322 sqlite3VdbeJumpHere(v, addrHitTest);
100327 ** Add a single OP_Explain instruction to the VDBE to explain a simple
100328 ** count(*) query ("SELECT count(*) FROM pTab").
100330 #ifndef SQLITE_OMIT_EXPLAIN
100331 static void explainSimpleCount(
100332 Parse *pParse, /* Parse context */
100333 Table *pTab, /* Table being queried */
100334 Index *pIdx /* Index used to optimize scan, or NULL */
100336 if( pParse->explain==2 ){
100337 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
100338 pTab->zName,
100339 pIdx ? " USING COVERING INDEX " : "",
100340 pIdx ? pIdx->zName : ""
100342 sqlite3VdbeAddOp4(
100343 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
100347 #else
100348 # define explainSimpleCount(a,b,c)
100349 #endif
100352 ** Generate code for the SELECT statement given in the p argument.
100354 ** The results are distributed in various ways depending on the
100355 ** contents of the SelectDest structure pointed to by argument pDest
100356 ** as follows:
100358 ** pDest->eDest Result
100359 ** ------------ -------------------------------------------
100360 ** SRT_Output Generate a row of output (using the OP_ResultRow
100361 ** opcode) for each row in the result set.
100363 ** SRT_Mem Only valid if the result is a single column.
100364 ** Store the first column of the first result row
100365 ** in register pDest->iSDParm then abandon the rest
100366 ** of the query. This destination implies "LIMIT 1".
100368 ** SRT_Set The result must be a single column. Store each
100369 ** row of result as the key in table pDest->iSDParm.
100370 ** Apply the affinity pDest->affSdst before storing
100371 ** results. Used to implement "IN (SELECT ...)".
100373 ** SRT_Union Store results as a key in a temporary table
100374 ** identified by pDest->iSDParm.
100376 ** SRT_Except Remove results from the temporary table pDest->iSDParm.
100378 ** SRT_Table Store results in temporary table pDest->iSDParm.
100379 ** This is like SRT_EphemTab except that the table
100380 ** is assumed to already be open.
100382 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
100383 ** the result there. The cursor is left open after
100384 ** returning. This is like SRT_Table except that
100385 ** this destination uses OP_OpenEphemeral to create
100386 ** the table first.
100388 ** SRT_Coroutine Generate a co-routine that returns a new row of
100389 ** results each time it is invoked. The entry point
100390 ** of the co-routine is stored in register pDest->iSDParm.
100392 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
100393 ** set is not empty.
100395 ** SRT_Discard Throw the results away. This is used by SELECT
100396 ** statements within triggers whose only purpose is
100397 ** the side-effects of functions.
100399 ** This routine returns the number of errors. If any errors are
100400 ** encountered, then an appropriate error message is left in
100401 ** pParse->zErrMsg.
100403 ** This routine does NOT free the Select structure passed in. The
100404 ** calling function needs to do that.
100406 SQLITE_PRIVATE int sqlite3Select(
100407 Parse *pParse, /* The parser context */
100408 Select *p, /* The SELECT statement being coded. */
100409 SelectDest *pDest /* What to do with the query results */
100411 int i, j; /* Loop counters */
100412 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
100413 Vdbe *v; /* The virtual machine under construction */
100414 int isAgg; /* True for select lists like "count(*)" */
100415 ExprList *pEList; /* List of columns to extract. */
100416 SrcList *pTabList; /* List of tables to select from */
100417 Expr *pWhere; /* The WHERE clause. May be NULL */
100418 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
100419 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
100420 Expr *pHaving; /* The HAVING clause. May be NULL */
100421 int rc = 1; /* Value to return from this function */
100422 int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
100423 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
100424 AggInfo sAggInfo; /* Information used by aggregate queries */
100425 int iEnd; /* Address of the end of the query */
100426 sqlite3 *db; /* The database connection */
100428 #ifndef SQLITE_OMIT_EXPLAIN
100429 int iRestoreSelectId = pParse->iSelectId;
100430 pParse->iSelectId = pParse->iNextSelectId++;
100431 #endif
100433 db = pParse->db;
100434 if( p==0 || db->mallocFailed || pParse->nErr ){
100435 return 1;
100437 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
100438 memset(&sAggInfo, 0, sizeof(sAggInfo));
100440 if( IgnorableOrderby(pDest) ){
100441 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
100442 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
100443 /* If ORDER BY makes no difference in the output then neither does
100444 ** DISTINCT so it can be removed too. */
100445 sqlite3ExprListDelete(db, p->pOrderBy);
100446 p->pOrderBy = 0;
100447 p->selFlags &= ~SF_Distinct;
100449 sqlite3SelectPrep(pParse, p, 0);
100450 pOrderBy = p->pOrderBy;
100451 pTabList = p->pSrc;
100452 pEList = p->pEList;
100453 if( pParse->nErr || db->mallocFailed ){
100454 goto select_end;
100456 isAgg = (p->selFlags & SF_Aggregate)!=0;
100457 assert( pEList!=0 );
100459 /* Begin generating code.
100461 v = sqlite3GetVdbe(pParse);
100462 if( v==0 ) goto select_end;
100464 /* If writing to memory or generating a set
100465 ** only a single column may be output.
100467 #ifndef SQLITE_OMIT_SUBQUERY
100468 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
100469 goto select_end;
100471 #endif
100473 /* Generate code for all sub-queries in the FROM clause
100475 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
100476 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
100477 struct SrcList_item *pItem = &pTabList->a[i];
100478 SelectDest dest;
100479 Select *pSub = pItem->pSelect;
100480 int isAggSub;
100482 if( pSub==0 ) continue;
100484 /* Sometimes the code for a subquery will be generated more than
100485 ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
100486 ** for example. In that case, do not regenerate the code to manifest
100487 ** a view or the co-routine to implement a view. The first instance
100488 ** is sufficient, though the subroutine to manifest the view does need
100489 ** to be invoked again. */
100490 if( pItem->addrFillSub ){
100491 if( pItem->viaCoroutine==0 ){
100492 sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
100494 continue;
100497 /* Increment Parse.nHeight by the height of the largest expression
100498 ** tree referred to by this, the parent select. The child select
100499 ** may contain expression trees of at most
100500 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
100501 ** more conservative than necessary, but much easier than enforcing
100502 ** an exact limit.
100504 pParse->nHeight += sqlite3SelectExprHeight(p);
100506 isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
100507 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
100508 /* This subquery can be absorbed into its parent. */
100509 if( isAggSub ){
100510 isAgg = 1;
100511 p->selFlags |= SF_Aggregate;
100513 i = -1;
100514 }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
100515 && OptimizationEnabled(db, SQLITE_SubqCoroutine)
100517 /* Implement a co-routine that will return a single row of the result
100518 ** set on each invocation.
100520 int addrTop;
100521 int addrEof;
100522 pItem->regReturn = ++pParse->nMem;
100523 addrEof = ++pParse->nMem;
100524 /* Before coding the OP_Goto to jump to the start of the main routine,
100525 ** ensure that the jump to the verify-schema routine has already
100526 ** been coded. Otherwise, the verify-schema would likely be coded as
100527 ** part of the co-routine. If the main routine then accessed the
100528 ** database before invoking the co-routine for the first time (for
100529 ** example to initialize a LIMIT register from a sub-select), it would
100530 ** be doing so without having verified the schema version and obtained
100531 ** the required db locks. See ticket d6b36be38. */
100532 sqlite3CodeVerifySchema(pParse, -1);
100533 sqlite3VdbeAddOp0(v, OP_Goto);
100534 addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
100535 sqlite3VdbeChangeP5(v, 1);
100536 VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
100537 pItem->addrFillSub = addrTop;
100538 sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
100539 sqlite3VdbeChangeP5(v, 1);
100540 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
100541 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
100542 sqlite3Select(pParse, pSub, &dest);
100543 pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
100544 pItem->viaCoroutine = 1;
100545 sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
100546 sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
100547 sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
100548 sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
100549 VdbeComment((v, "end %s", pItem->pTab->zName));
100550 sqlite3VdbeJumpHere(v, addrTop-1);
100551 sqlite3ClearTempRegCache(pParse);
100552 }else{
100553 /* Generate a subroutine that will fill an ephemeral table with
100554 ** the content of this subquery. pItem->addrFillSub will point
100555 ** to the address of the generated subroutine. pItem->regReturn
100556 ** is a register allocated to hold the subroutine return address
100558 int topAddr;
100559 int onceAddr = 0;
100560 int retAddr;
100561 assert( pItem->addrFillSub==0 );
100562 pItem->regReturn = ++pParse->nMem;
100563 topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
100564 pItem->addrFillSub = topAddr+1;
100565 VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
100566 if( pItem->isCorrelated==0 ){
100567 /* If the subquery is not correlated and if we are not inside of
100568 ** a trigger, then we only need to compute the value of the subquery
100569 ** once. */
100570 onceAddr = sqlite3CodeOnce(pParse);
100572 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
100573 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
100574 sqlite3Select(pParse, pSub, &dest);
100575 pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
100576 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
100577 retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
100578 VdbeComment((v, "end %s", pItem->pTab->zName));
100579 sqlite3VdbeChangeP1(v, topAddr, retAddr);
100580 sqlite3ClearTempRegCache(pParse);
100582 if( /*pParse->nErr ||*/ db->mallocFailed ){
100583 goto select_end;
100585 pParse->nHeight -= sqlite3SelectExprHeight(p);
100586 pTabList = p->pSrc;
100587 if( !IgnorableOrderby(pDest) ){
100588 pOrderBy = p->pOrderBy;
100591 pEList = p->pEList;
100592 #endif
100593 pWhere = p->pWhere;
100594 pGroupBy = p->pGroupBy;
100595 pHaving = p->pHaving;
100596 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
100598 #ifndef SQLITE_OMIT_COMPOUND_SELECT
100599 /* If there is are a sequence of queries, do the earlier ones first.
100601 if( p->pPrior ){
100602 if( p->pRightmost==0 ){
100603 Select *pLoop, *pRight = 0;
100604 int cnt = 0;
100605 int mxSelect;
100606 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
100607 pLoop->pRightmost = p;
100608 pLoop->pNext = pRight;
100609 pRight = pLoop;
100611 mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
100612 if( mxSelect && cnt>mxSelect ){
100613 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
100614 goto select_end;
100617 rc = multiSelect(pParse, p, pDest);
100618 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
100619 return rc;
100621 #endif
100623 /* If there is both a GROUP BY and an ORDER BY clause and they are
100624 ** identical, then disable the ORDER BY clause since the GROUP BY
100625 ** will cause elements to come out in the correct order. This is
100626 ** an optimization - the correct answer should result regardless.
100627 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
100628 ** to disable this optimization for testing purposes.
100630 if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
100631 && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
100632 pOrderBy = 0;
100635 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
100636 ** if the select-list is the same as the ORDER BY list, then this query
100637 ** can be rewritten as a GROUP BY. In other words, this:
100639 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
100641 ** is transformed to:
100643 ** SELECT xyz FROM ... GROUP BY xyz
100645 ** The second form is preferred as a single index (or temp-table) may be
100646 ** used for both the ORDER BY and DISTINCT processing. As originally
100647 ** written the query must use a temp-table for at least one of the ORDER
100648 ** BY and DISTINCT, and an index or separate temp-table for the other.
100650 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
100651 && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
100653 p->selFlags &= ~SF_Distinct;
100654 p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
100655 pGroupBy = p->pGroupBy;
100656 pOrderBy = 0;
100657 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
100658 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
100659 ** original setting of the SF_Distinct flag, not the current setting */
100660 assert( sDistinct.isTnct );
100663 /* If there is an ORDER BY clause, then this sorting
100664 ** index might end up being unused if the data can be
100665 ** extracted in pre-sorted order. If that is the case, then the
100666 ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
100667 ** we figure out that the sorting index is not needed. The addrSortIndex
100668 ** variable is used to facilitate that change.
100670 if( pOrderBy ){
100671 KeyInfo *pKeyInfo;
100672 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
100673 pOrderBy->iECursor = pParse->nTab++;
100674 p->addrOpenEphm[2] = addrSortIndex =
100675 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
100676 pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
100677 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
100678 }else{
100679 addrSortIndex = -1;
100682 /* If the output is destined for a temporary table, open that table.
100684 if( pDest->eDest==SRT_EphemTab ){
100685 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
100688 /* Set the limiter.
100690 iEnd = sqlite3VdbeMakeLabel(v);
100691 p->nSelectRow = LARGEST_INT64;
100692 computeLimitRegisters(pParse, p, iEnd);
100693 if( p->iLimit==0 && addrSortIndex>=0 ){
100694 sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
100695 p->selFlags |= SF_UseSorter;
100698 /* Open a virtual index to use for the distinct set.
100700 if( p->selFlags & SF_Distinct ){
100701 sDistinct.tabTnct = pParse->nTab++;
100702 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
100703 sDistinct.tabTnct, 0, 0,
100704 (char*)keyInfoFromExprList(pParse, p->pEList),
100705 P4_KEYINFO_HANDOFF);
100706 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
100707 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
100708 }else{
100709 sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
100712 if( !isAgg && pGroupBy==0 ){
100713 /* No aggregate functions and no GROUP BY clause */
100714 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
100716 /* Begin the database scan. */
100717 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList,
100718 wctrlFlags, 0);
100719 if( pWInfo==0 ) goto select_end;
100720 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
100721 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
100723 if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
100724 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
100726 if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
100728 /* If sorting index that was created by a prior OP_OpenEphemeral
100729 ** instruction ended up not being needed, then change the OP_OpenEphemeral
100730 ** into an OP_Noop.
100732 if( addrSortIndex>=0 && pOrderBy==0 ){
100733 sqlite3VdbeChangeToNoop(v, addrSortIndex);
100734 p->addrOpenEphm[2] = -1;
100737 /* Use the standard inner loop. */
100738 selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
100739 sqlite3WhereContinueLabel(pWInfo),
100740 sqlite3WhereBreakLabel(pWInfo));
100742 /* End the database scan loop.
100744 sqlite3WhereEnd(pWInfo);
100745 }else{
100746 /* This case when there exist aggregate functions or a GROUP BY clause
100747 ** or both */
100748 NameContext sNC; /* Name context for processing aggregate information */
100749 int iAMem; /* First Mem address for storing current GROUP BY */
100750 int iBMem; /* First Mem address for previous GROUP BY */
100751 int iUseFlag; /* Mem address holding flag indicating that at least
100752 ** one row of the input to the aggregator has been
100753 ** processed */
100754 int iAbortFlag; /* Mem address which causes query abort if positive */
100755 int groupBySort; /* Rows come from source in GROUP BY order */
100756 int addrEnd; /* End of processing for this SELECT */
100757 int sortPTab = 0; /* Pseudotable used to decode sorting results */
100758 int sortOut = 0; /* Output register from the sorter */
100760 /* Remove any and all aliases between the result set and the
100761 ** GROUP BY clause.
100763 if( pGroupBy ){
100764 int k; /* Loop counter */
100765 struct ExprList_item *pItem; /* For looping over expression in a list */
100767 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
100768 pItem->iAlias = 0;
100770 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
100771 pItem->iAlias = 0;
100773 if( p->nSelectRow>100 ) p->nSelectRow = 100;
100774 }else{
100775 p->nSelectRow = 1;
100779 /* Create a label to jump to when we want to abort the query */
100780 addrEnd = sqlite3VdbeMakeLabel(v);
100782 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
100783 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
100784 ** SELECT statement.
100786 memset(&sNC, 0, sizeof(sNC));
100787 sNC.pParse = pParse;
100788 sNC.pSrcList = pTabList;
100789 sNC.pAggInfo = &sAggInfo;
100790 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
100791 sAggInfo.pGroupBy = pGroupBy;
100792 sqlite3ExprAnalyzeAggList(&sNC, pEList);
100793 sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
100794 if( pHaving ){
100795 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
100797 sAggInfo.nAccumulator = sAggInfo.nColumn;
100798 for(i=0; i<sAggInfo.nFunc; i++){
100799 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
100800 sNC.ncFlags |= NC_InAggFunc;
100801 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
100802 sNC.ncFlags &= ~NC_InAggFunc;
100804 if( db->mallocFailed ) goto select_end;
100806 /* Processing for aggregates with GROUP BY is very different and
100807 ** much more complex than aggregates without a GROUP BY.
100809 if( pGroupBy ){
100810 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
100811 int j1; /* A-vs-B comparision jump */
100812 int addrOutputRow; /* Start of subroutine that outputs a result row */
100813 int regOutputRow; /* Return address register for output subroutine */
100814 int addrSetAbort; /* Set the abort flag and return */
100815 int addrTopOfLoop; /* Top of the input loop */
100816 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
100817 int addrReset; /* Subroutine for resetting the accumulator */
100818 int regReset; /* Return address register for reset subroutine */
100820 /* If there is a GROUP BY clause we might need a sorting index to
100821 ** implement it. Allocate that sorting index now. If it turns out
100822 ** that we do not need it after all, the OP_SorterOpen instruction
100823 ** will be converted into a Noop.
100825 sAggInfo.sortingIdx = pParse->nTab++;
100826 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
100827 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
100828 sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
100829 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
100831 /* Initialize memory locations used by GROUP BY aggregate processing
100833 iUseFlag = ++pParse->nMem;
100834 iAbortFlag = ++pParse->nMem;
100835 regOutputRow = ++pParse->nMem;
100836 addrOutputRow = sqlite3VdbeMakeLabel(v);
100837 regReset = ++pParse->nMem;
100838 addrReset = sqlite3VdbeMakeLabel(v);
100839 iAMem = pParse->nMem + 1;
100840 pParse->nMem += pGroupBy->nExpr;
100841 iBMem = pParse->nMem + 1;
100842 pParse->nMem += pGroupBy->nExpr;
100843 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
100844 VdbeComment((v, "clear abort flag"));
100845 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
100846 VdbeComment((v, "indicate accumulator empty"));
100847 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
100849 /* Begin a loop that will extract all source rows in GROUP BY order.
100850 ** This might involve two separate loops with an OP_Sort in between, or
100851 ** it might be a single loop that uses an index to extract information
100852 ** in the right order to begin with.
100854 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100855 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
100856 WHERE_GROUPBY, 0);
100857 if( pWInfo==0 ) goto select_end;
100858 if( sqlite3WhereIsOrdered(pWInfo) ){
100859 /* The optimizer is able to deliver rows in group by order so
100860 ** we do not have to sort. The OP_OpenEphemeral table will be
100861 ** cancelled later because we still need to use the pKeyInfo
100863 groupBySort = 0;
100864 }else{
100865 /* Rows are coming out in undetermined order. We have to push
100866 ** each row into a sorting index, terminate the first loop,
100867 ** then loop over the sorting index in order to get the output
100868 ** in sorted order
100870 int regBase;
100871 int regRecord;
100872 int nCol;
100873 int nGroupBy;
100875 explainTempTable(pParse,
100876 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
100877 "DISTINCT" : "GROUP BY");
100879 groupBySort = 1;
100880 nGroupBy = pGroupBy->nExpr;
100881 nCol = nGroupBy + 1;
100882 j = nGroupBy+1;
100883 for(i=0; i<sAggInfo.nColumn; i++){
100884 if( sAggInfo.aCol[i].iSorterColumn>=j ){
100885 nCol++;
100889 regBase = sqlite3GetTempRange(pParse, nCol);
100890 sqlite3ExprCacheClear(pParse);
100891 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
100892 sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
100893 j = nGroupBy+1;
100894 for(i=0; i<sAggInfo.nColumn; i++){
100895 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
100896 if( pCol->iSorterColumn>=j ){
100897 int r1 = j + regBase;
100898 int r2;
100900 r2 = sqlite3ExprCodeGetColumn(pParse,
100901 pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
100902 if( r1!=r2 ){
100903 sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
100908 regRecord = sqlite3GetTempReg(pParse);
100909 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
100910 sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
100911 sqlite3ReleaseTempReg(pParse, regRecord);
100912 sqlite3ReleaseTempRange(pParse, regBase, nCol);
100913 sqlite3WhereEnd(pWInfo);
100914 sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
100915 sortOut = sqlite3GetTempReg(pParse);
100916 sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
100917 sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
100918 VdbeComment((v, "GROUP BY sort"));
100919 sAggInfo.useSortingIdx = 1;
100920 sqlite3ExprCacheClear(pParse);
100923 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
100924 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
100925 ** Then compare the current GROUP BY terms against the GROUP BY terms
100926 ** from the previous row currently stored in a0, a1, a2...
100928 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
100929 sqlite3ExprCacheClear(pParse);
100930 if( groupBySort ){
100931 sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
100933 for(j=0; j<pGroupBy->nExpr; j++){
100934 if( groupBySort ){
100935 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
100936 if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
100937 }else{
100938 sAggInfo.directMode = 1;
100939 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
100942 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
100943 (char*)pKeyInfo, P4_KEYINFO);
100944 j1 = sqlite3VdbeCurrentAddr(v);
100945 sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
100947 /* Generate code that runs whenever the GROUP BY changes.
100948 ** Changes in the GROUP BY are detected by the previous code
100949 ** block. If there were no changes, this block is skipped.
100951 ** This code copies current group by terms in b0,b1,b2,...
100952 ** over to a0,a1,a2. It then calls the output subroutine
100953 ** and resets the aggregate accumulator registers in preparation
100954 ** for the next GROUP BY batch.
100956 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
100957 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
100958 VdbeComment((v, "output one row"));
100959 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
100960 VdbeComment((v, "check abort flag"));
100961 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100962 VdbeComment((v, "reset accumulator"));
100964 /* Update the aggregate accumulators based on the content of
100965 ** the current row
100967 sqlite3VdbeJumpHere(v, j1);
100968 updateAccumulator(pParse, &sAggInfo);
100969 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
100970 VdbeComment((v, "indicate data in accumulator"));
100972 /* End of the loop
100974 if( groupBySort ){
100975 sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
100976 }else{
100977 sqlite3WhereEnd(pWInfo);
100978 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
100981 /* Output the final row of result
100983 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
100984 VdbeComment((v, "output final row"));
100986 /* Jump over the subroutines
100988 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
100990 /* Generate a subroutine that outputs a single row of the result
100991 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
100992 ** is less than or equal to zero, the subroutine is a no-op. If
100993 ** the processing calls for the query to abort, this subroutine
100994 ** increments the iAbortFlag memory location before returning in
100995 ** order to signal the caller to abort.
100997 addrSetAbort = sqlite3VdbeCurrentAddr(v);
100998 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
100999 VdbeComment((v, "set abort flag"));
101000 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
101001 sqlite3VdbeResolveLabel(v, addrOutputRow);
101002 addrOutputRow = sqlite3VdbeCurrentAddr(v);
101003 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
101004 VdbeComment((v, "Groupby result generator entry point"));
101005 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
101006 finalizeAggFunctions(pParse, &sAggInfo);
101007 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
101008 selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
101009 &sDistinct, pDest,
101010 addrOutputRow+1, addrSetAbort);
101011 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
101012 VdbeComment((v, "end groupby result generator"));
101014 /* Generate a subroutine that will reset the group-by accumulator
101016 sqlite3VdbeResolveLabel(v, addrReset);
101017 resetAccumulator(pParse, &sAggInfo);
101018 sqlite3VdbeAddOp1(v, OP_Return, regReset);
101020 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
101021 else {
101022 ExprList *pDel = 0;
101023 #ifndef SQLITE_OMIT_BTREECOUNT
101024 Table *pTab;
101025 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
101026 /* If isSimpleCount() returns a pointer to a Table structure, then
101027 ** the SQL statement is of the form:
101029 ** SELECT count(*) FROM <tbl>
101031 ** where the Table structure returned represents table <tbl>.
101033 ** This statement is so common that it is optimized specially. The
101034 ** OP_Count instruction is executed either on the intkey table that
101035 ** contains the data for table <tbl> or on one of its indexes. It
101036 ** is better to execute the op on an index, as indexes are almost
101037 ** always spread across less pages than their corresponding tables.
101039 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
101040 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
101041 Index *pIdx; /* Iterator variable */
101042 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
101043 Index *pBest = 0; /* Best index found so far */
101044 int iRoot = pTab->tnum; /* Root page of scanned b-tree */
101046 sqlite3CodeVerifySchema(pParse, iDb);
101047 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
101049 /* Search for the index that has the least amount of columns. If
101050 ** there is such an index, and it has less columns than the table
101051 ** does, then we can assume that it consumes less space on disk and
101052 ** will therefore be cheaper to scan to determine the query result.
101053 ** In this case set iRoot to the root page number of the index b-tree
101054 ** and pKeyInfo to the KeyInfo structure required to navigate the
101055 ** index.
101057 ** (2011-04-15) Do not do a full scan of an unordered index.
101059 ** In practice the KeyInfo structure will not be used. It is only
101060 ** passed to keep OP_OpenRead happy.
101062 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101063 if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
101064 pBest = pIdx;
101067 if( pBest && pBest->nColumn<pTab->nCol ){
101068 iRoot = pBest->tnum;
101069 pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
101072 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
101073 sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
101074 if( pKeyInfo ){
101075 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
101077 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
101078 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
101079 explainSimpleCount(pParse, pTab, pBest);
101080 }else
101081 #endif /* SQLITE_OMIT_BTREECOUNT */
101083 /* Check if the query is of one of the following forms:
101085 ** SELECT min(x) FROM ...
101086 ** SELECT max(x) FROM ...
101088 ** If it is, then ask the code in where.c to attempt to sort results
101089 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
101090 ** If where.c is able to produce results sorted in this order, then
101091 ** add vdbe code to break out of the processing loop after the
101092 ** first iteration (since the first iteration of the loop is
101093 ** guaranteed to operate on the row with the minimum or maximum
101094 ** value of x, the only row required).
101096 ** A special flag must be passed to sqlite3WhereBegin() to slightly
101097 ** modify behavior as follows:
101099 ** + If the query is a "SELECT min(x)", then the loop coded by
101100 ** where.c should not iterate over any values with a NULL value
101101 ** for x.
101103 ** + The optimizer code in where.c (the thing that decides which
101104 ** index or indices to use) should place a different priority on
101105 ** satisfying the 'ORDER BY' clause than it does in other cases.
101106 ** Refer to code and comments in where.c for details.
101108 ExprList *pMinMax = 0;
101109 u8 flag = WHERE_ORDERBY_NORMAL;
101111 assert( p->pGroupBy==0 );
101112 assert( flag==0 );
101113 if( p->pHaving==0 ){
101114 flag = minMaxQuery(&sAggInfo, &pMinMax);
101116 assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
101118 if( flag ){
101119 pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
101120 pDel = pMinMax;
101121 if( pMinMax && !db->mallocFailed ){
101122 pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
101123 pMinMax->a[0].pExpr->op = TK_COLUMN;
101127 /* This case runs if the aggregate has no GROUP BY clause. The
101128 ** processing is much simpler since there is only a single row
101129 ** of output.
101131 resetAccumulator(pParse, &sAggInfo);
101132 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
101133 if( pWInfo==0 ){
101134 sqlite3ExprListDelete(db, pDel);
101135 goto select_end;
101137 updateAccumulator(pParse, &sAggInfo);
101138 assert( pMinMax==0 || pMinMax->nExpr==1 );
101139 if( sqlite3WhereIsOrdered(pWInfo) ){
101140 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
101141 VdbeComment((v, "%s() by index",
101142 (flag==WHERE_ORDERBY_MIN?"min":"max")));
101144 sqlite3WhereEnd(pWInfo);
101145 finalizeAggFunctions(pParse, &sAggInfo);
101148 pOrderBy = 0;
101149 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
101150 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
101151 pDest, addrEnd, addrEnd);
101152 sqlite3ExprListDelete(db, pDel);
101154 sqlite3VdbeResolveLabel(v, addrEnd);
101156 } /* endif aggregate query */
101158 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
101159 explainTempTable(pParse, "DISTINCT");
101162 /* If there is an ORDER BY clause, then we need to sort the results
101163 ** and send them to the callback one by one.
101165 if( pOrderBy ){
101166 explainTempTable(pParse, "ORDER BY");
101167 generateSortTail(pParse, p, v, pEList->nExpr, pDest);
101170 /* Jump here to skip this query
101172 sqlite3VdbeResolveLabel(v, iEnd);
101174 /* The SELECT was successfully coded. Set the return code to 0
101175 ** to indicate no errors.
101177 rc = 0;
101179 /* Control jumps to here if an error is encountered above, or upon
101180 ** successful coding of the SELECT.
101182 select_end:
101183 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
101185 /* Identify column names if results of the SELECT are to be output.
101187 if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
101188 generateColumnNames(pParse, pTabList, pEList);
101191 sqlite3DbFree(db, sAggInfo.aCol);
101192 sqlite3DbFree(db, sAggInfo.aFunc);
101193 return rc;
101196 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
101198 ** Generate a human-readable description of a the Select object.
101200 static void explainOneSelect(Vdbe *pVdbe, Select *p){
101201 sqlite3ExplainPrintf(pVdbe, "SELECT ");
101202 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
101203 if( p->selFlags & SF_Distinct ){
101204 sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
101206 if( p->selFlags & SF_Aggregate ){
101207 sqlite3ExplainPrintf(pVdbe, "agg_flag ");
101209 sqlite3ExplainNL(pVdbe);
101210 sqlite3ExplainPrintf(pVdbe, " ");
101212 sqlite3ExplainExprList(pVdbe, p->pEList);
101213 sqlite3ExplainNL(pVdbe);
101214 if( p->pSrc && p->pSrc->nSrc ){
101215 int i;
101216 sqlite3ExplainPrintf(pVdbe, "FROM ");
101217 sqlite3ExplainPush(pVdbe);
101218 for(i=0; i<p->pSrc->nSrc; i++){
101219 struct SrcList_item *pItem = &p->pSrc->a[i];
101220 sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
101221 if( pItem->pSelect ){
101222 sqlite3ExplainSelect(pVdbe, pItem->pSelect);
101223 if( pItem->pTab ){
101224 sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
101226 }else if( pItem->zName ){
101227 sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
101229 if( pItem->zAlias ){
101230 sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
101232 if( pItem->jointype & JT_LEFT ){
101233 sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
101235 sqlite3ExplainNL(pVdbe);
101237 sqlite3ExplainPop(pVdbe);
101239 if( p->pWhere ){
101240 sqlite3ExplainPrintf(pVdbe, "WHERE ");
101241 sqlite3ExplainExpr(pVdbe, p->pWhere);
101242 sqlite3ExplainNL(pVdbe);
101244 if( p->pGroupBy ){
101245 sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
101246 sqlite3ExplainExprList(pVdbe, p->pGroupBy);
101247 sqlite3ExplainNL(pVdbe);
101249 if( p->pHaving ){
101250 sqlite3ExplainPrintf(pVdbe, "HAVING ");
101251 sqlite3ExplainExpr(pVdbe, p->pHaving);
101252 sqlite3ExplainNL(pVdbe);
101254 if( p->pOrderBy ){
101255 sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
101256 sqlite3ExplainExprList(pVdbe, p->pOrderBy);
101257 sqlite3ExplainNL(pVdbe);
101259 if( p->pLimit ){
101260 sqlite3ExplainPrintf(pVdbe, "LIMIT ");
101261 sqlite3ExplainExpr(pVdbe, p->pLimit);
101262 sqlite3ExplainNL(pVdbe);
101264 if( p->pOffset ){
101265 sqlite3ExplainPrintf(pVdbe, "OFFSET ");
101266 sqlite3ExplainExpr(pVdbe, p->pOffset);
101267 sqlite3ExplainNL(pVdbe);
101270 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
101271 if( p==0 ){
101272 sqlite3ExplainPrintf(pVdbe, "(null-select)");
101273 return;
101275 while( p->pPrior ){
101276 p->pPrior->pNext = p;
101277 p = p->pPrior;
101279 sqlite3ExplainPush(pVdbe);
101280 while( p ){
101281 explainOneSelect(pVdbe, p);
101282 p = p->pNext;
101283 if( p==0 ) break;
101284 sqlite3ExplainNL(pVdbe);
101285 sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
101287 sqlite3ExplainPrintf(pVdbe, "END");
101288 sqlite3ExplainPop(pVdbe);
101291 /* End of the structure debug printing code
101292 *****************************************************************************/
101293 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
101295 /************** End of select.c **********************************************/
101296 /************** Begin file table.c *******************************************/
101298 ** 2001 September 15
101300 ** The author disclaims copyright to this source code. In place of
101301 ** a legal notice, here is a blessing:
101303 ** May you do good and not evil.
101304 ** May you find forgiveness for yourself and forgive others.
101305 ** May you share freely, never taking more than you give.
101307 *************************************************************************
101308 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
101309 ** interface routines. These are just wrappers around the main
101310 ** interface routine of sqlite3_exec().
101312 ** These routines are in a separate files so that they will not be linked
101313 ** if they are not used.
101315 /* #include <stdlib.h> */
101316 /* #include <string.h> */
101318 #ifndef SQLITE_OMIT_GET_TABLE
101321 ** This structure is used to pass data from sqlite3_get_table() through
101322 ** to the callback function is uses to build the result.
101324 typedef struct TabResult {
101325 char **azResult; /* Accumulated output */
101326 char *zErrMsg; /* Error message text, if an error occurs */
101327 int nAlloc; /* Slots allocated for azResult[] */
101328 int nRow; /* Number of rows in the result */
101329 int nColumn; /* Number of columns in the result */
101330 int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
101331 int rc; /* Return code from sqlite3_exec() */
101332 } TabResult;
101335 ** This routine is called once for each row in the result table. Its job
101336 ** is to fill in the TabResult structure appropriately, allocating new
101337 ** memory as necessary.
101339 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
101340 TabResult *p = (TabResult*)pArg; /* Result accumulator */
101341 int need; /* Slots needed in p->azResult[] */
101342 int i; /* Loop counter */
101343 char *z; /* A single column of result */
101345 /* Make sure there is enough space in p->azResult to hold everything
101346 ** we need to remember from this invocation of the callback.
101348 if( p->nRow==0 && argv!=0 ){
101349 need = nCol*2;
101350 }else{
101351 need = nCol;
101353 if( p->nData + need > p->nAlloc ){
101354 char **azNew;
101355 p->nAlloc = p->nAlloc*2 + need;
101356 azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
101357 if( azNew==0 ) goto malloc_failed;
101358 p->azResult = azNew;
101361 /* If this is the first row, then generate an extra row containing
101362 ** the names of all columns.
101364 if( p->nRow==0 ){
101365 p->nColumn = nCol;
101366 for(i=0; i<nCol; i++){
101367 z = sqlite3_mprintf("%s", colv[i]);
101368 if( z==0 ) goto malloc_failed;
101369 p->azResult[p->nData++] = z;
101371 }else if( p->nColumn!=nCol ){
101372 sqlite3_free(p->zErrMsg);
101373 p->zErrMsg = sqlite3_mprintf(
101374 "sqlite3_get_table() called with two or more incompatible queries"
101376 p->rc = SQLITE_ERROR;
101377 return 1;
101380 /* Copy over the row data
101382 if( argv!=0 ){
101383 for(i=0; i<nCol; i++){
101384 if( argv[i]==0 ){
101385 z = 0;
101386 }else{
101387 int n = sqlite3Strlen30(argv[i])+1;
101388 z = sqlite3_malloc( n );
101389 if( z==0 ) goto malloc_failed;
101390 memcpy(z, argv[i], n);
101392 p->azResult[p->nData++] = z;
101394 p->nRow++;
101396 return 0;
101398 malloc_failed:
101399 p->rc = SQLITE_NOMEM;
101400 return 1;
101404 ** Query the database. But instead of invoking a callback for each row,
101405 ** malloc() for space to hold the result and return the entire results
101406 ** at the conclusion of the call.
101408 ** The result that is written to ***pazResult is held in memory obtained
101409 ** from malloc(). But the caller cannot free this memory directly.
101410 ** Instead, the entire table should be passed to sqlite3_free_table() when
101411 ** the calling procedure is finished using it.
101413 SQLITE_API int sqlite3_get_table(
101414 sqlite3 *db, /* The database on which the SQL executes */
101415 const char *zSql, /* The SQL to be executed */
101416 char ***pazResult, /* Write the result table here */
101417 int *pnRow, /* Write the number of rows in the result here */
101418 int *pnColumn, /* Write the number of columns of result here */
101419 char **pzErrMsg /* Write error messages here */
101421 int rc;
101422 TabResult res;
101424 *pazResult = 0;
101425 if( pnColumn ) *pnColumn = 0;
101426 if( pnRow ) *pnRow = 0;
101427 if( pzErrMsg ) *pzErrMsg = 0;
101428 res.zErrMsg = 0;
101429 res.nRow = 0;
101430 res.nColumn = 0;
101431 res.nData = 1;
101432 res.nAlloc = 20;
101433 res.rc = SQLITE_OK;
101434 res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
101435 if( res.azResult==0 ){
101436 db->errCode = SQLITE_NOMEM;
101437 return SQLITE_NOMEM;
101439 res.azResult[0] = 0;
101440 rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
101441 assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
101442 res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
101443 if( (rc&0xff)==SQLITE_ABORT ){
101444 sqlite3_free_table(&res.azResult[1]);
101445 if( res.zErrMsg ){
101446 if( pzErrMsg ){
101447 sqlite3_free(*pzErrMsg);
101448 *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
101450 sqlite3_free(res.zErrMsg);
101452 db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
101453 return res.rc;
101455 sqlite3_free(res.zErrMsg);
101456 if( rc!=SQLITE_OK ){
101457 sqlite3_free_table(&res.azResult[1]);
101458 return rc;
101460 if( res.nAlloc>res.nData ){
101461 char **azNew;
101462 azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
101463 if( azNew==0 ){
101464 sqlite3_free_table(&res.azResult[1]);
101465 db->errCode = SQLITE_NOMEM;
101466 return SQLITE_NOMEM;
101468 res.azResult = azNew;
101470 *pazResult = &res.azResult[1];
101471 if( pnColumn ) *pnColumn = res.nColumn;
101472 if( pnRow ) *pnRow = res.nRow;
101473 return rc;
101477 ** This routine frees the space the sqlite3_get_table() malloced.
101479 SQLITE_API void sqlite3_free_table(
101480 char **azResult /* Result returned from from sqlite3_get_table() */
101482 if( azResult ){
101483 int i, n;
101484 azResult--;
101485 assert( azResult!=0 );
101486 n = SQLITE_PTR_TO_INT(azResult[0]);
101487 for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
101488 sqlite3_free(azResult);
101492 #endif /* SQLITE_OMIT_GET_TABLE */
101494 /************** End of table.c ***********************************************/
101495 /************** Begin file trigger.c *****************************************/
101498 ** The author disclaims copyright to this source code. In place of
101499 ** a legal notice, here is a blessing:
101501 ** May you do good and not evil.
101502 ** May you find forgiveness for yourself and forgive others.
101503 ** May you share freely, never taking more than you give.
101505 *************************************************************************
101506 ** This file contains the implementation for TRIGGERs
101509 #ifndef SQLITE_OMIT_TRIGGER
101511 ** Delete a linked list of TriggerStep structures.
101513 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
101514 while( pTriggerStep ){
101515 TriggerStep * pTmp = pTriggerStep;
101516 pTriggerStep = pTriggerStep->pNext;
101518 sqlite3ExprDelete(db, pTmp->pWhere);
101519 sqlite3ExprListDelete(db, pTmp->pExprList);
101520 sqlite3SelectDelete(db, pTmp->pSelect);
101521 sqlite3IdListDelete(db, pTmp->pIdList);
101523 sqlite3DbFree(db, pTmp);
101528 ** Given table pTab, return a list of all the triggers attached to
101529 ** the table. The list is connected by Trigger.pNext pointers.
101531 ** All of the triggers on pTab that are in the same database as pTab
101532 ** are already attached to pTab->pTrigger. But there might be additional
101533 ** triggers on pTab in the TEMP schema. This routine prepends all
101534 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
101535 ** and returns the combined list.
101537 ** To state it another way: This routine returns a list of all triggers
101538 ** that fire off of pTab. The list will include any TEMP triggers on
101539 ** pTab as well as the triggers lised in pTab->pTrigger.
101541 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
101542 Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
101543 Trigger *pList = 0; /* List of triggers to return */
101545 if( pParse->disableTriggers ){
101546 return 0;
101549 if( pTmpSchema!=pTab->pSchema ){
101550 HashElem *p;
101551 assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
101552 for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
101553 Trigger *pTrig = (Trigger *)sqliteHashData(p);
101554 if( pTrig->pTabSchema==pTab->pSchema
101555 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
101557 pTrig->pNext = (pList ? pList : pTab->pTrigger);
101558 pList = pTrig;
101563 return (pList ? pList : pTab->pTrigger);
101567 ** This is called by the parser when it sees a CREATE TRIGGER statement
101568 ** up to the point of the BEGIN before the trigger actions. A Trigger
101569 ** structure is generated based on the information available and stored
101570 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
101571 ** sqlite3FinishTrigger() function is called to complete the trigger
101572 ** construction process.
101574 SQLITE_PRIVATE void sqlite3BeginTrigger(
101575 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
101576 Token *pName1, /* The name of the trigger */
101577 Token *pName2, /* The name of the trigger */
101578 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
101579 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
101580 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
101581 SrcList *pTableName,/* The name of the table/view the trigger applies to */
101582 Expr *pWhen, /* WHEN clause */
101583 int isTemp, /* True if the TEMPORARY keyword is present */
101584 int noErr /* Suppress errors if the trigger already exists */
101586 Trigger *pTrigger = 0; /* The new trigger */
101587 Table *pTab; /* Table that the trigger fires off of */
101588 char *zName = 0; /* Name of the trigger */
101589 sqlite3 *db = pParse->db; /* The database connection */
101590 int iDb; /* The database to store the trigger in */
101591 Token *pName; /* The unqualified db name */
101592 DbFixer sFix; /* State vector for the DB fixer */
101593 int iTabDb; /* Index of the database holding pTab */
101595 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
101596 assert( pName2!=0 );
101597 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
101598 assert( op>0 && op<0xff );
101599 if( isTemp ){
101600 /* If TEMP was specified, then the trigger name may not be qualified. */
101601 if( pName2->n>0 ){
101602 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
101603 goto trigger_cleanup;
101605 iDb = 1;
101606 pName = pName1;
101607 }else{
101608 /* Figure out the db that the trigger will be created in */
101609 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
101610 if( iDb<0 ){
101611 goto trigger_cleanup;
101614 if( !pTableName || db->mallocFailed ){
101615 goto trigger_cleanup;
101618 /* A long-standing parser bug is that this syntax was allowed:
101620 ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
101621 ** ^^^^^^^^
101623 ** To maintain backwards compatibility, ignore the database
101624 ** name on pTableName if we are reparsing our of SQLITE_MASTER.
101626 if( db->init.busy && iDb!=1 ){
101627 sqlite3DbFree(db, pTableName->a[0].zDatabase);
101628 pTableName->a[0].zDatabase = 0;
101631 /* If the trigger name was unqualified, and the table is a temp table,
101632 ** then set iDb to 1 to create the trigger in the temporary database.
101633 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
101634 ** exist, the error is caught by the block below.
101636 pTab = sqlite3SrcListLookup(pParse, pTableName);
101637 if( db->init.busy==0 && pName2->n==0 && pTab
101638 && pTab->pSchema==db->aDb[1].pSchema ){
101639 iDb = 1;
101642 /* Ensure the table name matches database name and that the table exists */
101643 if( db->mallocFailed ) goto trigger_cleanup;
101644 assert( pTableName->nSrc==1 );
101645 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
101646 sqlite3FixSrcList(&sFix, pTableName) ){
101647 goto trigger_cleanup;
101649 pTab = sqlite3SrcListLookup(pParse, pTableName);
101650 if( !pTab ){
101651 /* The table does not exist. */
101652 if( db->init.iDb==1 ){
101653 /* Ticket #3810.
101654 ** Normally, whenever a table is dropped, all associated triggers are
101655 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
101656 ** and the table is dropped by a different database connection, the
101657 ** trigger is not visible to the database connection that does the
101658 ** drop so the trigger cannot be dropped. This results in an
101659 ** "orphaned trigger" - a trigger whose associated table is missing.
101661 db->init.orphanTrigger = 1;
101663 goto trigger_cleanup;
101665 if( IsVirtual(pTab) ){
101666 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
101667 goto trigger_cleanup;
101670 /* Check that the trigger name is not reserved and that no trigger of the
101671 ** specified name exists */
101672 zName = sqlite3NameFromToken(db, pName);
101673 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
101674 goto trigger_cleanup;
101676 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101677 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
101678 zName, sqlite3Strlen30(zName)) ){
101679 if( !noErr ){
101680 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
101681 }else{
101682 assert( !db->init.busy );
101683 sqlite3CodeVerifySchema(pParse, iDb);
101685 goto trigger_cleanup;
101688 /* Do not create a trigger on a system table */
101689 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
101690 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
101691 pParse->nErr++;
101692 goto trigger_cleanup;
101695 /* INSTEAD of triggers are only for views and views only support INSTEAD
101696 ** of triggers.
101698 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
101699 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
101700 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
101701 goto trigger_cleanup;
101703 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
101704 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
101705 " trigger on table: %S", pTableName, 0);
101706 goto trigger_cleanup;
101708 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101710 #ifndef SQLITE_OMIT_AUTHORIZATION
101712 int code = SQLITE_CREATE_TRIGGER;
101713 const char *zDb = db->aDb[iTabDb].zName;
101714 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
101715 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
101716 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
101717 goto trigger_cleanup;
101719 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
101720 goto trigger_cleanup;
101723 #endif
101725 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
101726 ** cannot appear on views. So we might as well translate every
101727 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
101728 ** elsewhere.
101730 if (tr_tm == TK_INSTEAD){
101731 tr_tm = TK_BEFORE;
101734 /* Build the Trigger object */
101735 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
101736 if( pTrigger==0 ) goto trigger_cleanup;
101737 pTrigger->zName = zName;
101738 zName = 0;
101739 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
101740 pTrigger->pSchema = db->aDb[iDb].pSchema;
101741 pTrigger->pTabSchema = pTab->pSchema;
101742 pTrigger->op = (u8)op;
101743 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
101744 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
101745 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
101746 assert( pParse->pNewTrigger==0 );
101747 pParse->pNewTrigger = pTrigger;
101749 trigger_cleanup:
101750 sqlite3DbFree(db, zName);
101751 sqlite3SrcListDelete(db, pTableName);
101752 sqlite3IdListDelete(db, pColumns);
101753 sqlite3ExprDelete(db, pWhen);
101754 if( !pParse->pNewTrigger ){
101755 sqlite3DeleteTrigger(db, pTrigger);
101756 }else{
101757 assert( pParse->pNewTrigger==pTrigger );
101762 ** This routine is called after all of the trigger actions have been parsed
101763 ** in order to complete the process of building the trigger.
101765 SQLITE_PRIVATE void sqlite3FinishTrigger(
101766 Parse *pParse, /* Parser context */
101767 TriggerStep *pStepList, /* The triggered program */
101768 Token *pAll /* Token that describes the complete CREATE TRIGGER */
101770 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
101771 char *zName; /* Name of trigger */
101772 sqlite3 *db = pParse->db; /* The database */
101773 DbFixer sFix; /* Fixer object */
101774 int iDb; /* Database containing the trigger */
101775 Token nameToken; /* Trigger name for error reporting */
101777 pParse->pNewTrigger = 0;
101778 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
101779 zName = pTrig->zName;
101780 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
101781 pTrig->step_list = pStepList;
101782 while( pStepList ){
101783 pStepList->pTrig = pTrig;
101784 pStepList = pStepList->pNext;
101786 nameToken.z = pTrig->zName;
101787 nameToken.n = sqlite3Strlen30(nameToken.z);
101788 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
101789 && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
101790 goto triggerfinish_cleanup;
101793 /* if we are not initializing,
101794 ** build the sqlite_master entry
101796 if( !db->init.busy ){
101797 Vdbe *v;
101798 char *z;
101800 /* Make an entry in the sqlite_master table */
101801 v = sqlite3GetVdbe(pParse);
101802 if( v==0 ) goto triggerfinish_cleanup;
101803 sqlite3BeginWriteOperation(pParse, 0, iDb);
101804 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
101805 sqlite3NestedParse(pParse,
101806 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
101807 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
101808 pTrig->table, z);
101809 sqlite3DbFree(db, z);
101810 sqlite3ChangeCookie(pParse, iDb);
101811 sqlite3VdbeAddParseSchemaOp(v, iDb,
101812 sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
101815 if( db->init.busy ){
101816 Trigger *pLink = pTrig;
101817 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
101818 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101819 pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
101820 if( pTrig ){
101821 db->mallocFailed = 1;
101822 }else if( pLink->pSchema==pLink->pTabSchema ){
101823 Table *pTab;
101824 int n = sqlite3Strlen30(pLink->table);
101825 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
101826 assert( pTab!=0 );
101827 pLink->pNext = pTab->pTrigger;
101828 pTab->pTrigger = pLink;
101832 triggerfinish_cleanup:
101833 sqlite3DeleteTrigger(db, pTrig);
101834 assert( !pParse->pNewTrigger );
101835 sqlite3DeleteTriggerStep(db, pStepList);
101839 ** Turn a SELECT statement (that the pSelect parameter points to) into
101840 ** a trigger step. Return a pointer to a TriggerStep structure.
101842 ** The parser calls this routine when it finds a SELECT statement in
101843 ** body of a TRIGGER.
101845 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
101846 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
101847 if( pTriggerStep==0 ) {
101848 sqlite3SelectDelete(db, pSelect);
101849 return 0;
101851 pTriggerStep->op = TK_SELECT;
101852 pTriggerStep->pSelect = pSelect;
101853 pTriggerStep->orconf = OE_Default;
101854 return pTriggerStep;
101858 ** Allocate space to hold a new trigger step. The allocated space
101859 ** holds both the TriggerStep object and the TriggerStep.target.z string.
101861 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
101863 static TriggerStep *triggerStepAllocate(
101864 sqlite3 *db, /* Database connection */
101865 u8 op, /* Trigger opcode */
101866 Token *pName /* The target name */
101868 TriggerStep *pTriggerStep;
101870 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
101871 if( pTriggerStep ){
101872 char *z = (char*)&pTriggerStep[1];
101873 memcpy(z, pName->z, pName->n);
101874 pTriggerStep->target.z = z;
101875 pTriggerStep->target.n = pName->n;
101876 pTriggerStep->op = op;
101878 return pTriggerStep;
101882 ** Build a trigger step out of an INSERT statement. Return a pointer
101883 ** to the new trigger step.
101885 ** The parser calls this routine when it sees an INSERT inside the
101886 ** body of a trigger.
101888 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
101889 sqlite3 *db, /* The database connection */
101890 Token *pTableName, /* Name of the table into which we insert */
101891 IdList *pColumn, /* List of columns in pTableName to insert into */
101892 ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
101893 Select *pSelect, /* A SELECT statement that supplies values */
101894 u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
101896 TriggerStep *pTriggerStep;
101898 assert(pEList == 0 || pSelect == 0);
101899 assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
101901 pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
101902 if( pTriggerStep ){
101903 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
101904 pTriggerStep->pIdList = pColumn;
101905 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
101906 pTriggerStep->orconf = orconf;
101907 }else{
101908 sqlite3IdListDelete(db, pColumn);
101910 sqlite3ExprListDelete(db, pEList);
101911 sqlite3SelectDelete(db, pSelect);
101913 return pTriggerStep;
101917 ** Construct a trigger step that implements an UPDATE statement and return
101918 ** a pointer to that trigger step. The parser calls this routine when it
101919 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
101921 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
101922 sqlite3 *db, /* The database connection */
101923 Token *pTableName, /* Name of the table to be updated */
101924 ExprList *pEList, /* The SET clause: list of column and new values */
101925 Expr *pWhere, /* The WHERE clause */
101926 u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
101928 TriggerStep *pTriggerStep;
101930 pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
101931 if( pTriggerStep ){
101932 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
101933 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
101934 pTriggerStep->orconf = orconf;
101936 sqlite3ExprListDelete(db, pEList);
101937 sqlite3ExprDelete(db, pWhere);
101938 return pTriggerStep;
101942 ** Construct a trigger step that implements a DELETE statement and return
101943 ** a pointer to that trigger step. The parser calls this routine when it
101944 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
101946 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
101947 sqlite3 *db, /* Database connection */
101948 Token *pTableName, /* The table from which rows are deleted */
101949 Expr *pWhere /* The WHERE clause */
101951 TriggerStep *pTriggerStep;
101953 pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
101954 if( pTriggerStep ){
101955 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
101956 pTriggerStep->orconf = OE_Default;
101958 sqlite3ExprDelete(db, pWhere);
101959 return pTriggerStep;
101963 ** Recursively delete a Trigger structure
101965 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
101966 if( pTrigger==0 ) return;
101967 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
101968 sqlite3DbFree(db, pTrigger->zName);
101969 sqlite3DbFree(db, pTrigger->table);
101970 sqlite3ExprDelete(db, pTrigger->pWhen);
101971 sqlite3IdListDelete(db, pTrigger->pColumns);
101972 sqlite3DbFree(db, pTrigger);
101976 ** This function is called to drop a trigger from the database schema.
101978 ** This may be called directly from the parser and therefore identifies
101979 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
101980 ** same job as this routine except it takes a pointer to the trigger
101981 ** instead of the trigger name.
101983 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
101984 Trigger *pTrigger = 0;
101985 int i;
101986 const char *zDb;
101987 const char *zName;
101988 int nName;
101989 sqlite3 *db = pParse->db;
101991 if( db->mallocFailed ) goto drop_trigger_cleanup;
101992 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101993 goto drop_trigger_cleanup;
101996 assert( pName->nSrc==1 );
101997 zDb = pName->a[0].zDatabase;
101998 zName = pName->a[0].zName;
101999 nName = sqlite3Strlen30(zName);
102000 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
102001 for(i=OMIT_TEMPDB; i<db->nDb; i++){
102002 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
102003 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
102004 assert( sqlite3SchemaMutexHeld(db, j, 0) );
102005 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
102006 if( pTrigger ) break;
102008 if( !pTrigger ){
102009 if( !noErr ){
102010 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
102011 }else{
102012 sqlite3CodeVerifyNamedSchema(pParse, zDb);
102014 pParse->checkSchema = 1;
102015 goto drop_trigger_cleanup;
102017 sqlite3DropTriggerPtr(pParse, pTrigger);
102019 drop_trigger_cleanup:
102020 sqlite3SrcListDelete(db, pName);
102024 ** Return a pointer to the Table structure for the table that a trigger
102025 ** is set on.
102027 static Table *tableOfTrigger(Trigger *pTrigger){
102028 int n = sqlite3Strlen30(pTrigger->table);
102029 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
102034 ** Drop a trigger given a pointer to that trigger.
102036 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
102037 Table *pTable;
102038 Vdbe *v;
102039 sqlite3 *db = pParse->db;
102040 int iDb;
102042 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
102043 assert( iDb>=0 && iDb<db->nDb );
102044 pTable = tableOfTrigger(pTrigger);
102045 assert( pTable );
102046 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
102047 #ifndef SQLITE_OMIT_AUTHORIZATION
102049 int code = SQLITE_DROP_TRIGGER;
102050 const char *zDb = db->aDb[iDb].zName;
102051 const char *zTab = SCHEMA_TABLE(iDb);
102052 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
102053 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
102054 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
102055 return;
102058 #endif
102060 /* Generate code to destroy the database record of the trigger.
102062 assert( pTable!=0 );
102063 if( (v = sqlite3GetVdbe(pParse))!=0 ){
102064 int base;
102065 static const VdbeOpList dropTrigger[] = {
102066 { OP_Rewind, 0, ADDR(9), 0},
102067 { OP_String8, 0, 1, 0}, /* 1 */
102068 { OP_Column, 0, 1, 2},
102069 { OP_Ne, 2, ADDR(8), 1},
102070 { OP_String8, 0, 1, 0}, /* 4: "trigger" */
102071 { OP_Column, 0, 0, 2},
102072 { OP_Ne, 2, ADDR(8), 1},
102073 { OP_Delete, 0, 0, 0},
102074 { OP_Next, 0, ADDR(1), 0}, /* 8 */
102077 sqlite3BeginWriteOperation(pParse, 0, iDb);
102078 sqlite3OpenMasterTable(pParse, iDb);
102079 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
102080 sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
102081 sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
102082 sqlite3ChangeCookie(pParse, iDb);
102083 sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
102084 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
102085 if( pParse->nMem<3 ){
102086 pParse->nMem = 3;
102092 ** Remove a trigger from the hash tables of the sqlite* pointer.
102094 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
102095 Trigger *pTrigger;
102096 Hash *pHash;
102098 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102099 pHash = &(db->aDb[iDb].pSchema->trigHash);
102100 pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
102101 if( ALWAYS(pTrigger) ){
102102 if( pTrigger->pSchema==pTrigger->pTabSchema ){
102103 Table *pTab = tableOfTrigger(pTrigger);
102104 Trigger **pp;
102105 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
102106 *pp = (*pp)->pNext;
102108 sqlite3DeleteTrigger(db, pTrigger);
102109 db->flags |= SQLITE_InternChanges;
102114 ** pEList is the SET clause of an UPDATE statement. Each entry
102115 ** in pEList is of the format <id>=<expr>. If any of the entries
102116 ** in pEList have an <id> which matches an identifier in pIdList,
102117 ** then return TRUE. If pIdList==NULL, then it is considered a
102118 ** wildcard that matches anything. Likewise if pEList==NULL then
102119 ** it matches anything so always return true. Return false only
102120 ** if there is no match.
102122 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
102123 int e;
102124 if( pIdList==0 || NEVER(pEList==0) ) return 1;
102125 for(e=0; e<pEList->nExpr; e++){
102126 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
102128 return 0;
102132 ** Return a list of all triggers on table pTab if there exists at least
102133 ** one trigger that must be fired when an operation of type 'op' is
102134 ** performed on the table, and, if that operation is an UPDATE, if at
102135 ** least one of the columns in pChanges is being modified.
102137 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
102138 Parse *pParse, /* Parse context */
102139 Table *pTab, /* The table the contains the triggers */
102140 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
102141 ExprList *pChanges, /* Columns that change in an UPDATE statement */
102142 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
102144 int mask = 0;
102145 Trigger *pList = 0;
102146 Trigger *p;
102148 if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
102149 pList = sqlite3TriggerList(pParse, pTab);
102151 assert( pList==0 || IsVirtual(pTab)==0 );
102152 for(p=pList; p; p=p->pNext){
102153 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
102154 mask |= p->tr_tm;
102157 if( pMask ){
102158 *pMask = mask;
102160 return (mask ? pList : 0);
102164 ** Convert the pStep->target token into a SrcList and return a pointer
102165 ** to that SrcList.
102167 ** This routine adds a specific database name, if needed, to the target when
102168 ** forming the SrcList. This prevents a trigger in one database from
102169 ** referring to a target in another database. An exception is when the
102170 ** trigger is in TEMP in which case it can refer to any other database it
102171 ** wants.
102173 static SrcList *targetSrcList(
102174 Parse *pParse, /* The parsing context */
102175 TriggerStep *pStep /* The trigger containing the target token */
102177 int iDb; /* Index of the database to use */
102178 SrcList *pSrc; /* SrcList to be returned */
102180 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
102181 if( pSrc ){
102182 assert( pSrc->nSrc>0 );
102183 assert( pSrc->a!=0 );
102184 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
102185 if( iDb==0 || iDb>=2 ){
102186 sqlite3 *db = pParse->db;
102187 assert( iDb<pParse->db->nDb );
102188 pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
102191 return pSrc;
102195 ** Generate VDBE code for the statements inside the body of a single
102196 ** trigger.
102198 static int codeTriggerProgram(
102199 Parse *pParse, /* The parser context */
102200 TriggerStep *pStepList, /* List of statements inside the trigger body */
102201 int orconf /* Conflict algorithm. (OE_Abort, etc) */
102203 TriggerStep *pStep;
102204 Vdbe *v = pParse->pVdbe;
102205 sqlite3 *db = pParse->db;
102207 assert( pParse->pTriggerTab && pParse->pToplevel );
102208 assert( pStepList );
102209 assert( v!=0 );
102210 for(pStep=pStepList; pStep; pStep=pStep->pNext){
102211 /* Figure out the ON CONFLICT policy that will be used for this step
102212 ** of the trigger program. If the statement that caused this trigger
102213 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
102214 ** the ON CONFLICT policy that was specified as part of the trigger
102215 ** step statement. Example:
102217 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
102218 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
102219 ** END;
102221 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
102222 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
102224 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
102226 /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
102227 ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
102228 ** that it is not safe to refactor constants (this happens after the
102229 ** start of the first loop in the SQL statement is coded - at that
102230 ** point code may be conditionally executed, so it is no longer safe to
102231 ** initialize constant register values). */
102232 assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
102233 pParse->cookieGoto = 0;
102235 switch( pStep->op ){
102236 case TK_UPDATE: {
102237 sqlite3Update(pParse,
102238 targetSrcList(pParse, pStep),
102239 sqlite3ExprListDup(db, pStep->pExprList, 0),
102240 sqlite3ExprDup(db, pStep->pWhere, 0),
102241 pParse->eOrconf
102243 break;
102245 case TK_INSERT: {
102246 sqlite3Insert(pParse,
102247 targetSrcList(pParse, pStep),
102248 sqlite3ExprListDup(db, pStep->pExprList, 0),
102249 sqlite3SelectDup(db, pStep->pSelect, 0),
102250 sqlite3IdListDup(db, pStep->pIdList),
102251 pParse->eOrconf
102253 break;
102255 case TK_DELETE: {
102256 sqlite3DeleteFrom(pParse,
102257 targetSrcList(pParse, pStep),
102258 sqlite3ExprDup(db, pStep->pWhere, 0)
102260 break;
102262 default: assert( pStep->op==TK_SELECT ); {
102263 SelectDest sDest;
102264 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
102265 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
102266 sqlite3Select(pParse, pSelect, &sDest);
102267 sqlite3SelectDelete(db, pSelect);
102268 break;
102271 if( pStep->op!=TK_SELECT ){
102272 sqlite3VdbeAddOp0(v, OP_ResetCount);
102276 return 0;
102279 #ifdef SQLITE_DEBUG
102281 ** This function is used to add VdbeComment() annotations to a VDBE
102282 ** program. It is not used in production code, only for debugging.
102284 static const char *onErrorText(int onError){
102285 switch( onError ){
102286 case OE_Abort: return "abort";
102287 case OE_Rollback: return "rollback";
102288 case OE_Fail: return "fail";
102289 case OE_Replace: return "replace";
102290 case OE_Ignore: return "ignore";
102291 case OE_Default: return "default";
102293 return "n/a";
102295 #endif
102298 ** Parse context structure pFrom has just been used to create a sub-vdbe
102299 ** (trigger program). If an error has occurred, transfer error information
102300 ** from pFrom to pTo.
102302 static void transferParseError(Parse *pTo, Parse *pFrom){
102303 assert( pFrom->zErrMsg==0 || pFrom->nErr );
102304 assert( pTo->zErrMsg==0 || pTo->nErr );
102305 if( pTo->nErr==0 ){
102306 pTo->zErrMsg = pFrom->zErrMsg;
102307 pTo->nErr = pFrom->nErr;
102308 }else{
102309 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
102314 ** Create and populate a new TriggerPrg object with a sub-program
102315 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
102317 static TriggerPrg *codeRowTrigger(
102318 Parse *pParse, /* Current parse context */
102319 Trigger *pTrigger, /* Trigger to code */
102320 Table *pTab, /* The table pTrigger is attached to */
102321 int orconf /* ON CONFLICT policy to code trigger program with */
102323 Parse *pTop = sqlite3ParseToplevel(pParse);
102324 sqlite3 *db = pParse->db; /* Database handle */
102325 TriggerPrg *pPrg; /* Value to return */
102326 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
102327 Vdbe *v; /* Temporary VM */
102328 NameContext sNC; /* Name context for sub-vdbe */
102329 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
102330 Parse *pSubParse; /* Parse context for sub-vdbe */
102331 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
102333 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
102334 assert( pTop->pVdbe );
102336 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
102337 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
102338 ** list of the top-level Parse object sooner rather than later. */
102339 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
102340 if( !pPrg ) return 0;
102341 pPrg->pNext = pTop->pTriggerPrg;
102342 pTop->pTriggerPrg = pPrg;
102343 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
102344 if( !pProgram ) return 0;
102345 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
102346 pPrg->pTrigger = pTrigger;
102347 pPrg->orconf = orconf;
102348 pPrg->aColmask[0] = 0xffffffff;
102349 pPrg->aColmask[1] = 0xffffffff;
102351 /* Allocate and populate a new Parse context to use for coding the
102352 ** trigger sub-program. */
102353 pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
102354 if( !pSubParse ) return 0;
102355 memset(&sNC, 0, sizeof(sNC));
102356 sNC.pParse = pSubParse;
102357 pSubParse->db = db;
102358 pSubParse->pTriggerTab = pTab;
102359 pSubParse->pToplevel = pTop;
102360 pSubParse->zAuthContext = pTrigger->zName;
102361 pSubParse->eTriggerOp = pTrigger->op;
102362 pSubParse->nQueryLoop = pParse->nQueryLoop;
102364 v = sqlite3GetVdbe(pSubParse);
102365 if( v ){
102366 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
102367 pTrigger->zName, onErrorText(orconf),
102368 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
102369 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
102370 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
102371 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
102372 pTab->zName
102374 #ifndef SQLITE_OMIT_TRACE
102375 sqlite3VdbeChangeP4(v, -1,
102376 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
102378 #endif
102380 /* If one was specified, code the WHEN clause. If it evaluates to false
102381 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
102382 ** OP_Halt inserted at the end of the program. */
102383 if( pTrigger->pWhen ){
102384 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
102385 if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
102386 && db->mallocFailed==0
102388 iEndTrigger = sqlite3VdbeMakeLabel(v);
102389 sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
102391 sqlite3ExprDelete(db, pWhen);
102394 /* Code the trigger program into the sub-vdbe. */
102395 codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
102397 /* Insert an OP_Halt at the end of the sub-program. */
102398 if( iEndTrigger ){
102399 sqlite3VdbeResolveLabel(v, iEndTrigger);
102401 sqlite3VdbeAddOp0(v, OP_Halt);
102402 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
102404 transferParseError(pParse, pSubParse);
102405 if( db->mallocFailed==0 ){
102406 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
102408 pProgram->nMem = pSubParse->nMem;
102409 pProgram->nCsr = pSubParse->nTab;
102410 pProgram->nOnce = pSubParse->nOnce;
102411 pProgram->token = (void *)pTrigger;
102412 pPrg->aColmask[0] = pSubParse->oldmask;
102413 pPrg->aColmask[1] = pSubParse->newmask;
102414 sqlite3VdbeDelete(v);
102417 assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
102418 assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
102419 sqlite3StackFree(db, pSubParse);
102421 return pPrg;
102425 ** Return a pointer to a TriggerPrg object containing the sub-program for
102426 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
102427 ** TriggerPrg object exists, a new object is allocated and populated before
102428 ** being returned.
102430 static TriggerPrg *getRowTrigger(
102431 Parse *pParse, /* Current parse context */
102432 Trigger *pTrigger, /* Trigger to code */
102433 Table *pTab, /* The table trigger pTrigger is attached to */
102434 int orconf /* ON CONFLICT algorithm. */
102436 Parse *pRoot = sqlite3ParseToplevel(pParse);
102437 TriggerPrg *pPrg;
102439 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
102441 /* It may be that this trigger has already been coded (or is in the
102442 ** process of being coded). If this is the case, then an entry with
102443 ** a matching TriggerPrg.pTrigger field will be present somewhere
102444 ** in the Parse.pTriggerPrg list. Search for such an entry. */
102445 for(pPrg=pRoot->pTriggerPrg;
102446 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
102447 pPrg=pPrg->pNext
102450 /* If an existing TriggerPrg could not be located, create a new one. */
102451 if( !pPrg ){
102452 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
102455 return pPrg;
102459 ** Generate code for the trigger program associated with trigger p on
102460 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
102461 ** function are the same as those described in the header function for
102462 ** sqlite3CodeRowTrigger()
102464 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
102465 Parse *pParse, /* Parse context */
102466 Trigger *p, /* Trigger to code */
102467 Table *pTab, /* The table to code triggers from */
102468 int reg, /* Reg array containing OLD.* and NEW.* values */
102469 int orconf, /* ON CONFLICT policy */
102470 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
102472 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
102473 TriggerPrg *pPrg;
102474 pPrg = getRowTrigger(pParse, p, pTab, orconf);
102475 assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
102477 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
102478 ** is a pointer to the sub-vdbe containing the trigger program. */
102479 if( pPrg ){
102480 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
102482 sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
102483 sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
102484 VdbeComment(
102485 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
102487 /* Set the P5 operand of the OP_Program instruction to non-zero if
102488 ** recursive invocation of this trigger program is disallowed. Recursive
102489 ** invocation is disallowed if (a) the sub-program is really a trigger,
102490 ** not a foreign key action, and (b) the flag to enable recursive triggers
102491 ** is clear. */
102492 sqlite3VdbeChangeP5(v, (u8)bRecursive);
102497 ** This is called to code the required FOR EACH ROW triggers for an operation
102498 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
102499 ** is given by the op parameter. The tr_tm parameter determines whether the
102500 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
102501 ** parameter pChanges is passed the list of columns being modified.
102503 ** If there are no triggers that fire at the specified time for the specified
102504 ** operation on pTab, this function is a no-op.
102506 ** The reg argument is the address of the first in an array of registers
102507 ** that contain the values substituted for the new.* and old.* references
102508 ** in the trigger program. If N is the number of columns in table pTab
102509 ** (a copy of pTab->nCol), then registers are populated as follows:
102511 ** Register Contains
102512 ** ------------------------------------------------------
102513 ** reg+0 OLD.rowid
102514 ** reg+1 OLD.* value of left-most column of pTab
102515 ** ... ...
102516 ** reg+N OLD.* value of right-most column of pTab
102517 ** reg+N+1 NEW.rowid
102518 ** reg+N+2 OLD.* value of left-most column of pTab
102519 ** ... ...
102520 ** reg+N+N+1 NEW.* value of right-most column of pTab
102522 ** For ON DELETE triggers, the registers containing the NEW.* values will
102523 ** never be accessed by the trigger program, so they are not allocated or
102524 ** populated by the caller (there is no data to populate them with anyway).
102525 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
102526 ** are never accessed, and so are not allocated by the caller. So, for an
102527 ** ON INSERT trigger, the value passed to this function as parameter reg
102528 ** is not a readable register, although registers (reg+N) through
102529 ** (reg+N+N+1) are.
102531 ** Parameter orconf is the default conflict resolution algorithm for the
102532 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
102533 ** is the instruction that control should jump to if a trigger program
102534 ** raises an IGNORE exception.
102536 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
102537 Parse *pParse, /* Parse context */
102538 Trigger *pTrigger, /* List of triggers on table pTab */
102539 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
102540 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
102541 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
102542 Table *pTab, /* The table to code triggers from */
102543 int reg, /* The first in an array of registers (see above) */
102544 int orconf, /* ON CONFLICT policy */
102545 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
102547 Trigger *p; /* Used to iterate through pTrigger list */
102549 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
102550 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
102551 assert( (op==TK_UPDATE)==(pChanges!=0) );
102553 for(p=pTrigger; p; p=p->pNext){
102555 /* Sanity checking: The schema for the trigger and for the table are
102556 ** always defined. The trigger must be in the same schema as the table
102557 ** or else it must be a TEMP trigger. */
102558 assert( p->pSchema!=0 );
102559 assert( p->pTabSchema!=0 );
102560 assert( p->pSchema==p->pTabSchema
102561 || p->pSchema==pParse->db->aDb[1].pSchema );
102563 /* Determine whether we should code this trigger */
102564 if( p->op==op
102565 && p->tr_tm==tr_tm
102566 && checkColumnOverlap(p->pColumns, pChanges)
102568 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
102574 ** Triggers may access values stored in the old.* or new.* pseudo-table.
102575 ** This function returns a 32-bit bitmask indicating which columns of the
102576 ** old.* or new.* tables actually are used by triggers. This information
102577 ** may be used by the caller, for example, to avoid having to load the entire
102578 ** old.* record into memory when executing an UPDATE or DELETE command.
102580 ** Bit 0 of the returned mask is set if the left-most column of the
102581 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
102582 ** the second leftmost column value is required, and so on. If there
102583 ** are more than 32 columns in the table, and at least one of the columns
102584 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
102586 ** It is not possible to determine if the old.rowid or new.rowid column is
102587 ** accessed by triggers. The caller must always assume that it is.
102589 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
102590 ** applies to the old.* table. If 1, the new.* table.
102592 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
102593 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
102594 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
102595 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
102596 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
102598 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
102599 Parse *pParse, /* Parse context */
102600 Trigger *pTrigger, /* List of triggers on table pTab */
102601 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
102602 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
102603 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
102604 Table *pTab, /* The table to code triggers from */
102605 int orconf /* Default ON CONFLICT policy for trigger steps */
102607 const int op = pChanges ? TK_UPDATE : TK_DELETE;
102608 u32 mask = 0;
102609 Trigger *p;
102611 assert( isNew==1 || isNew==0 );
102612 for(p=pTrigger; p; p=p->pNext){
102613 if( p->op==op && (tr_tm&p->tr_tm)
102614 && checkColumnOverlap(p->pColumns,pChanges)
102616 TriggerPrg *pPrg;
102617 pPrg = getRowTrigger(pParse, p, pTab, orconf);
102618 if( pPrg ){
102619 mask |= pPrg->aColmask[isNew];
102624 return mask;
102627 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
102629 /************** End of trigger.c *********************************************/
102630 /************** Begin file update.c ******************************************/
102632 ** 2001 September 15
102634 ** The author disclaims copyright to this source code. In place of
102635 ** a legal notice, here is a blessing:
102637 ** May you do good and not evil.
102638 ** May you find forgiveness for yourself and forgive others.
102639 ** May you share freely, never taking more than you give.
102641 *************************************************************************
102642 ** This file contains C code routines that are called by the parser
102643 ** to handle UPDATE statements.
102646 #ifndef SQLITE_OMIT_VIRTUALTABLE
102647 /* Forward declaration */
102648 static void updateVirtualTable(
102649 Parse *pParse, /* The parsing context */
102650 SrcList *pSrc, /* The virtual table to be modified */
102651 Table *pTab, /* The virtual table */
102652 ExprList *pChanges, /* The columns to change in the UPDATE statement */
102653 Expr *pRowidExpr, /* Expression used to recompute the rowid */
102654 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
102655 Expr *pWhere, /* WHERE clause of the UPDATE statement */
102656 int onError /* ON CONFLICT strategy */
102658 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102661 ** The most recently coded instruction was an OP_Column to retrieve the
102662 ** i-th column of table pTab. This routine sets the P4 parameter of the
102663 ** OP_Column to the default value, if any.
102665 ** The default value of a column is specified by a DEFAULT clause in the
102666 ** column definition. This was either supplied by the user when the table
102667 ** was created, or added later to the table definition by an ALTER TABLE
102668 ** command. If the latter, then the row-records in the table btree on disk
102669 ** may not contain a value for the column and the default value, taken
102670 ** from the P4 parameter of the OP_Column instruction, is returned instead.
102671 ** If the former, then all row-records are guaranteed to include a value
102672 ** for the column and the P4 value is not required.
102674 ** Column definitions created by an ALTER TABLE command may only have
102675 ** literal default values specified: a number, null or a string. (If a more
102676 ** complicated default expression value was provided, it is evaluated
102677 ** when the ALTER TABLE is executed and one of the literal values written
102678 ** into the sqlite_master table.)
102680 ** Therefore, the P4 parameter is only required if the default value for
102681 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
102682 ** function is capable of transforming these types of expressions into
102683 ** sqlite3_value objects.
102685 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
102686 ** on register iReg. This is used when an equivalent integer value is
102687 ** stored in place of an 8-byte floating point value in order to save
102688 ** space.
102690 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
102691 assert( pTab!=0 );
102692 if( !pTab->pSelect ){
102693 sqlite3_value *pValue;
102694 u8 enc = ENC(sqlite3VdbeDb(v));
102695 Column *pCol = &pTab->aCol[i];
102696 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
102697 assert( i<pTab->nCol );
102698 sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
102699 pCol->affinity, &pValue);
102700 if( pValue ){
102701 sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
102703 #ifndef SQLITE_OMIT_FLOATING_POINT
102704 if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
102705 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
102707 #endif
102712 ** Process an UPDATE statement.
102714 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
102715 ** \_______/ \________/ \______/ \________________/
102716 * onError pTabList pChanges pWhere
102718 SQLITE_PRIVATE void sqlite3Update(
102719 Parse *pParse, /* The parser context */
102720 SrcList *pTabList, /* The table in which we should change things */
102721 ExprList *pChanges, /* Things to be changed */
102722 Expr *pWhere, /* The WHERE clause. May be null */
102723 int onError /* How to handle constraint errors */
102725 int i, j; /* Loop counters */
102726 Table *pTab; /* The table to be updated */
102727 int addr = 0; /* VDBE instruction address of the start of the loop */
102728 WhereInfo *pWInfo; /* Information about the WHERE clause */
102729 Vdbe *v; /* The virtual database engine */
102730 Index *pIdx; /* For looping over indices */
102731 int nIdx; /* Number of indices that need updating */
102732 int iCur; /* VDBE Cursor number of pTab */
102733 sqlite3 *db; /* The database structure */
102734 int *aRegIdx = 0; /* One register assigned to each index to be updated */
102735 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
102736 ** an expression for the i-th column of the table.
102737 ** aXRef[i]==-1 if the i-th column is not changed. */
102738 int chngRowid; /* True if the record number is being changed */
102739 Expr *pRowidExpr = 0; /* Expression defining the new record number */
102740 int openAll = 0; /* True if all indices need to be opened */
102741 AuthContext sContext; /* The authorization context */
102742 NameContext sNC; /* The name-context to resolve expressions in */
102743 int iDb; /* Database containing the table being updated */
102744 int okOnePass; /* True for one-pass algorithm without the FIFO */
102745 int hasFK; /* True if foreign key processing is required */
102747 #ifndef SQLITE_OMIT_TRIGGER
102748 int isView; /* True when updating a view (INSTEAD OF trigger) */
102749 Trigger *pTrigger; /* List of triggers on pTab, if required */
102750 int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
102751 #endif
102752 int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
102754 /* Register Allocations */
102755 int regRowCount = 0; /* A count of rows changed */
102756 int regOldRowid; /* The old rowid */
102757 int regNewRowid; /* The new rowid */
102758 int regNew; /* Content of the NEW.* table in triggers */
102759 int regOld = 0; /* Content of OLD.* table in triggers */
102760 int regRowSet = 0; /* Rowset of rows to be updated */
102762 memset(&sContext, 0, sizeof(sContext));
102763 db = pParse->db;
102764 if( pParse->nErr || db->mallocFailed ){
102765 goto update_cleanup;
102767 assert( pTabList->nSrc==1 );
102769 /* Locate the table which we want to update.
102771 pTab = sqlite3SrcListLookup(pParse, pTabList);
102772 if( pTab==0 ) goto update_cleanup;
102773 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
102775 /* Figure out if we have any triggers and if the table being
102776 ** updated is a view.
102778 #ifndef SQLITE_OMIT_TRIGGER
102779 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
102780 isView = pTab->pSelect!=0;
102781 assert( pTrigger || tmask==0 );
102782 #else
102783 # define pTrigger 0
102784 # define isView 0
102785 # define tmask 0
102786 #endif
102787 #ifdef SQLITE_OMIT_VIEW
102788 # undef isView
102789 # define isView 0
102790 #endif
102792 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
102793 goto update_cleanup;
102795 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
102796 goto update_cleanup;
102798 aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
102799 if( aXRef==0 ) goto update_cleanup;
102800 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
102802 /* Allocate a cursors for the main database table and for all indices.
102803 ** The index cursors might not be used, but if they are used they
102804 ** need to occur right after the database cursor. So go ahead and
102805 ** allocate enough space, just in case.
102807 pTabList->a[0].iCursor = iCur = pParse->nTab++;
102808 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102809 pParse->nTab++;
102812 /* Initialize the name-context */
102813 memset(&sNC, 0, sizeof(sNC));
102814 sNC.pParse = pParse;
102815 sNC.pSrcList = pTabList;
102817 /* Resolve the column names in all the expressions of the
102818 ** of the UPDATE statement. Also find the column index
102819 ** for each column to be updated in the pChanges array. For each
102820 ** column to be updated, make sure we have authorization to change
102821 ** that column.
102823 chngRowid = 0;
102824 for(i=0; i<pChanges->nExpr; i++){
102825 if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
102826 goto update_cleanup;
102828 for(j=0; j<pTab->nCol; j++){
102829 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
102830 if( j==pTab->iPKey ){
102831 chngRowid = 1;
102832 pRowidExpr = pChanges->a[i].pExpr;
102834 aXRef[j] = i;
102835 break;
102838 if( j>=pTab->nCol ){
102839 if( sqlite3IsRowid(pChanges->a[i].zName) ){
102840 j = -1;
102841 chngRowid = 1;
102842 pRowidExpr = pChanges->a[i].pExpr;
102843 }else{
102844 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
102845 pParse->checkSchema = 1;
102846 goto update_cleanup;
102849 #ifndef SQLITE_OMIT_AUTHORIZATION
102851 int rc;
102852 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
102853 j<0 ? "ROWID" : pTab->aCol[j].zName,
102854 db->aDb[iDb].zName);
102855 if( rc==SQLITE_DENY ){
102856 goto update_cleanup;
102857 }else if( rc==SQLITE_IGNORE ){
102858 aXRef[j] = -1;
102861 #endif
102864 hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
102866 /* Allocate memory for the array aRegIdx[]. There is one entry in the
102867 ** array for each index associated with table being updated. Fill in
102868 ** the value with a register number for indices that are to be used
102869 ** and with zero for unused indices.
102871 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
102872 if( nIdx>0 ){
102873 aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
102874 if( aRegIdx==0 ) goto update_cleanup;
102876 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102877 int reg;
102878 if( hasFK || chngRowid || pIdx->pPartIdxWhere ){
102879 reg = ++pParse->nMem;
102880 }else{
102881 reg = 0;
102882 for(i=0; i<pIdx->nColumn; i++){
102883 if( aXRef[pIdx->aiColumn[i]]>=0 ){
102884 reg = ++pParse->nMem;
102885 break;
102889 aRegIdx[j] = reg;
102892 /* Begin generating code. */
102893 v = sqlite3GetVdbe(pParse);
102894 if( v==0 ) goto update_cleanup;
102895 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
102896 sqlite3BeginWriteOperation(pParse, 1, iDb);
102898 #ifndef SQLITE_OMIT_VIRTUALTABLE
102899 /* Virtual tables must be handled separately */
102900 if( IsVirtual(pTab) ){
102901 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
102902 pWhere, onError);
102903 pWhere = 0;
102904 pTabList = 0;
102905 goto update_cleanup;
102907 #endif
102909 /* Allocate required registers. */
102910 regRowSet = ++pParse->nMem;
102911 regOldRowid = regNewRowid = ++pParse->nMem;
102912 if( pTrigger || hasFK ){
102913 regOld = pParse->nMem + 1;
102914 pParse->nMem += pTab->nCol;
102916 if( chngRowid || pTrigger || hasFK ){
102917 regNewRowid = ++pParse->nMem;
102919 regNew = pParse->nMem + 1;
102920 pParse->nMem += pTab->nCol;
102922 /* Start the view context. */
102923 if( isView ){
102924 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
102927 /* If we are trying to update a view, realize that view into
102928 ** a ephemeral table.
102930 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
102931 if( isView ){
102932 sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
102934 #endif
102936 /* Resolve the column names in all the expressions in the
102937 ** WHERE clause.
102939 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
102940 goto update_cleanup;
102943 /* Begin the database scan
102945 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
102946 pWInfo = sqlite3WhereBegin(
102947 pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
102949 if( pWInfo==0 ) goto update_cleanup;
102950 okOnePass = sqlite3WhereOkOnePass(pWInfo);
102952 /* Remember the rowid of every item to be updated.
102954 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
102955 if( !okOnePass ){
102956 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
102959 /* End the database scan loop.
102961 sqlite3WhereEnd(pWInfo);
102963 /* Initialize the count of updated rows
102965 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
102966 regRowCount = ++pParse->nMem;
102967 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
102970 if( !isView ){
102972 ** Open every index that needs updating. Note that if any
102973 ** index could potentially invoke a REPLACE conflict resolution
102974 ** action, then we need to open all indices because we might need
102975 ** to be deleting some records.
102977 if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
102978 if( onError==OE_Replace ){
102979 openAll = 1;
102980 }else{
102981 openAll = 0;
102982 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102983 if( pIdx->onError==OE_Replace ){
102984 openAll = 1;
102985 break;
102989 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
102990 assert( aRegIdx );
102991 if( openAll || aRegIdx[i]>0 ){
102992 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
102993 sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
102994 (char*)pKey, P4_KEYINFO_HANDOFF);
102995 assert( pParse->nTab>iCur+i+1 );
103000 /* Top of the update loop */
103001 if( okOnePass ){
103002 int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
103003 addr = sqlite3VdbeAddOp0(v, OP_Goto);
103004 sqlite3VdbeJumpHere(v, a1);
103005 }else{
103006 addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
103009 /* Make cursor iCur point to the record that is being updated. If
103010 ** this record does not exist for some reason (deleted by a trigger,
103011 ** for example, then jump to the next iteration of the RowSet loop. */
103012 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
103014 /* If the record number will change, set register regNewRowid to
103015 ** contain the new value. If the record number is not being modified,
103016 ** then regNewRowid is the same register as regOldRowid, which is
103017 ** already populated. */
103018 assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
103019 if( chngRowid ){
103020 sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
103021 sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
103024 /* If there are triggers on this table, populate an array of registers
103025 ** with the required old.* column data. */
103026 if( hasFK || pTrigger ){
103027 u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
103028 oldmask |= sqlite3TriggerColmask(pParse,
103029 pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
103031 for(i=0; i<pTab->nCol; i++){
103032 if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
103033 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
103034 }else{
103035 sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
103038 if( chngRowid==0 ){
103039 sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
103043 /* Populate the array of registers beginning at regNew with the new
103044 ** row data. This array is used to check constaints, create the new
103045 ** table and index records, and as the values for any new.* references
103046 ** made by triggers.
103048 ** If there are one or more BEFORE triggers, then do not populate the
103049 ** registers associated with columns that are (a) not modified by
103050 ** this UPDATE statement and (b) not accessed by new.* references. The
103051 ** values for registers not modified by the UPDATE must be reloaded from
103052 ** the database after the BEFORE triggers are fired anyway (as the trigger
103053 ** may have modified them). So not loading those that are not going to
103054 ** be used eliminates some redundant opcodes.
103056 newmask = sqlite3TriggerColmask(
103057 pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
103059 sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
103060 for(i=0; i<pTab->nCol; i++){
103061 if( i==pTab->iPKey ){
103062 /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
103063 }else{
103064 j = aXRef[i];
103065 if( j>=0 ){
103066 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
103067 }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
103068 /* This branch loads the value of a column that will not be changed
103069 ** into a register. This is done if there are no BEFORE triggers, or
103070 ** if there are one or more BEFORE triggers that use this value via
103071 ** a new.* reference in a trigger program.
103073 testcase( i==31 );
103074 testcase( i==32 );
103075 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
103076 sqlite3ColumnDefault(v, pTab, i, regNew+i);
103081 /* Fire any BEFORE UPDATE triggers. This happens before constraints are
103082 ** verified. One could argue that this is wrong.
103084 if( tmask&TRIGGER_BEFORE ){
103085 sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
103086 sqlite3TableAffinityStr(v, pTab);
103087 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
103088 TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
103090 /* The row-trigger may have deleted the row being updated. In this
103091 ** case, jump to the next row. No updates or AFTER triggers are
103092 ** required. This behavior - what happens when the row being updated
103093 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
103094 ** documentation.
103096 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
103098 /* If it did not delete it, the row-trigger may still have modified
103099 ** some of the columns of the row being updated. Load the values for
103100 ** all columns not modified by the update statement into their
103101 ** registers in case this has happened.
103103 for(i=0; i<pTab->nCol; i++){
103104 if( aXRef[i]<0 && i!=pTab->iPKey ){
103105 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
103106 sqlite3ColumnDefault(v, pTab, i, regNew+i);
103111 if( !isView ){
103112 int j1; /* Address of jump instruction */
103114 /* Do constraint checks. */
103115 sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
103116 aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
103118 /* Do FK constraint checks. */
103119 if( hasFK ){
103120 sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
103123 /* Delete the index entries associated with the current record. */
103124 j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
103125 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
103127 /* If changing the record number, delete the old record. */
103128 if( hasFK || chngRowid ){
103129 sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
103131 sqlite3VdbeJumpHere(v, j1);
103133 if( hasFK ){
103134 sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
103137 /* Insert the new index entries and the new record. */
103138 sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
103140 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
103141 ** handle rows (possibly in other tables) that refer via a foreign key
103142 ** to the row just updated. */
103143 if( hasFK ){
103144 sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
103148 /* Increment the row counter
103150 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
103151 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
103154 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
103155 TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
103157 /* Repeat the above with the next record to be updated, until
103158 ** all record selected by the WHERE clause have been updated.
103160 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
103161 sqlite3VdbeJumpHere(v, addr);
103163 /* Close all tables */
103164 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
103165 assert( aRegIdx );
103166 if( openAll || aRegIdx[i]>0 ){
103167 sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
103170 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
103172 /* Update the sqlite_sequence table by storing the content of the
103173 ** maximum rowid counter values recorded while inserting into
103174 ** autoincrement tables.
103176 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
103177 sqlite3AutoincrementEnd(pParse);
103181 ** Return the number of rows that were changed. If this routine is
103182 ** generating code because of a call to sqlite3NestedParse(), do not
103183 ** invoke the callback function.
103185 if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
103186 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
103187 sqlite3VdbeSetNumCols(v, 1);
103188 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
103191 update_cleanup:
103192 sqlite3AuthContextPop(&sContext);
103193 sqlite3DbFree(db, aRegIdx);
103194 sqlite3DbFree(db, aXRef);
103195 sqlite3SrcListDelete(db, pTabList);
103196 sqlite3ExprListDelete(db, pChanges);
103197 sqlite3ExprDelete(db, pWhere);
103198 return;
103200 /* Make sure "isView" and other macros defined above are undefined. Otherwise
103201 ** thely may interfere with compilation of other functions in this file
103202 ** (or in another file, if this file becomes part of the amalgamation). */
103203 #ifdef isView
103204 #undef isView
103205 #endif
103206 #ifdef pTrigger
103207 #undef pTrigger
103208 #endif
103210 #ifndef SQLITE_OMIT_VIRTUALTABLE
103212 ** Generate code for an UPDATE of a virtual table.
103214 ** The strategy is that we create an ephemerial table that contains
103215 ** for each row to be changed:
103217 ** (A) The original rowid of that row.
103218 ** (B) The revised rowid for the row. (note1)
103219 ** (C) The content of every column in the row.
103221 ** Then we loop over this ephemeral table and for each row in
103222 ** the ephermeral table call VUpdate.
103224 ** When finished, drop the ephemeral table.
103226 ** (note1) Actually, if we know in advance that (A) is always the same
103227 ** as (B) we only store (A), then duplicate (A) when pulling
103228 ** it out of the ephemeral table before calling VUpdate.
103230 static void updateVirtualTable(
103231 Parse *pParse, /* The parsing context */
103232 SrcList *pSrc, /* The virtual table to be modified */
103233 Table *pTab, /* The virtual table */
103234 ExprList *pChanges, /* The columns to change in the UPDATE statement */
103235 Expr *pRowid, /* Expression used to recompute the rowid */
103236 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
103237 Expr *pWhere, /* WHERE clause of the UPDATE statement */
103238 int onError /* ON CONFLICT strategy */
103240 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
103241 ExprList *pEList = 0; /* The result set of the SELECT statement */
103242 Select *pSelect = 0; /* The SELECT statement */
103243 Expr *pExpr; /* Temporary expression */
103244 int ephemTab; /* Table holding the result of the SELECT */
103245 int i; /* Loop counter */
103246 int addr; /* Address of top of loop */
103247 int iReg; /* First register in set passed to OP_VUpdate */
103248 sqlite3 *db = pParse->db; /* Database connection */
103249 const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
103250 SelectDest dest;
103252 /* Construct the SELECT statement that will find the new values for
103253 ** all updated rows.
103255 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
103256 if( pRowid ){
103257 pEList = sqlite3ExprListAppend(pParse, pEList,
103258 sqlite3ExprDup(db, pRowid, 0));
103260 assert( pTab->iPKey<0 );
103261 for(i=0; i<pTab->nCol; i++){
103262 if( aXRef[i]>=0 ){
103263 pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
103264 }else{
103265 pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
103267 pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
103269 pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
103271 /* Create the ephemeral table into which the update results will
103272 ** be stored.
103274 assert( v );
103275 ephemTab = pParse->nTab++;
103276 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
103277 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
103279 /* fill the ephemeral table
103281 sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
103282 sqlite3Select(pParse, pSelect, &dest);
103284 /* Generate code to scan the ephemeral table and call VUpdate. */
103285 iReg = ++pParse->nMem;
103286 pParse->nMem += pTab->nCol+1;
103287 addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
103288 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
103289 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
103290 for(i=0; i<pTab->nCol; i++){
103291 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
103293 sqlite3VtabMakeWritable(pParse, pTab);
103294 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
103295 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
103296 sqlite3MayAbort(pParse);
103297 sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
103298 sqlite3VdbeJumpHere(v, addr);
103299 sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
103301 /* Cleanup */
103302 sqlite3SelectDelete(db, pSelect);
103304 #endif /* SQLITE_OMIT_VIRTUALTABLE */
103306 /************** End of update.c **********************************************/
103307 /************** Begin file vacuum.c ******************************************/
103309 ** 2003 April 6
103311 ** The author disclaims copyright to this source code. In place of
103312 ** a legal notice, here is a blessing:
103314 ** May you do good and not evil.
103315 ** May you find forgiveness for yourself and forgive others.
103316 ** May you share freely, never taking more than you give.
103318 *************************************************************************
103319 ** This file contains code used to implement the VACUUM command.
103321 ** Most of the code in this file may be omitted by defining the
103322 ** SQLITE_OMIT_VACUUM macro.
103325 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
103327 ** Finalize a prepared statement. If there was an error, store the
103328 ** text of the error message in *pzErrMsg. Return the result code.
103330 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
103331 int rc;
103332 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
103333 if( rc ){
103334 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
103336 return rc;
103340 ** Execute zSql on database db. Return an error code.
103342 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
103343 sqlite3_stmt *pStmt;
103344 VVA_ONLY( int rc; )
103345 if( !zSql ){
103346 return SQLITE_NOMEM;
103348 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
103349 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
103350 return sqlite3_errcode(db);
103352 VVA_ONLY( rc = ) sqlite3_step(pStmt);
103353 assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
103354 return vacuumFinalize(db, pStmt, pzErrMsg);
103358 ** Execute zSql on database db. The statement returns exactly
103359 ** one column. Execute this as SQL on the same database.
103361 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
103362 sqlite3_stmt *pStmt;
103363 int rc;
103365 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
103366 if( rc!=SQLITE_OK ) return rc;
103368 while( SQLITE_ROW==sqlite3_step(pStmt) ){
103369 rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
103370 if( rc!=SQLITE_OK ){
103371 vacuumFinalize(db, pStmt, pzErrMsg);
103372 return rc;
103376 return vacuumFinalize(db, pStmt, pzErrMsg);
103380 ** The non-standard VACUUM command is used to clean up the database,
103381 ** collapse free space, etc. It is modelled after the VACUUM command
103382 ** in PostgreSQL.
103384 ** In version 1.0.x of SQLite, the VACUUM command would call
103385 ** gdbm_reorganize() on all the database tables. But beginning
103386 ** with 2.0.0, SQLite no longer uses GDBM so this command has
103387 ** become a no-op.
103389 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
103390 Vdbe *v = sqlite3GetVdbe(pParse);
103391 if( v ){
103392 sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
103393 sqlite3VdbeUsesBtree(v, 0);
103395 return;
103399 ** This routine implements the OP_Vacuum opcode of the VDBE.
103401 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
103402 int rc = SQLITE_OK; /* Return code from service routines */
103403 Btree *pMain; /* The database being vacuumed */
103404 Btree *pTemp; /* The temporary database we vacuum into */
103405 char *zSql = 0; /* SQL statements */
103406 int saved_flags; /* Saved value of the db->flags */
103407 int saved_nChange; /* Saved value of db->nChange */
103408 int saved_nTotalChange; /* Saved value of db->nTotalChange */
103409 void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
103410 Db *pDb = 0; /* Database to detach at end of vacuum */
103411 int isMemDb; /* True if vacuuming a :memory: database */
103412 int nRes; /* Bytes of reserved space at the end of each page */
103413 int nDb; /* Number of attached databases */
103415 if( !db->autoCommit ){
103416 sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
103417 return SQLITE_ERROR;
103419 if( db->nVdbeActive>1 ){
103420 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
103421 return SQLITE_ERROR;
103424 /* Save the current value of the database flags so that it can be
103425 ** restored before returning. Then set the writable-schema flag, and
103426 ** disable CHECK and foreign key constraints. */
103427 saved_flags = db->flags;
103428 saved_nChange = db->nChange;
103429 saved_nTotalChange = db->nTotalChange;
103430 saved_xTrace = db->xTrace;
103431 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
103432 db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
103433 db->xTrace = 0;
103435 pMain = db->aDb[0].pBt;
103436 isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
103438 /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
103439 ** can be set to 'off' for this file, as it is not recovered if a crash
103440 ** occurs anyway. The integrity of the database is maintained by a
103441 ** (possibly synchronous) transaction opened on the main database before
103442 ** sqlite3BtreeCopyFile() is called.
103444 ** An optimisation would be to use a non-journaled pager.
103445 ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
103446 ** that actually made the VACUUM run slower. Very little journalling
103447 ** actually occurs when doing a vacuum since the vacuum_db is initially
103448 ** empty. Only the journal header is written. Apparently it takes more
103449 ** time to parse and run the PRAGMA to turn journalling off than it does
103450 ** to write the journal header file.
103452 nDb = db->nDb;
103453 if( sqlite3TempInMemory(db) ){
103454 zSql = "ATTACH ':memory:' AS vacuum_db;";
103455 }else{
103456 zSql = "ATTACH '' AS vacuum_db;";
103458 rc = execSql(db, pzErrMsg, zSql);
103459 if( db->nDb>nDb ){
103460 pDb = &db->aDb[db->nDb-1];
103461 assert( strcmp(pDb->zName,"vacuum_db")==0 );
103463 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103464 pTemp = db->aDb[db->nDb-1].pBt;
103466 /* The call to execSql() to attach the temp database has left the file
103467 ** locked (as there was more than one active statement when the transaction
103468 ** to read the schema was concluded. Unlock it here so that this doesn't
103469 ** cause problems for the call to BtreeSetPageSize() below. */
103470 sqlite3BtreeCommit(pTemp);
103472 nRes = sqlite3BtreeGetReserve(pMain);
103474 /* A VACUUM cannot change the pagesize of an encrypted database. */
103475 #ifdef SQLITE_HAS_CODEC
103476 if( db->nextPagesize ){
103477 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
103478 int nKey;
103479 char *zKey;
103480 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
103481 if( nKey ) db->nextPagesize = 0;
103483 #endif
103485 rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
103486 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103488 /* Begin a transaction and take an exclusive lock on the main database
103489 ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
103490 ** to ensure that we do not try to change the page-size on a WAL database.
103492 rc = execSql(db, pzErrMsg, "BEGIN;");
103493 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103494 rc = sqlite3BtreeBeginTrans(pMain, 2);
103495 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103497 /* Do not attempt to change the page size for a WAL database */
103498 if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
103499 ==PAGER_JOURNALMODE_WAL ){
103500 db->nextPagesize = 0;
103503 if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
103504 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
103505 || NEVER(db->mallocFailed)
103507 rc = SQLITE_NOMEM;
103508 goto end_of_vacuum;
103511 #ifndef SQLITE_OMIT_AUTOVACUUM
103512 sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
103513 sqlite3BtreeGetAutoVacuum(pMain));
103514 #endif
103516 /* Query the schema of the main database. Create a mirror schema
103517 ** in the temporary database.
103519 rc = execExecSql(db, pzErrMsg,
103520 "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
103521 " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
103522 " AND rootpage>0"
103524 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103525 rc = execExecSql(db, pzErrMsg,
103526 "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
103527 " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
103528 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103529 rc = execExecSql(db, pzErrMsg,
103530 "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
103531 " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
103532 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103534 /* Loop through the tables in the main database. For each, do
103535 ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
103536 ** the contents to the temporary database.
103538 rc = execExecSql(db, pzErrMsg,
103539 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
103540 "|| ' SELECT * FROM main.' || quote(name) || ';'"
103541 "FROM main.sqlite_master "
103542 "WHERE type = 'table' AND name!='sqlite_sequence' "
103543 " AND rootpage>0"
103545 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103547 /* Copy over the sequence table
103549 rc = execExecSql(db, pzErrMsg,
103550 "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
103551 "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
103553 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103554 rc = execExecSql(db, pzErrMsg,
103555 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
103556 "|| ' SELECT * FROM main.' || quote(name) || ';' "
103557 "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
103559 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103562 /* Copy the triggers, views, and virtual tables from the main database
103563 ** over to the temporary database. None of these objects has any
103564 ** associated storage, so all we have to do is copy their entries
103565 ** from the SQLITE_MASTER table.
103567 rc = execSql(db, pzErrMsg,
103568 "INSERT INTO vacuum_db.sqlite_master "
103569 " SELECT type, name, tbl_name, rootpage, sql"
103570 " FROM main.sqlite_master"
103571 " WHERE type='view' OR type='trigger'"
103572 " OR (type='table' AND rootpage=0)"
103574 if( rc ) goto end_of_vacuum;
103576 /* At this point, there is a write transaction open on both the
103577 ** vacuum database and the main database. Assuming no error occurs,
103578 ** both transactions are closed by this block - the main database
103579 ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
103580 ** call to sqlite3BtreeCommit().
103583 u32 meta;
103584 int i;
103586 /* This array determines which meta meta values are preserved in the
103587 ** vacuum. Even entries are the meta value number and odd entries
103588 ** are an increment to apply to the meta value after the vacuum.
103589 ** The increment is used to increase the schema cookie so that other
103590 ** connections to the same database will know to reread the schema.
103592 static const unsigned char aCopy[] = {
103593 BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
103594 BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
103595 BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
103596 BTREE_USER_VERSION, 0, /* Preserve the user version */
103597 BTREE_APPLICATION_ID, 0, /* Preserve the application id */
103600 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
103601 assert( 1==sqlite3BtreeIsInTrans(pMain) );
103603 /* Copy Btree meta values */
103604 for(i=0; i<ArraySize(aCopy); i+=2){
103605 /* GetMeta() and UpdateMeta() cannot fail in this context because
103606 ** we already have page 1 loaded into cache and marked dirty. */
103607 sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
103608 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
103609 if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
103612 rc = sqlite3BtreeCopyFile(pMain, pTemp);
103613 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103614 rc = sqlite3BtreeCommit(pTemp);
103615 if( rc!=SQLITE_OK ) goto end_of_vacuum;
103616 #ifndef SQLITE_OMIT_AUTOVACUUM
103617 sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
103618 #endif
103621 assert( rc==SQLITE_OK );
103622 rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
103624 end_of_vacuum:
103625 /* Restore the original value of db->flags */
103626 db->flags = saved_flags;
103627 db->nChange = saved_nChange;
103628 db->nTotalChange = saved_nTotalChange;
103629 db->xTrace = saved_xTrace;
103630 sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
103632 /* Currently there is an SQL level transaction open on the vacuum
103633 ** database. No locks are held on any other files (since the main file
103634 ** was committed at the btree level). So it safe to end the transaction
103635 ** by manually setting the autoCommit flag to true and detaching the
103636 ** vacuum database. The vacuum_db journal file is deleted when the pager
103637 ** is closed by the DETACH.
103639 db->autoCommit = 1;
103641 if( pDb ){
103642 sqlite3BtreeClose(pDb->pBt);
103643 pDb->pBt = 0;
103644 pDb->pSchema = 0;
103647 /* This both clears the schemas and reduces the size of the db->aDb[]
103648 ** array. */
103649 sqlite3ResetAllSchemasOfConnection(db);
103651 return rc;
103654 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
103656 /************** End of vacuum.c **********************************************/
103657 /************** Begin file vtab.c ********************************************/
103659 ** 2006 June 10
103661 ** The author disclaims copyright to this source code. In place of
103662 ** a legal notice, here is a blessing:
103664 ** May you do good and not evil.
103665 ** May you find forgiveness for yourself and forgive others.
103666 ** May you share freely, never taking more than you give.
103668 *************************************************************************
103669 ** This file contains code used to help implement virtual tables.
103671 #ifndef SQLITE_OMIT_VIRTUALTABLE
103674 ** Before a virtual table xCreate() or xConnect() method is invoked, the
103675 ** sqlite3.pVtabCtx member variable is set to point to an instance of
103676 ** this struct allocated on the stack. It is used by the implementation of
103677 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
103678 ** are invoked only from within xCreate and xConnect methods.
103680 struct VtabCtx {
103681 VTable *pVTable; /* The virtual table being constructed */
103682 Table *pTab; /* The Table object to which the virtual table belongs */
103686 ** The actual function that does the work of creating a new module.
103687 ** This function implements the sqlite3_create_module() and
103688 ** sqlite3_create_module_v2() interfaces.
103690 static int createModule(
103691 sqlite3 *db, /* Database in which module is registered */
103692 const char *zName, /* Name assigned to this module */
103693 const sqlite3_module *pModule, /* The definition of the module */
103694 void *pAux, /* Context pointer for xCreate/xConnect */
103695 void (*xDestroy)(void *) /* Module destructor function */
103697 int rc = SQLITE_OK;
103698 int nName;
103700 sqlite3_mutex_enter(db->mutex);
103701 nName = sqlite3Strlen30(zName);
103702 if( sqlite3HashFind(&db->aModule, zName, nName) ){
103703 rc = SQLITE_MISUSE_BKPT;
103704 }else{
103705 Module *pMod;
103706 pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
103707 if( pMod ){
103708 Module *pDel;
103709 char *zCopy = (char *)(&pMod[1]);
103710 memcpy(zCopy, zName, nName+1);
103711 pMod->zName = zCopy;
103712 pMod->pModule = pModule;
103713 pMod->pAux = pAux;
103714 pMod->xDestroy = xDestroy;
103715 pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
103716 assert( pDel==0 || pDel==pMod );
103717 if( pDel ){
103718 db->mallocFailed = 1;
103719 sqlite3DbFree(db, pDel);
103723 rc = sqlite3ApiExit(db, rc);
103724 if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
103726 sqlite3_mutex_leave(db->mutex);
103727 return rc;
103732 ** External API function used to create a new virtual-table module.
103734 SQLITE_API int sqlite3_create_module(
103735 sqlite3 *db, /* Database in which module is registered */
103736 const char *zName, /* Name assigned to this module */
103737 const sqlite3_module *pModule, /* The definition of the module */
103738 void *pAux /* Context pointer for xCreate/xConnect */
103740 return createModule(db, zName, pModule, pAux, 0);
103744 ** External API function used to create a new virtual-table module.
103746 SQLITE_API int sqlite3_create_module_v2(
103747 sqlite3 *db, /* Database in which module is registered */
103748 const char *zName, /* Name assigned to this module */
103749 const sqlite3_module *pModule, /* The definition of the module */
103750 void *pAux, /* Context pointer for xCreate/xConnect */
103751 void (*xDestroy)(void *) /* Module destructor function */
103753 return createModule(db, zName, pModule, pAux, xDestroy);
103757 ** Lock the virtual table so that it cannot be disconnected.
103758 ** Locks nest. Every lock should have a corresponding unlock.
103759 ** If an unlock is omitted, resources leaks will occur.
103761 ** If a disconnect is attempted while a virtual table is locked,
103762 ** the disconnect is deferred until all locks have been removed.
103764 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
103765 pVTab->nRef++;
103770 ** pTab is a pointer to a Table structure representing a virtual-table.
103771 ** Return a pointer to the VTable object used by connection db to access
103772 ** this virtual-table, if one has been created, or NULL otherwise.
103774 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
103775 VTable *pVtab;
103776 assert( IsVirtual(pTab) );
103777 for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
103778 return pVtab;
103782 ** Decrement the ref-count on a virtual table object. When the ref-count
103783 ** reaches zero, call the xDisconnect() method to delete the object.
103785 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
103786 sqlite3 *db = pVTab->db;
103788 assert( db );
103789 assert( pVTab->nRef>0 );
103790 assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
103792 pVTab->nRef--;
103793 if( pVTab->nRef==0 ){
103794 sqlite3_vtab *p = pVTab->pVtab;
103795 if( p ){
103796 p->pModule->xDisconnect(p);
103798 sqlite3DbFree(db, pVTab);
103803 ** Table p is a virtual table. This function moves all elements in the
103804 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
103805 ** database connections to be disconnected at the next opportunity.
103806 ** Except, if argument db is not NULL, then the entry associated with
103807 ** connection db is left in the p->pVTable list.
103809 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
103810 VTable *pRet = 0;
103811 VTable *pVTable = p->pVTable;
103812 p->pVTable = 0;
103814 /* Assert that the mutex (if any) associated with the BtShared database
103815 ** that contains table p is held by the caller. See header comments
103816 ** above function sqlite3VtabUnlockList() for an explanation of why
103817 ** this makes it safe to access the sqlite3.pDisconnect list of any
103818 ** database connection that may have an entry in the p->pVTable list.
103820 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
103822 while( pVTable ){
103823 sqlite3 *db2 = pVTable->db;
103824 VTable *pNext = pVTable->pNext;
103825 assert( db2 );
103826 if( db2==db ){
103827 pRet = pVTable;
103828 p->pVTable = pRet;
103829 pRet->pNext = 0;
103830 }else{
103831 pVTable->pNext = db2->pDisconnect;
103832 db2->pDisconnect = pVTable;
103834 pVTable = pNext;
103837 assert( !db || pRet );
103838 return pRet;
103842 ** Table *p is a virtual table. This function removes the VTable object
103843 ** for table *p associated with database connection db from the linked
103844 ** list in p->pVTab. It also decrements the VTable ref count. This is
103845 ** used when closing database connection db to free all of its VTable
103846 ** objects without disturbing the rest of the Schema object (which may
103847 ** be being used by other shared-cache connections).
103849 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
103850 VTable **ppVTab;
103852 assert( IsVirtual(p) );
103853 assert( sqlite3BtreeHoldsAllMutexes(db) );
103854 assert( sqlite3_mutex_held(db->mutex) );
103856 for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
103857 if( (*ppVTab)->db==db ){
103858 VTable *pVTab = *ppVTab;
103859 *ppVTab = pVTab->pNext;
103860 sqlite3VtabUnlock(pVTab);
103861 break;
103868 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
103870 ** This function may only be called when the mutexes associated with all
103871 ** shared b-tree databases opened using connection db are held by the
103872 ** caller. This is done to protect the sqlite3.pDisconnect list. The
103873 ** sqlite3.pDisconnect list is accessed only as follows:
103875 ** 1) By this function. In this case, all BtShared mutexes and the mutex
103876 ** associated with the database handle itself must be held.
103878 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
103879 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
103880 ** associated with the database the virtual table is stored in is held
103881 ** or, if the virtual table is stored in a non-sharable database, then
103882 ** the database handle mutex is held.
103884 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
103885 ** by multiple threads. It is thread-safe.
103887 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
103888 VTable *p = db->pDisconnect;
103889 db->pDisconnect = 0;
103891 assert( sqlite3BtreeHoldsAllMutexes(db) );
103892 assert( sqlite3_mutex_held(db->mutex) );
103894 if( p ){
103895 sqlite3ExpirePreparedStatements(db);
103897 VTable *pNext = p->pNext;
103898 sqlite3VtabUnlock(p);
103899 p = pNext;
103900 }while( p );
103905 ** Clear any and all virtual-table information from the Table record.
103906 ** This routine is called, for example, just before deleting the Table
103907 ** record.
103909 ** Since it is a virtual-table, the Table structure contains a pointer
103910 ** to the head of a linked list of VTable structures. Each VTable
103911 ** structure is associated with a single sqlite3* user of the schema.
103912 ** The reference count of the VTable structure associated with database
103913 ** connection db is decremented immediately (which may lead to the
103914 ** structure being xDisconnected and free). Any other VTable structures
103915 ** in the list are moved to the sqlite3.pDisconnect list of the associated
103916 ** database connection.
103918 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
103919 if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
103920 if( p->azModuleArg ){
103921 int i;
103922 for(i=0; i<p->nModuleArg; i++){
103923 if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
103925 sqlite3DbFree(db, p->azModuleArg);
103930 ** Add a new module argument to pTable->azModuleArg[].
103931 ** The string is not copied - the pointer is stored. The
103932 ** string will be freed automatically when the table is
103933 ** deleted.
103935 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
103936 int i = pTable->nModuleArg++;
103937 int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
103938 char **azModuleArg;
103939 azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
103940 if( azModuleArg==0 ){
103941 int j;
103942 for(j=0; j<i; j++){
103943 sqlite3DbFree(db, pTable->azModuleArg[j]);
103945 sqlite3DbFree(db, zArg);
103946 sqlite3DbFree(db, pTable->azModuleArg);
103947 pTable->nModuleArg = 0;
103948 }else{
103949 azModuleArg[i] = zArg;
103950 azModuleArg[i+1] = 0;
103952 pTable->azModuleArg = azModuleArg;
103956 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
103957 ** statement. The module name has been parsed, but the optional list
103958 ** of parameters that follow the module name are still pending.
103960 SQLITE_PRIVATE void sqlite3VtabBeginParse(
103961 Parse *pParse, /* Parsing context */
103962 Token *pName1, /* Name of new table, or database name */
103963 Token *pName2, /* Name of new table or NULL */
103964 Token *pModuleName, /* Name of the module for the virtual table */
103965 int ifNotExists /* No error if the table already exists */
103967 int iDb; /* The database the table is being created in */
103968 Table *pTable; /* The new virtual table */
103969 sqlite3 *db; /* Database connection */
103971 sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
103972 pTable = pParse->pNewTable;
103973 if( pTable==0 ) return;
103974 assert( 0==pTable->pIndex );
103976 db = pParse->db;
103977 iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
103978 assert( iDb>=0 );
103980 pTable->tabFlags |= TF_Virtual;
103981 pTable->nModuleArg = 0;
103982 addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
103983 addModuleArgument(db, pTable, 0);
103984 addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
103985 pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
103987 #ifndef SQLITE_OMIT_AUTHORIZATION
103988 /* Creating a virtual table invokes the authorization callback twice.
103989 ** The first invocation, to obtain permission to INSERT a row into the
103990 ** sqlite_master table, has already been made by sqlite3StartTable().
103991 ** The second call, to obtain permission to create the table, is made now.
103993 if( pTable->azModuleArg ){
103994 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
103995 pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
103997 #endif
104001 ** This routine takes the module argument that has been accumulating
104002 ** in pParse->zArg[] and appends it to the list of arguments on the
104003 ** virtual table currently under construction in pParse->pTable.
104005 static void addArgumentToVtab(Parse *pParse){
104006 if( pParse->sArg.z && pParse->pNewTable ){
104007 const char *z = (const char*)pParse->sArg.z;
104008 int n = pParse->sArg.n;
104009 sqlite3 *db = pParse->db;
104010 addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
104015 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
104016 ** has been completely parsed.
104018 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
104019 Table *pTab = pParse->pNewTable; /* The table being constructed */
104020 sqlite3 *db = pParse->db; /* The database connection */
104022 if( pTab==0 ) return;
104023 addArgumentToVtab(pParse);
104024 pParse->sArg.z = 0;
104025 if( pTab->nModuleArg<1 ) return;
104027 /* If the CREATE VIRTUAL TABLE statement is being entered for the
104028 ** first time (in other words if the virtual table is actually being
104029 ** created now instead of just being read out of sqlite_master) then
104030 ** do additional initialization work and store the statement text
104031 ** in the sqlite_master table.
104033 if( !db->init.busy ){
104034 char *zStmt;
104035 char *zWhere;
104036 int iDb;
104037 Vdbe *v;
104039 /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
104040 if( pEnd ){
104041 pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
104043 zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
104045 /* A slot for the record has already been allocated in the
104046 ** SQLITE_MASTER table. We just need to update that slot with all
104047 ** the information we've collected.
104049 ** The VM register number pParse->regRowid holds the rowid of an
104050 ** entry in the sqlite_master table tht was created for this vtab
104051 ** by sqlite3StartTable().
104053 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
104054 sqlite3NestedParse(pParse,
104055 "UPDATE %Q.%s "
104056 "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
104057 "WHERE rowid=#%d",
104058 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
104059 pTab->zName,
104060 pTab->zName,
104061 zStmt,
104062 pParse->regRowid
104064 sqlite3DbFree(db, zStmt);
104065 v = sqlite3GetVdbe(pParse);
104066 sqlite3ChangeCookie(pParse, iDb);
104068 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
104069 zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
104070 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
104071 sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
104072 pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
104075 /* If we are rereading the sqlite_master table create the in-memory
104076 ** record of the table. The xConnect() method is not called until
104077 ** the first time the virtual table is used in an SQL statement. This
104078 ** allows a schema that contains virtual tables to be loaded before
104079 ** the required virtual table implementations are registered. */
104080 else {
104081 Table *pOld;
104082 Schema *pSchema = pTab->pSchema;
104083 const char *zName = pTab->zName;
104084 int nName = sqlite3Strlen30(zName);
104085 assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
104086 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
104087 if( pOld ){
104088 db->mallocFailed = 1;
104089 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
104090 return;
104092 pParse->pNewTable = 0;
104097 ** The parser calls this routine when it sees the first token
104098 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
104100 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
104101 addArgumentToVtab(pParse);
104102 pParse->sArg.z = 0;
104103 pParse->sArg.n = 0;
104107 ** The parser calls this routine for each token after the first token
104108 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
104110 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
104111 Token *pArg = &pParse->sArg;
104112 if( pArg->z==0 ){
104113 pArg->z = p->z;
104114 pArg->n = p->n;
104115 }else{
104116 assert(pArg->z < p->z);
104117 pArg->n = (int)(&p->z[p->n] - pArg->z);
104122 ** Invoke a virtual table constructor (either xCreate or xConnect). The
104123 ** pointer to the function to invoke is passed as the fourth parameter
104124 ** to this procedure.
104126 static int vtabCallConstructor(
104127 sqlite3 *db,
104128 Table *pTab,
104129 Module *pMod,
104130 int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
104131 char **pzErr
104133 VtabCtx sCtx, *pPriorCtx;
104134 VTable *pVTable;
104135 int rc;
104136 const char *const*azArg = (const char *const*)pTab->azModuleArg;
104137 int nArg = pTab->nModuleArg;
104138 char *zErr = 0;
104139 char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
104140 int iDb;
104142 if( !zModuleName ){
104143 return SQLITE_NOMEM;
104146 pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
104147 if( !pVTable ){
104148 sqlite3DbFree(db, zModuleName);
104149 return SQLITE_NOMEM;
104151 pVTable->db = db;
104152 pVTable->pMod = pMod;
104154 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
104155 pTab->azModuleArg[1] = db->aDb[iDb].zName;
104157 /* Invoke the virtual table constructor */
104158 assert( &db->pVtabCtx );
104159 assert( xConstruct );
104160 sCtx.pTab = pTab;
104161 sCtx.pVTable = pVTable;
104162 pPriorCtx = db->pVtabCtx;
104163 db->pVtabCtx = &sCtx;
104164 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
104165 db->pVtabCtx = pPriorCtx;
104166 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
104168 if( SQLITE_OK!=rc ){
104169 if( zErr==0 ){
104170 *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
104171 }else {
104172 *pzErr = sqlite3MPrintf(db, "%s", zErr);
104173 sqlite3_free(zErr);
104175 sqlite3DbFree(db, pVTable);
104176 }else if( ALWAYS(pVTable->pVtab) ){
104177 /* Justification of ALWAYS(): A correct vtab constructor must allocate
104178 ** the sqlite3_vtab object if successful. */
104179 pVTable->pVtab->pModule = pMod->pModule;
104180 pVTable->nRef = 1;
104181 if( sCtx.pTab ){
104182 const char *zFormat = "vtable constructor did not declare schema: %s";
104183 *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
104184 sqlite3VtabUnlock(pVTable);
104185 rc = SQLITE_ERROR;
104186 }else{
104187 int iCol;
104188 /* If everything went according to plan, link the new VTable structure
104189 ** into the linked list headed by pTab->pVTable. Then loop through the
104190 ** columns of the table to see if any of them contain the token "hidden".
104191 ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
104192 ** the type string. */
104193 pVTable->pNext = pTab->pVTable;
104194 pTab->pVTable = pVTable;
104196 for(iCol=0; iCol<pTab->nCol; iCol++){
104197 char *zType = pTab->aCol[iCol].zType;
104198 int nType;
104199 int i = 0;
104200 if( !zType ) continue;
104201 nType = sqlite3Strlen30(zType);
104202 if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
104203 for(i=0; i<nType; i++){
104204 if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
104205 && (zType[i+7]=='\0' || zType[i+7]==' ')
104208 break;
104212 if( i<nType ){
104213 int j;
104214 int nDel = 6 + (zType[i+6] ? 1 : 0);
104215 for(j=i; (j+nDel)<=nType; j++){
104216 zType[j] = zType[j+nDel];
104218 if( zType[i]=='\0' && i>0 ){
104219 assert(zType[i-1]==' ');
104220 zType[i-1] = '\0';
104222 pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
104228 sqlite3DbFree(db, zModuleName);
104229 return rc;
104233 ** This function is invoked by the parser to call the xConnect() method
104234 ** of the virtual table pTab. If an error occurs, an error code is returned
104235 ** and an error left in pParse.
104237 ** This call is a no-op if table pTab is not a virtual table.
104239 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
104240 sqlite3 *db = pParse->db;
104241 const char *zMod;
104242 Module *pMod;
104243 int rc;
104245 assert( pTab );
104246 if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
104247 return SQLITE_OK;
104250 /* Locate the required virtual table module */
104251 zMod = pTab->azModuleArg[0];
104252 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
104254 if( !pMod ){
104255 const char *zModule = pTab->azModuleArg[0];
104256 sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
104257 rc = SQLITE_ERROR;
104258 }else{
104259 char *zErr = 0;
104260 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
104261 if( rc!=SQLITE_OK ){
104262 sqlite3ErrorMsg(pParse, "%s", zErr);
104264 sqlite3DbFree(db, zErr);
104267 return rc;
104270 ** Grow the db->aVTrans[] array so that there is room for at least one
104271 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
104273 static int growVTrans(sqlite3 *db){
104274 const int ARRAY_INCR = 5;
104276 /* Grow the sqlite3.aVTrans array if required */
104277 if( (db->nVTrans%ARRAY_INCR)==0 ){
104278 VTable **aVTrans;
104279 int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
104280 aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
104281 if( !aVTrans ){
104282 return SQLITE_NOMEM;
104284 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
104285 db->aVTrans = aVTrans;
104288 return SQLITE_OK;
104292 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
104293 ** have already been reserved using growVTrans().
104295 static void addToVTrans(sqlite3 *db, VTable *pVTab){
104296 /* Add pVtab to the end of sqlite3.aVTrans */
104297 db->aVTrans[db->nVTrans++] = pVTab;
104298 sqlite3VtabLock(pVTab);
104302 ** This function is invoked by the vdbe to call the xCreate method
104303 ** of the virtual table named zTab in database iDb.
104305 ** If an error occurs, *pzErr is set to point an an English language
104306 ** description of the error and an SQLITE_XXX error code is returned.
104307 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
104309 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
104310 int rc = SQLITE_OK;
104311 Table *pTab;
104312 Module *pMod;
104313 const char *zMod;
104315 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
104316 assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
104318 /* Locate the required virtual table module */
104319 zMod = pTab->azModuleArg[0];
104320 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
104322 /* If the module has been registered and includes a Create method,
104323 ** invoke it now. If the module has not been registered, return an
104324 ** error. Otherwise, do nothing.
104326 if( !pMod ){
104327 *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
104328 rc = SQLITE_ERROR;
104329 }else{
104330 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
104333 /* Justification of ALWAYS(): The xConstructor method is required to
104334 ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
104335 if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
104336 rc = growVTrans(db);
104337 if( rc==SQLITE_OK ){
104338 addToVTrans(db, sqlite3GetVTable(db, pTab));
104342 return rc;
104346 ** This function is used to set the schema of a virtual table. It is only
104347 ** valid to call this function from within the xCreate() or xConnect() of a
104348 ** virtual table module.
104350 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
104351 Parse *pParse;
104353 int rc = SQLITE_OK;
104354 Table *pTab;
104355 char *zErr = 0;
104357 sqlite3_mutex_enter(db->mutex);
104358 if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
104359 sqlite3Error(db, SQLITE_MISUSE, 0);
104360 sqlite3_mutex_leave(db->mutex);
104361 return SQLITE_MISUSE_BKPT;
104363 assert( (pTab->tabFlags & TF_Virtual)!=0 );
104365 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
104366 if( pParse==0 ){
104367 rc = SQLITE_NOMEM;
104368 }else{
104369 pParse->declareVtab = 1;
104370 pParse->db = db;
104371 pParse->nQueryLoop = 1;
104373 if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
104374 && pParse->pNewTable
104375 && !db->mallocFailed
104376 && !pParse->pNewTable->pSelect
104377 && (pParse->pNewTable->tabFlags & TF_Virtual)==0
104379 if( !pTab->aCol ){
104380 pTab->aCol = pParse->pNewTable->aCol;
104381 pTab->nCol = pParse->pNewTable->nCol;
104382 pParse->pNewTable->nCol = 0;
104383 pParse->pNewTable->aCol = 0;
104385 db->pVtabCtx->pTab = 0;
104386 }else{
104387 sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
104388 sqlite3DbFree(db, zErr);
104389 rc = SQLITE_ERROR;
104391 pParse->declareVtab = 0;
104393 if( pParse->pVdbe ){
104394 sqlite3VdbeFinalize(pParse->pVdbe);
104396 sqlite3DeleteTable(db, pParse->pNewTable);
104397 sqlite3StackFree(db, pParse);
104400 assert( (rc&0xff)==rc );
104401 rc = sqlite3ApiExit(db, rc);
104402 sqlite3_mutex_leave(db->mutex);
104403 return rc;
104407 ** This function is invoked by the vdbe to call the xDestroy method
104408 ** of the virtual table named zTab in database iDb. This occurs
104409 ** when a DROP TABLE is mentioned.
104411 ** This call is a no-op if zTab is not a virtual table.
104413 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
104414 int rc = SQLITE_OK;
104415 Table *pTab;
104417 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
104418 if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
104419 VTable *p = vtabDisconnectAll(db, pTab);
104421 assert( rc==SQLITE_OK );
104422 rc = p->pMod->pModule->xDestroy(p->pVtab);
104424 /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
104425 if( rc==SQLITE_OK ){
104426 assert( pTab->pVTable==p && p->pNext==0 );
104427 p->pVtab = 0;
104428 pTab->pVTable = 0;
104429 sqlite3VtabUnlock(p);
104433 return rc;
104437 ** This function invokes either the xRollback or xCommit method
104438 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
104439 ** called is identified by the second argument, "offset", which is
104440 ** the offset of the method to call in the sqlite3_module structure.
104442 ** The array is cleared after invoking the callbacks.
104444 static void callFinaliser(sqlite3 *db, int offset){
104445 int i;
104446 if( db->aVTrans ){
104447 for(i=0; i<db->nVTrans; i++){
104448 VTable *pVTab = db->aVTrans[i];
104449 sqlite3_vtab *p = pVTab->pVtab;
104450 if( p ){
104451 int (*x)(sqlite3_vtab *);
104452 x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
104453 if( x ) x(p);
104455 pVTab->iSavepoint = 0;
104456 sqlite3VtabUnlock(pVTab);
104458 sqlite3DbFree(db, db->aVTrans);
104459 db->nVTrans = 0;
104460 db->aVTrans = 0;
104465 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
104466 ** array. Return the error code for the first error that occurs, or
104467 ** SQLITE_OK if all xSync operations are successful.
104469 ** If an error message is available, leave it in p->zErrMsg.
104471 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
104472 int i;
104473 int rc = SQLITE_OK;
104474 VTable **aVTrans = db->aVTrans;
104476 db->aVTrans = 0;
104477 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
104478 int (*x)(sqlite3_vtab *);
104479 sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
104480 if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
104481 rc = x(pVtab);
104482 sqlite3VtabImportErrmsg(p, pVtab);
104485 db->aVTrans = aVTrans;
104486 return rc;
104490 ** Invoke the xRollback method of all virtual tables in the
104491 ** sqlite3.aVTrans array. Then clear the array itself.
104493 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
104494 callFinaliser(db, offsetof(sqlite3_module,xRollback));
104495 return SQLITE_OK;
104499 ** Invoke the xCommit method of all virtual tables in the
104500 ** sqlite3.aVTrans array. Then clear the array itself.
104502 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
104503 callFinaliser(db, offsetof(sqlite3_module,xCommit));
104504 return SQLITE_OK;
104508 ** If the virtual table pVtab supports the transaction interface
104509 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
104510 ** not currently open, invoke the xBegin method now.
104512 ** If the xBegin call is successful, place the sqlite3_vtab pointer
104513 ** in the sqlite3.aVTrans array.
104515 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
104516 int rc = SQLITE_OK;
104517 const sqlite3_module *pModule;
104519 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
104520 ** than zero, then this function is being called from within a
104521 ** virtual module xSync() callback. It is illegal to write to
104522 ** virtual module tables in this case, so return SQLITE_LOCKED.
104524 if( sqlite3VtabInSync(db) ){
104525 return SQLITE_LOCKED;
104527 if( !pVTab ){
104528 return SQLITE_OK;
104530 pModule = pVTab->pVtab->pModule;
104532 if( pModule->xBegin ){
104533 int i;
104535 /* If pVtab is already in the aVTrans array, return early */
104536 for(i=0; i<db->nVTrans; i++){
104537 if( db->aVTrans[i]==pVTab ){
104538 return SQLITE_OK;
104542 /* Invoke the xBegin method. If successful, add the vtab to the
104543 ** sqlite3.aVTrans[] array. */
104544 rc = growVTrans(db);
104545 if( rc==SQLITE_OK ){
104546 rc = pModule->xBegin(pVTab->pVtab);
104547 if( rc==SQLITE_OK ){
104548 addToVTrans(db, pVTab);
104552 return rc;
104556 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
104557 ** virtual tables that currently have an open transaction. Pass iSavepoint
104558 ** as the second argument to the virtual table method invoked.
104560 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
104561 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
104562 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
104563 ** an open transaction is invoked.
104565 ** If any virtual table method returns an error code other than SQLITE_OK,
104566 ** processing is abandoned and the error returned to the caller of this
104567 ** function immediately. If all calls to virtual table methods are successful,
104568 ** SQLITE_OK is returned.
104570 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
104571 int rc = SQLITE_OK;
104573 assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
104574 assert( iSavepoint>=0 );
104575 if( db->aVTrans ){
104576 int i;
104577 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
104578 VTable *pVTab = db->aVTrans[i];
104579 const sqlite3_module *pMod = pVTab->pMod->pModule;
104580 if( pVTab->pVtab && pMod->iVersion>=2 ){
104581 int (*xMethod)(sqlite3_vtab *, int);
104582 switch( op ){
104583 case SAVEPOINT_BEGIN:
104584 xMethod = pMod->xSavepoint;
104585 pVTab->iSavepoint = iSavepoint+1;
104586 break;
104587 case SAVEPOINT_ROLLBACK:
104588 xMethod = pMod->xRollbackTo;
104589 break;
104590 default:
104591 xMethod = pMod->xRelease;
104592 break;
104594 if( xMethod && pVTab->iSavepoint>iSavepoint ){
104595 rc = xMethod(pVTab->pVtab, iSavepoint);
104600 return rc;
104604 ** The first parameter (pDef) is a function implementation. The
104605 ** second parameter (pExpr) is the first argument to this function.
104606 ** If pExpr is a column in a virtual table, then let the virtual
104607 ** table implementation have an opportunity to overload the function.
104609 ** This routine is used to allow virtual table implementations to
104610 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
104612 ** Return either the pDef argument (indicating no change) or a
104613 ** new FuncDef structure that is marked as ephemeral using the
104614 ** SQLITE_FUNC_EPHEM flag.
104616 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
104617 sqlite3 *db, /* Database connection for reporting malloc problems */
104618 FuncDef *pDef, /* Function to possibly overload */
104619 int nArg, /* Number of arguments to the function */
104620 Expr *pExpr /* First argument to the function */
104622 Table *pTab;
104623 sqlite3_vtab *pVtab;
104624 sqlite3_module *pMod;
104625 void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
104626 void *pArg = 0;
104627 FuncDef *pNew;
104628 int rc = 0;
104629 char *zLowerName;
104630 unsigned char *z;
104633 /* Check to see the left operand is a column in a virtual table */
104634 if( NEVER(pExpr==0) ) return pDef;
104635 if( pExpr->op!=TK_COLUMN ) return pDef;
104636 pTab = pExpr->pTab;
104637 if( NEVER(pTab==0) ) return pDef;
104638 if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
104639 pVtab = sqlite3GetVTable(db, pTab)->pVtab;
104640 assert( pVtab!=0 );
104641 assert( pVtab->pModule!=0 );
104642 pMod = (sqlite3_module *)pVtab->pModule;
104643 if( pMod->xFindFunction==0 ) return pDef;
104645 /* Call the xFindFunction method on the virtual table implementation
104646 ** to see if the implementation wants to overload this function
104648 zLowerName = sqlite3DbStrDup(db, pDef->zName);
104649 if( zLowerName ){
104650 for(z=(unsigned char*)zLowerName; *z; z++){
104651 *z = sqlite3UpperToLower[*z];
104653 rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
104654 sqlite3DbFree(db, zLowerName);
104656 if( rc==0 ){
104657 return pDef;
104660 /* Create a new ephemeral function definition for the overloaded
104661 ** function */
104662 pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
104663 + sqlite3Strlen30(pDef->zName) + 1);
104664 if( pNew==0 ){
104665 return pDef;
104667 *pNew = *pDef;
104668 pNew->zName = (char *)&pNew[1];
104669 memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
104670 pNew->xFunc = xFunc;
104671 pNew->pUserData = pArg;
104672 pNew->flags |= SQLITE_FUNC_EPHEM;
104673 return pNew;
104677 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
104678 ** array so that an OP_VBegin will get generated for it. Add pTab to the
104679 ** array if it is missing. If pTab is already in the array, this routine
104680 ** is a no-op.
104682 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
104683 Parse *pToplevel = sqlite3ParseToplevel(pParse);
104684 int i, n;
104685 Table **apVtabLock;
104687 assert( IsVirtual(pTab) );
104688 for(i=0; i<pToplevel->nVtabLock; i++){
104689 if( pTab==pToplevel->apVtabLock[i] ) return;
104691 n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
104692 apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
104693 if( apVtabLock ){
104694 pToplevel->apVtabLock = apVtabLock;
104695 pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
104696 }else{
104697 pToplevel->db->mallocFailed = 1;
104702 ** Return the ON CONFLICT resolution mode in effect for the virtual
104703 ** table update operation currently in progress.
104705 ** The results of this routine are undefined unless it is called from
104706 ** within an xUpdate method.
104708 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
104709 static const unsigned char aMap[] = {
104710 SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
104712 assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
104713 assert( OE_Ignore==4 && OE_Replace==5 );
104714 assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
104715 return (int)aMap[db->vtabOnConflict-1];
104719 ** Call from within the xCreate() or xConnect() methods to provide
104720 ** the SQLite core with additional information about the behavior
104721 ** of the virtual table being implemented.
104723 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
104724 va_list ap;
104725 int rc = SQLITE_OK;
104727 sqlite3_mutex_enter(db->mutex);
104729 va_start(ap, op);
104730 switch( op ){
104731 case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
104732 VtabCtx *p = db->pVtabCtx;
104733 if( !p ){
104734 rc = SQLITE_MISUSE_BKPT;
104735 }else{
104736 assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
104737 p->pVTable->bConstraint = (u8)va_arg(ap, int);
104739 break;
104741 default:
104742 rc = SQLITE_MISUSE_BKPT;
104743 break;
104745 va_end(ap);
104747 if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
104748 sqlite3_mutex_leave(db->mutex);
104749 return rc;
104752 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104754 /************** End of vtab.c ************************************************/
104755 /************** Begin file where.c *******************************************/
104757 ** 2001 September 15
104759 ** The author disclaims copyright to this source code. In place of
104760 ** a legal notice, here is a blessing:
104762 ** May you do good and not evil.
104763 ** May you find forgiveness for yourself and forgive others.
104764 ** May you share freely, never taking more than you give.
104766 *************************************************************************
104767 ** This module contains C code that generates VDBE code used to process
104768 ** the WHERE clause of SQL statements. This module is responsible for
104769 ** generating the code that loops through a table looking for applicable
104770 ** rows. Indices are selected and used to speed the search when doing
104771 ** so is applicable. Because this module is responsible for selecting
104772 ** indices, you might also think of this module as the "query optimizer".
104777 ** Trace output macros
104779 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
104780 /***/ int sqlite3WhereTrace = 0;
104781 #endif
104782 #if defined(SQLITE_DEBUG) \
104783 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
104784 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
104785 # define WHERETRACE_ENABLED 1
104786 #else
104787 # define WHERETRACE(K,X)
104788 #endif
104790 /* Forward references
104792 typedef struct WhereClause WhereClause;
104793 typedef struct WhereMaskSet WhereMaskSet;
104794 typedef struct WhereOrInfo WhereOrInfo;
104795 typedef struct WhereAndInfo WhereAndInfo;
104796 typedef struct WhereLevel WhereLevel;
104797 typedef struct WhereLoop WhereLoop;
104798 typedef struct WherePath WherePath;
104799 typedef struct WhereTerm WhereTerm;
104800 typedef struct WhereLoopBuilder WhereLoopBuilder;
104801 typedef struct WhereScan WhereScan;
104802 typedef struct WhereOrCost WhereOrCost;
104803 typedef struct WhereOrSet WhereOrSet;
104806 ** Cost X is tracked as 10*log2(X) stored in a 16-bit integer. The
104807 ** maximum cost for ordinary tables is 64*(2**63) which becomes 6900.
104808 ** (Virtual tables can return a larger cost, but let's assume they do not.)
104809 ** So all costs can be stored in a 16-bit unsigned integer without risk
104810 ** of overflow.
104812 ** Costs are estimates, so no effort is made to compute 10*log2(X) exactly.
104813 ** Instead, a close estimate is used. Any value of X<=1 is stored as 0.
104814 ** X=2 is 10. X=3 is 16. X=1000 is 99. etc.
104816 ** The tool/wherecosttest.c source file implements a command-line program
104817 ** that will convert WhereCosts to integers, convert integers to WhereCosts
104818 ** and do addition and multiplication on WhereCost values. The wherecosttest
104819 ** command-line program is a useful utility to have around when working with
104820 ** this module.
104822 typedef unsigned short int WhereCost;
104825 ** This object contains information needed to implement a single nested
104826 ** loop in WHERE clause.
104828 ** Contrast this object with WhereLoop. This object describes the
104829 ** implementation of the loop. WhereLoop describes the algorithm.
104830 ** This object contains a pointer to the WhereLoop algorithm as one of
104831 ** its elements.
104833 ** The WhereInfo object contains a single instance of this object for
104834 ** each term in the FROM clause (which is to say, for each of the
104835 ** nested loops as implemented). The order of WhereLevel objects determines
104836 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
104837 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
104839 struct WhereLevel {
104840 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
104841 int iTabCur; /* The VDBE cursor used to access the table */
104842 int iIdxCur; /* The VDBE cursor used to access pIdx */
104843 int addrBrk; /* Jump here to break out of the loop */
104844 int addrNxt; /* Jump here to start the next IN combination */
104845 int addrCont; /* Jump here to continue with the next loop cycle */
104846 int addrFirst; /* First instruction of interior of the loop */
104847 int addrBody; /* Beginning of the body of this loop */
104848 u8 iFrom; /* Which entry in the FROM clause */
104849 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
104850 int p1, p2; /* Operands of the opcode used to ends the loop */
104851 union { /* Information that depends on pWLoop->wsFlags */
104852 struct {
104853 int nIn; /* Number of entries in aInLoop[] */
104854 struct InLoop {
104855 int iCur; /* The VDBE cursor used by this IN operator */
104856 int addrInTop; /* Top of the IN loop */
104857 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
104858 } *aInLoop; /* Information about each nested IN operator */
104859 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
104860 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
104862 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
104866 ** Each instance of this object represents an algorithm for evaluating one
104867 ** term of a join. Every term of the FROM clause will have at least
104868 ** one corresponding WhereLoop object (unless INDEXED BY constraints
104869 ** prevent a query solution - which is an error) and many terms of the
104870 ** FROM clause will have multiple WhereLoop objects, each describing a
104871 ** potential way of implementing that FROM-clause term, together with
104872 ** dependencies and cost estimates for using the chosen algorithm.
104874 ** Query planning consists of building up a collection of these WhereLoop
104875 ** objects, then computing a particular sequence of WhereLoop objects, with
104876 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
104877 ** and that minimize the overall cost.
104879 struct WhereLoop {
104880 Bitmask prereq; /* Bitmask of other loops that must run first */
104881 Bitmask maskSelf; /* Bitmask identifying table iTab */
104882 #ifdef SQLITE_DEBUG
104883 char cId; /* Symbolic ID of this loop for debugging use */
104884 #endif
104885 u8 iTab; /* Position in FROM clause of table for this loop */
104886 u8 iSortIdx; /* Sorting index number. 0==None */
104887 WhereCost rSetup; /* One-time setup cost (ex: create transient index) */
104888 WhereCost rRun; /* Cost of running each loop */
104889 WhereCost nOut; /* Estimated number of output rows */
104890 union {
104891 struct { /* Information for internal btree tables */
104892 int nEq; /* Number of equality constraints */
104893 Index *pIndex; /* Index used, or NULL */
104894 } btree;
104895 struct { /* Information for virtual tables */
104896 int idxNum; /* Index number */
104897 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
104898 u8 isOrdered; /* True if satisfies ORDER BY */
104899 u16 omitMask; /* Terms that may be omitted */
104900 char *idxStr; /* Index identifier string */
104901 } vtab;
104903 u32 wsFlags; /* WHERE_* flags describing the plan */
104904 u16 nLTerm; /* Number of entries in aLTerm[] */
104905 /**** whereLoopXfer() copies fields above ***********************/
104906 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
104907 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
104908 WhereTerm **aLTerm; /* WhereTerms used */
104909 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
104910 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
104913 /* This object holds the prerequisites and the cost of running a
104914 ** subquery on one operand of an OR operator in the WHERE clause.
104915 ** See WhereOrSet for additional information
104917 struct WhereOrCost {
104918 Bitmask prereq; /* Prerequisites */
104919 WhereCost rRun; /* Cost of running this subquery */
104920 WhereCost nOut; /* Number of outputs for this subquery */
104923 /* The WhereOrSet object holds a set of possible WhereOrCosts that
104924 ** correspond to the subquery(s) of OR-clause processing. Only the
104925 ** best N_OR_COST elements are retained.
104927 #define N_OR_COST 3
104928 struct WhereOrSet {
104929 u16 n; /* Number of valid a[] entries */
104930 WhereOrCost a[N_OR_COST]; /* Set of best costs */
104934 /* Forward declaration of methods */
104935 static int whereLoopResize(sqlite3*, WhereLoop*, int);
104938 ** Each instance of this object holds a sequence of WhereLoop objects
104939 ** that implement some or all of a query plan.
104941 ** Think of each WhereLoop object as a node in a graph with arcs
104942 ** showing dependences and costs for travelling between nodes. (That is
104943 ** not a completely accurate description because WhereLoop costs are a
104944 ** vector, not a scalar, and because dependences are many-to-one, not
104945 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
104946 ** Then a WherePath object is a path through the graph that visits some
104947 ** or all of the WhereLoop objects once.
104949 ** The "solver" works by creating the N best WherePath objects of length
104950 ** 1. Then using those as a basis to compute the N best WherePath objects
104951 ** of length 2. And so forth until the length of WherePaths equals the
104952 ** number of nodes in the FROM clause. The best (lowest cost) WherePath
104953 ** at the end is the choosen query plan.
104955 struct WherePath {
104956 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
104957 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
104958 WhereCost nRow; /* Estimated number of rows generated by this path */
104959 WhereCost rCost; /* Total cost of this path */
104960 u8 isOrdered; /* True if this path satisfies ORDER BY */
104961 u8 isOrderedValid; /* True if the isOrdered field is valid */
104962 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
104966 ** The query generator uses an array of instances of this structure to
104967 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
104968 ** clause subexpression is separated from the others by AND operators,
104969 ** usually, or sometimes subexpressions separated by OR.
104971 ** All WhereTerms are collected into a single WhereClause structure.
104972 ** The following identity holds:
104974 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
104976 ** When a term is of the form:
104978 ** X <op> <expr>
104980 ** where X is a column name and <op> is one of certain operators,
104981 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
104982 ** cursor number and column number for X. WhereTerm.eOperator records
104983 ** the <op> using a bitmask encoding defined by WO_xxx below. The
104984 ** use of a bitmask encoding for the operator allows us to search
104985 ** quickly for terms that match any of several different operators.
104987 ** A WhereTerm might also be two or more subterms connected by OR:
104989 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
104991 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
104992 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
104993 ** is collected about the OR clause.
104995 ** If a term in the WHERE clause does not match either of the two previous
104996 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
104997 ** to the original subexpression content and wtFlags is set up appropriately
104998 ** but no other fields in the WhereTerm object are meaningful.
105000 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
105001 ** but they do so indirectly. A single WhereMaskSet structure translates
105002 ** cursor number into bits and the translated bit is stored in the prereq
105003 ** fields. The translation is used in order to maximize the number of
105004 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
105005 ** spread out over the non-negative integers. For example, the cursor
105006 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
105007 ** translates these sparse cursor numbers into consecutive integers
105008 ** beginning with 0 in order to make the best possible use of the available
105009 ** bits in the Bitmask. So, in the example above, the cursor numbers
105010 ** would be mapped into integers 0 through 7.
105012 ** The number of terms in a join is limited by the number of bits
105013 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
105014 ** is only able to process joins with 64 or fewer tables.
105016 struct WhereTerm {
105017 Expr *pExpr; /* Pointer to the subexpression that is this term */
105018 int iParent; /* Disable pWC->a[iParent] when this term disabled */
105019 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
105020 union {
105021 int leftColumn; /* Column number of X in "X <op> <expr>" */
105022 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
105023 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
105025 u16 eOperator; /* A WO_xx value describing <op> */
105026 u8 wtFlags; /* TERM_xxx bit flags. See below */
105027 u8 nChild; /* Number of children that must disable us */
105028 WhereClause *pWC; /* The clause this term is part of */
105029 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
105030 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
105034 ** Allowed values of WhereTerm.wtFlags
105036 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
105037 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
105038 #define TERM_CODED 0x04 /* This term is already coded */
105039 #define TERM_COPIED 0x08 /* Has a child */
105040 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
105041 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
105042 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
105043 #ifdef SQLITE_ENABLE_STAT3
105044 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
105045 #else
105046 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
105047 #endif
105050 ** An instance of the WhereScan object is used as an iterator for locating
105051 ** terms in the WHERE clause that are useful to the query planner.
105053 struct WhereScan {
105054 WhereClause *pOrigWC; /* Original, innermost WhereClause */
105055 WhereClause *pWC; /* WhereClause currently being scanned */
105056 char *zCollName; /* Required collating sequence, if not NULL */
105057 char idxaff; /* Must match this affinity, if zCollName!=NULL */
105058 unsigned char nEquiv; /* Number of entries in aEquiv[] */
105059 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
105060 u32 opMask; /* Acceptable operators */
105061 int k; /* Resume scanning at this->pWC->a[this->k] */
105062 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
105066 ** An instance of the following structure holds all information about a
105067 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
105069 ** Explanation of pOuter: For a WHERE clause of the form
105071 ** a AND ((b AND c) OR (d AND e)) AND f
105073 ** There are separate WhereClause objects for the whole clause and for
105074 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
105075 ** subclauses points to the WhereClause object for the whole clause.
105077 struct WhereClause {
105078 WhereInfo *pWInfo; /* WHERE clause processing context */
105079 WhereClause *pOuter; /* Outer conjunction */
105080 u8 op; /* Split operator. TK_AND or TK_OR */
105081 int nTerm; /* Number of terms */
105082 int nSlot; /* Number of entries in a[] */
105083 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
105084 #if defined(SQLITE_SMALL_STACK)
105085 WhereTerm aStatic[1]; /* Initial static space for a[] */
105086 #else
105087 WhereTerm aStatic[8]; /* Initial static space for a[] */
105088 #endif
105092 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
105093 ** a dynamically allocated instance of the following structure.
105095 struct WhereOrInfo {
105096 WhereClause wc; /* Decomposition into subterms */
105097 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
105101 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
105102 ** a dynamically allocated instance of the following structure.
105104 struct WhereAndInfo {
105105 WhereClause wc; /* The subexpression broken out */
105109 ** An instance of the following structure keeps track of a mapping
105110 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
105112 ** The VDBE cursor numbers are small integers contained in
105113 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
105114 ** clause, the cursor numbers might not begin with 0 and they might
105115 ** contain gaps in the numbering sequence. But we want to make maximum
105116 ** use of the bits in our bitmasks. This structure provides a mapping
105117 ** from the sparse cursor numbers into consecutive integers beginning
105118 ** with 0.
105120 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
105121 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
105123 ** For example, if the WHERE clause expression used these VDBE
105124 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
105125 ** would map those cursor numbers into bits 0 through 5.
105127 ** Note that the mapping is not necessarily ordered. In the example
105128 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
105129 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
105130 ** does not really matter. What is important is that sparse cursor
105131 ** numbers all get mapped into bit numbers that begin with 0 and contain
105132 ** no gaps.
105134 struct WhereMaskSet {
105135 int n; /* Number of assigned cursor values */
105136 int ix[BMS]; /* Cursor assigned to each bit */
105140 ** This object is a convenience wrapper holding all information needed
105141 ** to construct WhereLoop objects for a particular query.
105143 struct WhereLoopBuilder {
105144 WhereInfo *pWInfo; /* Information about this WHERE */
105145 WhereClause *pWC; /* WHERE clause terms */
105146 ExprList *pOrderBy; /* ORDER BY clause */
105147 WhereLoop *pNew; /* Template WhereLoop */
105148 WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
105152 ** The WHERE clause processing routine has two halves. The
105153 ** first part does the start of the WHERE loop and the second
105154 ** half does the tail of the WHERE loop. An instance of
105155 ** this structure is returned by the first half and passed
105156 ** into the second half to give some continuity.
105158 ** An instance of this object holds the complete state of the query
105159 ** planner.
105161 struct WhereInfo {
105162 Parse *pParse; /* Parsing and code generating context */
105163 SrcList *pTabList; /* List of tables in the join */
105164 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
105165 ExprList *pResultSet; /* Result set. DISTINCT operates on these */
105166 WhereLoop *pLoops; /* List of all WhereLoop objects */
105167 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
105168 WhereCost nRowOut; /* Estimated number of output rows */
105169 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
105170 u8 bOBSat; /* ORDER BY satisfied by indices */
105171 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
105172 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
105173 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
105174 u8 nLevel; /* Number of nested loop */
105175 int iTop; /* The very beginning of the WHERE loop */
105176 int iContinue; /* Jump here to continue with next record */
105177 int iBreak; /* Jump here to break out of the loop */
105178 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
105179 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
105180 WhereClause sWC; /* Decomposition of the WHERE clause */
105181 WhereLevel a[1]; /* Information about each nest loop in WHERE */
105185 ** Bitmasks for the operators on WhereTerm objects. These are all
105186 ** operators that are of interest to the query planner. An
105187 ** OR-ed combination of these values can be used when searching for
105188 ** particular WhereTerms within a WhereClause.
105190 #define WO_IN 0x001
105191 #define WO_EQ 0x002
105192 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
105193 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
105194 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
105195 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
105196 #define WO_MATCH 0x040
105197 #define WO_ISNULL 0x080
105198 #define WO_OR 0x100 /* Two or more OR-connected terms */
105199 #define WO_AND 0x200 /* Two or more AND-connected terms */
105200 #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
105201 #define WO_NOOP 0x800 /* This term does not restrict search space */
105203 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
105204 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
105207 ** These are definitions of bits in the WhereLoop.wsFlags field.
105208 ** The particular combination of bits in each WhereLoop help to
105209 ** determine the algorithm that WhereLoop represents.
105211 #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
105212 #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
105213 #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
105214 #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
105215 #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
105216 #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
105217 #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
105218 #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
105219 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
105220 #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
105221 #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
105222 #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
105223 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
105224 #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
105225 #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
105226 #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
105229 /* Convert a WhereCost value (10 times log2(X)) into its integer value X.
105230 ** A rough approximation is used. The value returned is not exact.
105232 static u64 whereCostToInt(WhereCost x){
105233 u64 n;
105234 if( x<10 ) return 1;
105235 n = x%10;
105236 x /= 10;
105237 if( n>=5 ) n -= 2;
105238 else if( n>=1 ) n -= 1;
105239 if( x>=3 ) return (n+8)<<(x-3);
105240 return (n+8)>>(3-x);
105244 ** Return the estimated number of output rows from a WHERE clause
105246 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
105247 return whereCostToInt(pWInfo->nRowOut);
105251 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
105252 ** WHERE clause returns outputs for DISTINCT processing.
105254 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
105255 return pWInfo->eDistinct;
105259 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
105260 ** Return FALSE if the output needs to be sorted.
105262 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
105263 return pWInfo->bOBSat!=0;
105267 ** Return the VDBE address or label to jump to in order to continue
105268 ** immediately with the next row of a WHERE clause.
105270 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
105271 return pWInfo->iContinue;
105275 ** Return the VDBE address or label to jump to in order to break
105276 ** out of a WHERE loop.
105278 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
105279 return pWInfo->iBreak;
105283 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
105284 ** the rowids returned by a WHERE clause. Return FALSE if doing an
105285 ** UPDATE or DELETE might change subsequent WHERE clause results.
105287 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
105288 return pWInfo->okOnePass;
105292 ** Move the content of pSrc into pDest
105294 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
105295 pDest->n = pSrc->n;
105296 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
105300 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
105302 ** The new entry might overwrite an existing entry, or it might be
105303 ** appended, or it might be discarded. Do whatever is the right thing
105304 ** so that pSet keeps the N_OR_COST best entries seen so far.
105306 static int whereOrInsert(
105307 WhereOrSet *pSet, /* The WhereOrSet to be updated */
105308 Bitmask prereq, /* Prerequisites of the new entry */
105309 WhereCost rRun, /* Run-cost of the new entry */
105310 WhereCost nOut /* Number of outputs for the new entry */
105312 u16 i;
105313 WhereOrCost *p;
105314 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
105315 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
105316 goto whereOrInsert_done;
105318 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
105319 return 0;
105322 if( pSet->n<N_OR_COST ){
105323 p = &pSet->a[pSet->n++];
105324 p->nOut = nOut;
105325 }else{
105326 p = pSet->a;
105327 for(i=1; i<pSet->n; i++){
105328 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
105330 if( p->rRun<=rRun ) return 0;
105332 whereOrInsert_done:
105333 p->prereq = prereq;
105334 p->rRun = rRun;
105335 if( p->nOut>nOut ) p->nOut = nOut;
105336 return 1;
105340 ** Initialize a preallocated WhereClause structure.
105342 static void whereClauseInit(
105343 WhereClause *pWC, /* The WhereClause to be initialized */
105344 WhereInfo *pWInfo /* The WHERE processing context */
105346 pWC->pWInfo = pWInfo;
105347 pWC->pOuter = 0;
105348 pWC->nTerm = 0;
105349 pWC->nSlot = ArraySize(pWC->aStatic);
105350 pWC->a = pWC->aStatic;
105353 /* Forward reference */
105354 static void whereClauseClear(WhereClause*);
105357 ** Deallocate all memory associated with a WhereOrInfo object.
105359 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
105360 whereClauseClear(&p->wc);
105361 sqlite3DbFree(db, p);
105365 ** Deallocate all memory associated with a WhereAndInfo object.
105367 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
105368 whereClauseClear(&p->wc);
105369 sqlite3DbFree(db, p);
105373 ** Deallocate a WhereClause structure. The WhereClause structure
105374 ** itself is not freed. This routine is the inverse of whereClauseInit().
105376 static void whereClauseClear(WhereClause *pWC){
105377 int i;
105378 WhereTerm *a;
105379 sqlite3 *db = pWC->pWInfo->pParse->db;
105380 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
105381 if( a->wtFlags & TERM_DYNAMIC ){
105382 sqlite3ExprDelete(db, a->pExpr);
105384 if( a->wtFlags & TERM_ORINFO ){
105385 whereOrInfoDelete(db, a->u.pOrInfo);
105386 }else if( a->wtFlags & TERM_ANDINFO ){
105387 whereAndInfoDelete(db, a->u.pAndInfo);
105390 if( pWC->a!=pWC->aStatic ){
105391 sqlite3DbFree(db, pWC->a);
105396 ** Add a single new WhereTerm entry to the WhereClause object pWC.
105397 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
105398 ** The index in pWC->a[] of the new WhereTerm is returned on success.
105399 ** 0 is returned if the new WhereTerm could not be added due to a memory
105400 ** allocation error. The memory allocation failure will be recorded in
105401 ** the db->mallocFailed flag so that higher-level functions can detect it.
105403 ** This routine will increase the size of the pWC->a[] array as necessary.
105405 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
105406 ** for freeing the expression p is assumed by the WhereClause object pWC.
105407 ** This is true even if this routine fails to allocate a new WhereTerm.
105409 ** WARNING: This routine might reallocate the space used to store
105410 ** WhereTerms. All pointers to WhereTerms should be invalidated after
105411 ** calling this routine. Such pointers may be reinitialized by referencing
105412 ** the pWC->a[] array.
105414 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
105415 WhereTerm *pTerm;
105416 int idx;
105417 testcase( wtFlags & TERM_VIRTUAL );
105418 if( pWC->nTerm>=pWC->nSlot ){
105419 WhereTerm *pOld = pWC->a;
105420 sqlite3 *db = pWC->pWInfo->pParse->db;
105421 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
105422 if( pWC->a==0 ){
105423 if( wtFlags & TERM_DYNAMIC ){
105424 sqlite3ExprDelete(db, p);
105426 pWC->a = pOld;
105427 return 0;
105429 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
105430 if( pOld!=pWC->aStatic ){
105431 sqlite3DbFree(db, pOld);
105433 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
105435 pTerm = &pWC->a[idx = pWC->nTerm++];
105436 pTerm->pExpr = sqlite3ExprSkipCollate(p);
105437 pTerm->wtFlags = wtFlags;
105438 pTerm->pWC = pWC;
105439 pTerm->iParent = -1;
105440 return idx;
105444 ** This routine identifies subexpressions in the WHERE clause where
105445 ** each subexpression is separated by the AND operator or some other
105446 ** operator specified in the op parameter. The WhereClause structure
105447 ** is filled with pointers to subexpressions. For example:
105449 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
105450 ** \________/ \_______________/ \________________/
105451 ** slot[0] slot[1] slot[2]
105453 ** The original WHERE clause in pExpr is unaltered. All this routine
105454 ** does is make slot[] entries point to substructure within pExpr.
105456 ** In the previous sentence and in the diagram, "slot[]" refers to
105457 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
105458 ** all terms of the WHERE clause.
105460 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
105461 pWC->op = op;
105462 if( pExpr==0 ) return;
105463 if( pExpr->op!=op ){
105464 whereClauseInsert(pWC, pExpr, 0);
105465 }else{
105466 whereSplit(pWC, pExpr->pLeft, op);
105467 whereSplit(pWC, pExpr->pRight, op);
105472 ** Initialize a WhereMaskSet object
105474 #define initMaskSet(P) (P)->n=0
105477 ** Return the bitmask for the given cursor number. Return 0 if
105478 ** iCursor is not in the set.
105480 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
105481 int i;
105482 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
105483 for(i=0; i<pMaskSet->n; i++){
105484 if( pMaskSet->ix[i]==iCursor ){
105485 return MASKBIT(i);
105488 return 0;
105492 ** Create a new mask for cursor iCursor.
105494 ** There is one cursor per table in the FROM clause. The number of
105495 ** tables in the FROM clause is limited by a test early in the
105496 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
105497 ** array will never overflow.
105499 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
105500 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
105501 pMaskSet->ix[pMaskSet->n++] = iCursor;
105505 ** These routines walk (recursively) an expression tree and generate
105506 ** a bitmask indicating which tables are used in that expression
105507 ** tree.
105509 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
105510 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
105511 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
105512 Bitmask mask = 0;
105513 if( p==0 ) return 0;
105514 if( p->op==TK_COLUMN ){
105515 mask = getMask(pMaskSet, p->iTable);
105516 return mask;
105518 mask = exprTableUsage(pMaskSet, p->pRight);
105519 mask |= exprTableUsage(pMaskSet, p->pLeft);
105520 if( ExprHasProperty(p, EP_xIsSelect) ){
105521 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
105522 }else{
105523 mask |= exprListTableUsage(pMaskSet, p->x.pList);
105525 return mask;
105527 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
105528 int i;
105529 Bitmask mask = 0;
105530 if( pList ){
105531 for(i=0; i<pList->nExpr; i++){
105532 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
105535 return mask;
105537 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
105538 Bitmask mask = 0;
105539 while( pS ){
105540 SrcList *pSrc = pS->pSrc;
105541 mask |= exprListTableUsage(pMaskSet, pS->pEList);
105542 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
105543 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
105544 mask |= exprTableUsage(pMaskSet, pS->pWhere);
105545 mask |= exprTableUsage(pMaskSet, pS->pHaving);
105546 if( ALWAYS(pSrc!=0) ){
105547 int i;
105548 for(i=0; i<pSrc->nSrc; i++){
105549 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
105550 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
105553 pS = pS->pPrior;
105555 return mask;
105559 ** Return TRUE if the given operator is one of the operators that is
105560 ** allowed for an indexable WHERE clause term. The allowed operators are
105561 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
105563 static int allowedOp(int op){
105564 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
105565 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
105566 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
105567 assert( TK_GE==TK_EQ+4 );
105568 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
105572 ** Swap two objects of type TYPE.
105574 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
105577 ** Commute a comparison operator. Expressions of the form "X op Y"
105578 ** are converted into "Y op X".
105580 ** If left/right precedence rules come into play when determining the
105581 ** collating sequence, then COLLATE operators are adjusted to ensure
105582 ** that the collating sequence does not change. For example:
105583 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
105584 ** the left hand side of a comparison overrides any collation sequence
105585 ** attached to the right. For the same reason the EP_Collate flag
105586 ** is not commuted.
105588 static void exprCommute(Parse *pParse, Expr *pExpr){
105589 u16 expRight = (pExpr->pRight->flags & EP_Collate);
105590 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
105591 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
105592 if( expRight==expLeft ){
105593 /* Either X and Y both have COLLATE operator or neither do */
105594 if( expRight ){
105595 /* Both X and Y have COLLATE operators. Make sure X is always
105596 ** used by clearing the EP_Collate flag from Y. */
105597 pExpr->pRight->flags &= ~EP_Collate;
105598 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
105599 /* Neither X nor Y have COLLATE operators, but X has a non-default
105600 ** collating sequence. So add the EP_Collate marker on X to cause
105601 ** it to be searched first. */
105602 pExpr->pLeft->flags |= EP_Collate;
105605 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
105606 if( pExpr->op>=TK_GT ){
105607 assert( TK_LT==TK_GT+2 );
105608 assert( TK_GE==TK_LE+2 );
105609 assert( TK_GT>TK_EQ );
105610 assert( TK_GT<TK_LE );
105611 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
105612 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
105617 ** Translate from TK_xx operator to WO_xx bitmask.
105619 static u16 operatorMask(int op){
105620 u16 c;
105621 assert( allowedOp(op) );
105622 if( op==TK_IN ){
105623 c = WO_IN;
105624 }else if( op==TK_ISNULL ){
105625 c = WO_ISNULL;
105626 }else{
105627 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
105628 c = (u16)(WO_EQ<<(op-TK_EQ));
105630 assert( op!=TK_ISNULL || c==WO_ISNULL );
105631 assert( op!=TK_IN || c==WO_IN );
105632 assert( op!=TK_EQ || c==WO_EQ );
105633 assert( op!=TK_LT || c==WO_LT );
105634 assert( op!=TK_LE || c==WO_LE );
105635 assert( op!=TK_GT || c==WO_GT );
105636 assert( op!=TK_GE || c==WO_GE );
105637 return c;
105641 ** Advance to the next WhereTerm that matches according to the criteria
105642 ** established when the pScan object was initialized by whereScanInit().
105643 ** Return NULL if there are no more matching WhereTerms.
105645 static WhereTerm *whereScanNext(WhereScan *pScan){
105646 int iCur; /* The cursor on the LHS of the term */
105647 int iColumn; /* The column on the LHS of the term. -1 for IPK */
105648 Expr *pX; /* An expression being tested */
105649 WhereClause *pWC; /* Shorthand for pScan->pWC */
105650 WhereTerm *pTerm; /* The term being tested */
105651 int k = pScan->k; /* Where to start scanning */
105653 while( pScan->iEquiv<=pScan->nEquiv ){
105654 iCur = pScan->aEquiv[pScan->iEquiv-2];
105655 iColumn = pScan->aEquiv[pScan->iEquiv-1];
105656 while( (pWC = pScan->pWC)!=0 ){
105657 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
105658 if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
105659 if( (pTerm->eOperator & WO_EQUIV)!=0
105660 && pScan->nEquiv<ArraySize(pScan->aEquiv)
105662 int j;
105663 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
105664 assert( pX->op==TK_COLUMN );
105665 for(j=0; j<pScan->nEquiv; j+=2){
105666 if( pScan->aEquiv[j]==pX->iTable
105667 && pScan->aEquiv[j+1]==pX->iColumn ){
105668 break;
105671 if( j==pScan->nEquiv ){
105672 pScan->aEquiv[j] = pX->iTable;
105673 pScan->aEquiv[j+1] = pX->iColumn;
105674 pScan->nEquiv += 2;
105677 if( (pTerm->eOperator & pScan->opMask)!=0 ){
105678 /* Verify the affinity and collating sequence match */
105679 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
105680 CollSeq *pColl;
105681 Parse *pParse = pWC->pWInfo->pParse;
105682 pX = pTerm->pExpr;
105683 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
105684 continue;
105686 assert(pX->pLeft);
105687 pColl = sqlite3BinaryCompareCollSeq(pParse,
105688 pX->pLeft, pX->pRight);
105689 if( pColl==0 ) pColl = pParse->db->pDfltColl;
105690 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
105691 continue;
105694 if( (pTerm->eOperator & WO_EQ)!=0
105695 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
105696 && pX->iTable==pScan->aEquiv[0]
105697 && pX->iColumn==pScan->aEquiv[1]
105699 continue;
105701 pScan->k = k+1;
105702 return pTerm;
105706 pScan->pWC = pScan->pWC->pOuter;
105707 k = 0;
105709 pScan->pWC = pScan->pOrigWC;
105710 k = 0;
105711 pScan->iEquiv += 2;
105713 return 0;
105717 ** Initialize a WHERE clause scanner object. Return a pointer to the
105718 ** first match. Return NULL if there are no matches.
105720 ** The scanner will be searching the WHERE clause pWC. It will look
105721 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
105722 ** iCur. The <op> must be one of the operators described by opMask.
105724 ** If the search is for X and the WHERE clause contains terms of the
105725 ** form X=Y then this routine might also return terms of the form
105726 ** "Y <op> <expr>". The number of levels of transitivity is limited,
105727 ** but is enough to handle most commonly occurring SQL statements.
105729 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
105730 ** index pIdx.
105732 static WhereTerm *whereScanInit(
105733 WhereScan *pScan, /* The WhereScan object being initialized */
105734 WhereClause *pWC, /* The WHERE clause to be scanned */
105735 int iCur, /* Cursor to scan for */
105736 int iColumn, /* Column to scan for */
105737 u32 opMask, /* Operator(s) to scan for */
105738 Index *pIdx /* Must be compatible with this index */
105740 int j;
105742 /* memset(pScan, 0, sizeof(*pScan)); */
105743 pScan->pOrigWC = pWC;
105744 pScan->pWC = pWC;
105745 if( pIdx && iColumn>=0 ){
105746 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
105747 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
105748 if( NEVER(j>=pIdx->nColumn) ) return 0;
105750 pScan->zCollName = pIdx->azColl[j];
105751 }else{
105752 pScan->idxaff = 0;
105753 pScan->zCollName = 0;
105755 pScan->opMask = opMask;
105756 pScan->k = 0;
105757 pScan->aEquiv[0] = iCur;
105758 pScan->aEquiv[1] = iColumn;
105759 pScan->nEquiv = 2;
105760 pScan->iEquiv = 2;
105761 return whereScanNext(pScan);
105765 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
105766 ** where X is a reference to the iColumn of table iCur and <op> is one of
105767 ** the WO_xx operator codes specified by the op parameter.
105768 ** Return a pointer to the term. Return 0 if not found.
105770 ** The term returned might by Y=<expr> if there is another constraint in
105771 ** the WHERE clause that specifies that X=Y. Any such constraints will be
105772 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
105773 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
105774 ** taking up two slots in aEquiv[]. The first slot is for the cursor number
105775 ** and the second is for the column number. There are 22 slots in aEquiv[]
105776 ** so that means we can look for X plus up to 10 other equivalent values.
105777 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
105778 ** and ... and A9=A10 and A10=<expr>.
105780 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
105781 ** then try for the one with no dependencies on <expr> - in other words where
105782 ** <expr> is a constant expression of some kind. Only return entries of
105783 ** the form "X <op> Y" where Y is a column in another table if no terms of
105784 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
105785 ** exist, try to return a term that does not use WO_EQUIV.
105787 static WhereTerm *findTerm(
105788 WhereClause *pWC, /* The WHERE clause to be searched */
105789 int iCur, /* Cursor number of LHS */
105790 int iColumn, /* Column number of LHS */
105791 Bitmask notReady, /* RHS must not overlap with this mask */
105792 u32 op, /* Mask of WO_xx values describing operator */
105793 Index *pIdx /* Must be compatible with this index, if not NULL */
105795 WhereTerm *pResult = 0;
105796 WhereTerm *p;
105797 WhereScan scan;
105799 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
105800 while( p ){
105801 if( (p->prereqRight & notReady)==0 ){
105802 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
105803 return p;
105805 if( pResult==0 ) pResult = p;
105807 p = whereScanNext(&scan);
105809 return pResult;
105812 /* Forward reference */
105813 static void exprAnalyze(SrcList*, WhereClause*, int);
105816 ** Call exprAnalyze on all terms in a WHERE clause.
105818 static void exprAnalyzeAll(
105819 SrcList *pTabList, /* the FROM clause */
105820 WhereClause *pWC /* the WHERE clause to be analyzed */
105822 int i;
105823 for(i=pWC->nTerm-1; i>=0; i--){
105824 exprAnalyze(pTabList, pWC, i);
105828 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
105830 ** Check to see if the given expression is a LIKE or GLOB operator that
105831 ** can be optimized using inequality constraints. Return TRUE if it is
105832 ** so and false if not.
105834 ** In order for the operator to be optimizible, the RHS must be a string
105835 ** literal that does not begin with a wildcard.
105837 static int isLikeOrGlob(
105838 Parse *pParse, /* Parsing and code generating context */
105839 Expr *pExpr, /* Test this expression */
105840 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
105841 int *pisComplete, /* True if the only wildcard is % in the last character */
105842 int *pnoCase /* True if uppercase is equivalent to lowercase */
105844 const char *z = 0; /* String on RHS of LIKE operator */
105845 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
105846 ExprList *pList; /* List of operands to the LIKE operator */
105847 int c; /* One character in z[] */
105848 int cnt; /* Number of non-wildcard prefix characters */
105849 char wc[3]; /* Wildcard characters */
105850 sqlite3 *db = pParse->db; /* Database connection */
105851 sqlite3_value *pVal = 0;
105852 int op; /* Opcode of pRight */
105854 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
105855 return 0;
105857 #ifdef SQLITE_EBCDIC
105858 if( *pnoCase ) return 0;
105859 #endif
105860 pList = pExpr->x.pList;
105861 pLeft = pList->a[1].pExpr;
105862 if( pLeft->op!=TK_COLUMN
105863 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
105864 || IsVirtual(pLeft->pTab)
105866 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
105867 ** be the name of an indexed column with TEXT affinity. */
105868 return 0;
105870 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
105872 pRight = pList->a[0].pExpr;
105873 op = pRight->op;
105874 if( op==TK_REGISTER ){
105875 op = pRight->op2;
105877 if( op==TK_VARIABLE ){
105878 Vdbe *pReprepare = pParse->pReprepare;
105879 int iCol = pRight->iColumn;
105880 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
105881 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
105882 z = (char *)sqlite3_value_text(pVal);
105884 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
105885 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
105886 }else if( op==TK_STRING ){
105887 z = pRight->u.zToken;
105889 if( z ){
105890 cnt = 0;
105891 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
105892 cnt++;
105894 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
105895 Expr *pPrefix;
105896 *pisComplete = c==wc[0] && z[cnt+1]==0;
105897 pPrefix = sqlite3Expr(db, TK_STRING, z);
105898 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
105899 *ppPrefix = pPrefix;
105900 if( op==TK_VARIABLE ){
105901 Vdbe *v = pParse->pVdbe;
105902 sqlite3VdbeSetVarmask(v, pRight->iColumn);
105903 if( *pisComplete && pRight->u.zToken[1] ){
105904 /* If the rhs of the LIKE expression is a variable, and the current
105905 ** value of the variable means there is no need to invoke the LIKE
105906 ** function, then no OP_Variable will be added to the program.
105907 ** This causes problems for the sqlite3_bind_parameter_name()
105908 ** API. To workaround them, add a dummy OP_Variable here.
105910 int r1 = sqlite3GetTempReg(pParse);
105911 sqlite3ExprCodeTarget(pParse, pRight, r1);
105912 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
105913 sqlite3ReleaseTempReg(pParse, r1);
105916 }else{
105917 z = 0;
105921 sqlite3ValueFree(pVal);
105922 return (z!=0);
105924 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
105927 #ifndef SQLITE_OMIT_VIRTUALTABLE
105929 ** Check to see if the given expression is of the form
105931 ** column MATCH expr
105933 ** If it is then return TRUE. If not, return FALSE.
105935 static int isMatchOfColumn(
105936 Expr *pExpr /* Test this expression */
105938 ExprList *pList;
105940 if( pExpr->op!=TK_FUNCTION ){
105941 return 0;
105943 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
105944 return 0;
105946 pList = pExpr->x.pList;
105947 if( pList->nExpr!=2 ){
105948 return 0;
105950 if( pList->a[1].pExpr->op != TK_COLUMN ){
105951 return 0;
105953 return 1;
105955 #endif /* SQLITE_OMIT_VIRTUALTABLE */
105958 ** If the pBase expression originated in the ON or USING clause of
105959 ** a join, then transfer the appropriate markings over to derived.
105961 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
105962 pDerived->flags |= pBase->flags & EP_FromJoin;
105963 pDerived->iRightJoinTable = pBase->iRightJoinTable;
105966 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
105968 ** Analyze a term that consists of two or more OR-connected
105969 ** subterms. So in:
105971 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
105972 ** ^^^^^^^^^^^^^^^^^^^^
105974 ** This routine analyzes terms such as the middle term in the above example.
105975 ** A WhereOrTerm object is computed and attached to the term under
105976 ** analysis, regardless of the outcome of the analysis. Hence:
105978 ** WhereTerm.wtFlags |= TERM_ORINFO
105979 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
105981 ** The term being analyzed must have two or more of OR-connected subterms.
105982 ** A single subterm might be a set of AND-connected sub-subterms.
105983 ** Examples of terms under analysis:
105985 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
105986 ** (B) x=expr1 OR expr2=x OR x=expr3
105987 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
105988 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
105989 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
105991 ** CASE 1:
105993 ** If all subterms are of the form T.C=expr for some single column of C and
105994 ** a single table T (as shown in example B above) then create a new virtual
105995 ** term that is an equivalent IN expression. In other words, if the term
105996 ** being analyzed is:
105998 ** x = expr1 OR expr2 = x OR x = expr3
106000 ** then create a new virtual term like this:
106002 ** x IN (expr1,expr2,expr3)
106004 ** CASE 2:
106006 ** If all subterms are indexable by a single table T, then set
106008 ** WhereTerm.eOperator = WO_OR
106009 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
106011 ** A subterm is "indexable" if it is of the form
106012 ** "T.C <op> <expr>" where C is any column of table T and
106013 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
106014 ** A subterm is also indexable if it is an AND of two or more
106015 ** subsubterms at least one of which is indexable. Indexable AND
106016 ** subterms have their eOperator set to WO_AND and they have
106017 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
106019 ** From another point of view, "indexable" means that the subterm could
106020 ** potentially be used with an index if an appropriate index exists.
106021 ** This analysis does not consider whether or not the index exists; that
106022 ** is decided elsewhere. This analysis only looks at whether subterms
106023 ** appropriate for indexing exist.
106025 ** All examples A through E above satisfy case 2. But if a term
106026 ** also statisfies case 1 (such as B) we know that the optimizer will
106027 ** always prefer case 1, so in that case we pretend that case 2 is not
106028 ** satisfied.
106030 ** It might be the case that multiple tables are indexable. For example,
106031 ** (E) above is indexable on tables P, Q, and R.
106033 ** Terms that satisfy case 2 are candidates for lookup by using
106034 ** separate indices to find rowids for each subterm and composing
106035 ** the union of all rowids using a RowSet object. This is similar
106036 ** to "bitmap indices" in other database engines.
106038 ** OTHERWISE:
106040 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
106041 ** zero. This term is not useful for search.
106043 static void exprAnalyzeOrTerm(
106044 SrcList *pSrc, /* the FROM clause */
106045 WhereClause *pWC, /* the complete WHERE clause */
106046 int idxTerm /* Index of the OR-term to be analyzed */
106048 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
106049 Parse *pParse = pWInfo->pParse; /* Parser context */
106050 sqlite3 *db = pParse->db; /* Database connection */
106051 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
106052 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
106053 int i; /* Loop counters */
106054 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
106055 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
106056 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
106057 Bitmask chngToIN; /* Tables that might satisfy case 1 */
106058 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
106061 ** Break the OR clause into its separate subterms. The subterms are
106062 ** stored in a WhereClause structure containing within the WhereOrInfo
106063 ** object that is attached to the original OR clause term.
106065 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
106066 assert( pExpr->op==TK_OR );
106067 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
106068 if( pOrInfo==0 ) return;
106069 pTerm->wtFlags |= TERM_ORINFO;
106070 pOrWc = &pOrInfo->wc;
106071 whereClauseInit(pOrWc, pWInfo);
106072 whereSplit(pOrWc, pExpr, TK_OR);
106073 exprAnalyzeAll(pSrc, pOrWc);
106074 if( db->mallocFailed ) return;
106075 assert( pOrWc->nTerm>=2 );
106078 ** Compute the set of tables that might satisfy cases 1 or 2.
106080 indexable = ~(Bitmask)0;
106081 chngToIN = ~(Bitmask)0;
106082 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
106083 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
106084 WhereAndInfo *pAndInfo;
106085 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
106086 chngToIN = 0;
106087 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
106088 if( pAndInfo ){
106089 WhereClause *pAndWC;
106090 WhereTerm *pAndTerm;
106091 int j;
106092 Bitmask b = 0;
106093 pOrTerm->u.pAndInfo = pAndInfo;
106094 pOrTerm->wtFlags |= TERM_ANDINFO;
106095 pOrTerm->eOperator = WO_AND;
106096 pAndWC = &pAndInfo->wc;
106097 whereClauseInit(pAndWC, pWC->pWInfo);
106098 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
106099 exprAnalyzeAll(pSrc, pAndWC);
106100 pAndWC->pOuter = pWC;
106101 testcase( db->mallocFailed );
106102 if( !db->mallocFailed ){
106103 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
106104 assert( pAndTerm->pExpr );
106105 if( allowedOp(pAndTerm->pExpr->op) ){
106106 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
106110 indexable &= b;
106112 }else if( pOrTerm->wtFlags & TERM_COPIED ){
106113 /* Skip this term for now. We revisit it when we process the
106114 ** corresponding TERM_VIRTUAL term */
106115 }else{
106116 Bitmask b;
106117 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
106118 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
106119 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
106120 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
106122 indexable &= b;
106123 if( (pOrTerm->eOperator & WO_EQ)==0 ){
106124 chngToIN = 0;
106125 }else{
106126 chngToIN &= b;
106132 ** Record the set of tables that satisfy case 2. The set might be
106133 ** empty.
106135 pOrInfo->indexable = indexable;
106136 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
106139 ** chngToIN holds a set of tables that *might* satisfy case 1. But
106140 ** we have to do some additional checking to see if case 1 really
106141 ** is satisfied.
106143 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
106144 ** that there is no possibility of transforming the OR clause into an
106145 ** IN operator because one or more terms in the OR clause contain
106146 ** something other than == on a column in the single table. The 1-bit
106147 ** case means that every term of the OR clause is of the form
106148 ** "table.column=expr" for some single table. The one bit that is set
106149 ** will correspond to the common table. We still need to check to make
106150 ** sure the same column is used on all terms. The 2-bit case is when
106151 ** the all terms are of the form "table1.column=table2.column". It
106152 ** might be possible to form an IN operator with either table1.column
106153 ** or table2.column as the LHS if either is common to every term of
106154 ** the OR clause.
106156 ** Note that terms of the form "table.column1=table.column2" (the
106157 ** same table on both sizes of the ==) cannot be optimized.
106159 if( chngToIN ){
106160 int okToChngToIN = 0; /* True if the conversion to IN is valid */
106161 int iColumn = -1; /* Column index on lhs of IN operator */
106162 int iCursor = -1; /* Table cursor common to all terms */
106163 int j = 0; /* Loop counter */
106165 /* Search for a table and column that appears on one side or the
106166 ** other of the == operator in every subterm. That table and column
106167 ** will be recorded in iCursor and iColumn. There might not be any
106168 ** such table and column. Set okToChngToIN if an appropriate table
106169 ** and column is found but leave okToChngToIN false if not found.
106171 for(j=0; j<2 && !okToChngToIN; j++){
106172 pOrTerm = pOrWc->a;
106173 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
106174 assert( pOrTerm->eOperator & WO_EQ );
106175 pOrTerm->wtFlags &= ~TERM_OR_OK;
106176 if( pOrTerm->leftCursor==iCursor ){
106177 /* This is the 2-bit case and we are on the second iteration and
106178 ** current term is from the first iteration. So skip this term. */
106179 assert( j==1 );
106180 continue;
106182 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
106183 /* This term must be of the form t1.a==t2.b where t2 is in the
106184 ** chngToIN set but t1 is not. This term will be either preceeded
106185 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
106186 ** and use its inversion. */
106187 testcase( pOrTerm->wtFlags & TERM_COPIED );
106188 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
106189 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
106190 continue;
106192 iColumn = pOrTerm->u.leftColumn;
106193 iCursor = pOrTerm->leftCursor;
106194 break;
106196 if( i<0 ){
106197 /* No candidate table+column was found. This can only occur
106198 ** on the second iteration */
106199 assert( j==1 );
106200 assert( IsPowerOfTwo(chngToIN) );
106201 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
106202 break;
106204 testcase( j==1 );
106206 /* We have found a candidate table and column. Check to see if that
106207 ** table and column is common to every term in the OR clause */
106208 okToChngToIN = 1;
106209 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
106210 assert( pOrTerm->eOperator & WO_EQ );
106211 if( pOrTerm->leftCursor!=iCursor ){
106212 pOrTerm->wtFlags &= ~TERM_OR_OK;
106213 }else if( pOrTerm->u.leftColumn!=iColumn ){
106214 okToChngToIN = 0;
106215 }else{
106216 int affLeft, affRight;
106217 /* If the right-hand side is also a column, then the affinities
106218 ** of both right and left sides must be such that no type
106219 ** conversions are required on the right. (Ticket #2249)
106221 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
106222 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
106223 if( affRight!=0 && affRight!=affLeft ){
106224 okToChngToIN = 0;
106225 }else{
106226 pOrTerm->wtFlags |= TERM_OR_OK;
106232 /* At this point, okToChngToIN is true if original pTerm satisfies
106233 ** case 1. In that case, construct a new virtual term that is
106234 ** pTerm converted into an IN operator.
106236 if( okToChngToIN ){
106237 Expr *pDup; /* A transient duplicate expression */
106238 ExprList *pList = 0; /* The RHS of the IN operator */
106239 Expr *pLeft = 0; /* The LHS of the IN operator */
106240 Expr *pNew; /* The complete IN operator */
106242 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
106243 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
106244 assert( pOrTerm->eOperator & WO_EQ );
106245 assert( pOrTerm->leftCursor==iCursor );
106246 assert( pOrTerm->u.leftColumn==iColumn );
106247 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
106248 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
106249 pLeft = pOrTerm->pExpr->pLeft;
106251 assert( pLeft!=0 );
106252 pDup = sqlite3ExprDup(db, pLeft, 0);
106253 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
106254 if( pNew ){
106255 int idxNew;
106256 transferJoinMarkings(pNew, pExpr);
106257 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
106258 pNew->x.pList = pList;
106259 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
106260 testcase( idxNew==0 );
106261 exprAnalyze(pSrc, pWC, idxNew);
106262 pTerm = &pWC->a[idxTerm];
106263 pWC->a[idxNew].iParent = idxTerm;
106264 pTerm->nChild = 1;
106265 }else{
106266 sqlite3ExprListDelete(db, pList);
106268 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
106272 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
106275 ** The input to this routine is an WhereTerm structure with only the
106276 ** "pExpr" field filled in. The job of this routine is to analyze the
106277 ** subexpression and populate all the other fields of the WhereTerm
106278 ** structure.
106280 ** If the expression is of the form "<expr> <op> X" it gets commuted
106281 ** to the standard form of "X <op> <expr>".
106283 ** If the expression is of the form "X <op> Y" where both X and Y are
106284 ** columns, then the original expression is unchanged and a new virtual
106285 ** term of the form "Y <op> X" is added to the WHERE clause and
106286 ** analyzed separately. The original term is marked with TERM_COPIED
106287 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
106288 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
106289 ** is a commuted copy of a prior term.) The original term has nChild=1
106290 ** and the copy has idxParent set to the index of the original term.
106292 static void exprAnalyze(
106293 SrcList *pSrc, /* the FROM clause */
106294 WhereClause *pWC, /* the WHERE clause */
106295 int idxTerm /* Index of the term to be analyzed */
106297 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
106298 WhereTerm *pTerm; /* The term to be analyzed */
106299 WhereMaskSet *pMaskSet; /* Set of table index masks */
106300 Expr *pExpr; /* The expression to be analyzed */
106301 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
106302 Bitmask prereqAll; /* Prerequesites of pExpr */
106303 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
106304 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
106305 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
106306 int noCase = 0; /* LIKE/GLOB distinguishes case */
106307 int op; /* Top-level operator. pExpr->op */
106308 Parse *pParse = pWInfo->pParse; /* Parsing context */
106309 sqlite3 *db = pParse->db; /* Database connection */
106311 if( db->mallocFailed ){
106312 return;
106314 pTerm = &pWC->a[idxTerm];
106315 pMaskSet = &pWInfo->sMaskSet;
106316 pExpr = pTerm->pExpr;
106317 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
106318 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
106319 op = pExpr->op;
106320 if( op==TK_IN ){
106321 assert( pExpr->pRight==0 );
106322 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
106323 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
106324 }else{
106325 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
106327 }else if( op==TK_ISNULL ){
106328 pTerm->prereqRight = 0;
106329 }else{
106330 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
106332 prereqAll = exprTableUsage(pMaskSet, pExpr);
106333 if( ExprHasProperty(pExpr, EP_FromJoin) ){
106334 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
106335 prereqAll |= x;
106336 extraRight = x-1; /* ON clause terms may not be used with an index
106337 ** on left table of a LEFT JOIN. Ticket #3015 */
106339 pTerm->prereqAll = prereqAll;
106340 pTerm->leftCursor = -1;
106341 pTerm->iParent = -1;
106342 pTerm->eOperator = 0;
106343 if( allowedOp(op) ){
106344 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
106345 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
106346 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
106347 if( pLeft->op==TK_COLUMN ){
106348 pTerm->leftCursor = pLeft->iTable;
106349 pTerm->u.leftColumn = pLeft->iColumn;
106350 pTerm->eOperator = operatorMask(op) & opMask;
106352 if( pRight && pRight->op==TK_COLUMN ){
106353 WhereTerm *pNew;
106354 Expr *pDup;
106355 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
106356 if( pTerm->leftCursor>=0 ){
106357 int idxNew;
106358 pDup = sqlite3ExprDup(db, pExpr, 0);
106359 if( db->mallocFailed ){
106360 sqlite3ExprDelete(db, pDup);
106361 return;
106363 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
106364 if( idxNew==0 ) return;
106365 pNew = &pWC->a[idxNew];
106366 pNew->iParent = idxTerm;
106367 pTerm = &pWC->a[idxTerm];
106368 pTerm->nChild = 1;
106369 pTerm->wtFlags |= TERM_COPIED;
106370 if( pExpr->op==TK_EQ
106371 && !ExprHasProperty(pExpr, EP_FromJoin)
106372 && OptimizationEnabled(db, SQLITE_Transitive)
106374 pTerm->eOperator |= WO_EQUIV;
106375 eExtraOp = WO_EQUIV;
106377 }else{
106378 pDup = pExpr;
106379 pNew = pTerm;
106381 exprCommute(pParse, pDup);
106382 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
106383 pNew->leftCursor = pLeft->iTable;
106384 pNew->u.leftColumn = pLeft->iColumn;
106385 testcase( (prereqLeft | extraRight) != prereqLeft );
106386 pNew->prereqRight = prereqLeft | extraRight;
106387 pNew->prereqAll = prereqAll;
106388 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
106392 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
106393 /* If a term is the BETWEEN operator, create two new virtual terms
106394 ** that define the range that the BETWEEN implements. For example:
106396 ** a BETWEEN b AND c
106398 ** is converted into:
106400 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
106402 ** The two new terms are added onto the end of the WhereClause object.
106403 ** The new terms are "dynamic" and are children of the original BETWEEN
106404 ** term. That means that if the BETWEEN term is coded, the children are
106405 ** skipped. Or, if the children are satisfied by an index, the original
106406 ** BETWEEN term is skipped.
106408 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
106409 ExprList *pList = pExpr->x.pList;
106410 int i;
106411 static const u8 ops[] = {TK_GE, TK_LE};
106412 assert( pList!=0 );
106413 assert( pList->nExpr==2 );
106414 for(i=0; i<2; i++){
106415 Expr *pNewExpr;
106416 int idxNew;
106417 pNewExpr = sqlite3PExpr(pParse, ops[i],
106418 sqlite3ExprDup(db, pExpr->pLeft, 0),
106419 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
106420 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
106421 testcase( idxNew==0 );
106422 exprAnalyze(pSrc, pWC, idxNew);
106423 pTerm = &pWC->a[idxTerm];
106424 pWC->a[idxNew].iParent = idxTerm;
106426 pTerm->nChild = 2;
106428 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
106430 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
106431 /* Analyze a term that is composed of two or more subterms connected by
106432 ** an OR operator.
106434 else if( pExpr->op==TK_OR ){
106435 assert( pWC->op==TK_AND );
106436 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
106437 pTerm = &pWC->a[idxTerm];
106439 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
106441 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
106442 /* Add constraints to reduce the search space on a LIKE or GLOB
106443 ** operator.
106445 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
106447 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
106449 ** The last character of the prefix "abc" is incremented to form the
106450 ** termination condition "abd".
106452 if( pWC->op==TK_AND
106453 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
106455 Expr *pLeft; /* LHS of LIKE/GLOB operator */
106456 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
106457 Expr *pNewExpr1;
106458 Expr *pNewExpr2;
106459 int idxNew1;
106460 int idxNew2;
106461 Token sCollSeqName; /* Name of collating sequence */
106463 pLeft = pExpr->x.pList->a[1].pExpr;
106464 pStr2 = sqlite3ExprDup(db, pStr1, 0);
106465 if( !db->mallocFailed ){
106466 u8 c, *pC; /* Last character before the first wildcard */
106467 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
106468 c = *pC;
106469 if( noCase ){
106470 /* The point is to increment the last character before the first
106471 ** wildcard. But if we increment '@', that will push it into the
106472 ** alphabetic range where case conversions will mess up the
106473 ** inequality. To avoid this, make sure to also run the full
106474 ** LIKE on all candidate expressions by clearing the isComplete flag
106476 if( c=='A'-1 ) isComplete = 0;
106477 c = sqlite3UpperToLower[c];
106479 *pC = c + 1;
106481 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
106482 sCollSeqName.n = 6;
106483 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
106484 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
106485 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
106486 pStr1, 0);
106487 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
106488 testcase( idxNew1==0 );
106489 exprAnalyze(pSrc, pWC, idxNew1);
106490 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
106491 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
106492 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
106493 pStr2, 0);
106494 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
106495 testcase( idxNew2==0 );
106496 exprAnalyze(pSrc, pWC, idxNew2);
106497 pTerm = &pWC->a[idxTerm];
106498 if( isComplete ){
106499 pWC->a[idxNew1].iParent = idxTerm;
106500 pWC->a[idxNew2].iParent = idxTerm;
106501 pTerm->nChild = 2;
106504 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
106506 #ifndef SQLITE_OMIT_VIRTUALTABLE
106507 /* Add a WO_MATCH auxiliary term to the constraint set if the
106508 ** current expression is of the form: column MATCH expr.
106509 ** This information is used by the xBestIndex methods of
106510 ** virtual tables. The native query optimizer does not attempt
106511 ** to do anything with MATCH functions.
106513 if( isMatchOfColumn(pExpr) ){
106514 int idxNew;
106515 Expr *pRight, *pLeft;
106516 WhereTerm *pNewTerm;
106517 Bitmask prereqColumn, prereqExpr;
106519 pRight = pExpr->x.pList->a[0].pExpr;
106520 pLeft = pExpr->x.pList->a[1].pExpr;
106521 prereqExpr = exprTableUsage(pMaskSet, pRight);
106522 prereqColumn = exprTableUsage(pMaskSet, pLeft);
106523 if( (prereqExpr & prereqColumn)==0 ){
106524 Expr *pNewExpr;
106525 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
106526 0, sqlite3ExprDup(db, pRight, 0), 0);
106527 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
106528 testcase( idxNew==0 );
106529 pNewTerm = &pWC->a[idxNew];
106530 pNewTerm->prereqRight = prereqExpr;
106531 pNewTerm->leftCursor = pLeft->iTable;
106532 pNewTerm->u.leftColumn = pLeft->iColumn;
106533 pNewTerm->eOperator = WO_MATCH;
106534 pNewTerm->iParent = idxTerm;
106535 pTerm = &pWC->a[idxTerm];
106536 pTerm->nChild = 1;
106537 pTerm->wtFlags |= TERM_COPIED;
106538 pNewTerm->prereqAll = pTerm->prereqAll;
106541 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106543 #ifdef SQLITE_ENABLE_STAT3
106544 /* When sqlite_stat3 histogram data is available an operator of the
106545 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
106546 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
106547 ** virtual term of that form.
106549 ** Note that the virtual term must be tagged with TERM_VNULL. This
106550 ** TERM_VNULL tag will suppress the not-null check at the beginning
106551 ** of the loop. Without the TERM_VNULL flag, the not-null check at
106552 ** the start of the loop will prevent any results from being returned.
106554 if( pExpr->op==TK_NOTNULL
106555 && pExpr->pLeft->op==TK_COLUMN
106556 && pExpr->pLeft->iColumn>=0
106557 && OptimizationEnabled(db, SQLITE_Stat3)
106559 Expr *pNewExpr;
106560 Expr *pLeft = pExpr->pLeft;
106561 int idxNew;
106562 WhereTerm *pNewTerm;
106564 pNewExpr = sqlite3PExpr(pParse, TK_GT,
106565 sqlite3ExprDup(db, pLeft, 0),
106566 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
106568 idxNew = whereClauseInsert(pWC, pNewExpr,
106569 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
106570 if( idxNew ){
106571 pNewTerm = &pWC->a[idxNew];
106572 pNewTerm->prereqRight = 0;
106573 pNewTerm->leftCursor = pLeft->iTable;
106574 pNewTerm->u.leftColumn = pLeft->iColumn;
106575 pNewTerm->eOperator = WO_GT;
106576 pNewTerm->iParent = idxTerm;
106577 pTerm = &pWC->a[idxTerm];
106578 pTerm->nChild = 1;
106579 pTerm->wtFlags |= TERM_COPIED;
106580 pNewTerm->prereqAll = pTerm->prereqAll;
106583 #endif /* SQLITE_ENABLE_STAT */
106585 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
106586 ** an index for tables to the left of the join.
106588 pTerm->prereqRight |= extraRight;
106592 ** This function searches pList for a entry that matches the iCol-th column
106593 ** of index pIdx.
106595 ** If such an expression is found, its index in pList->a[] is returned. If
106596 ** no expression is found, -1 is returned.
106598 static int findIndexCol(
106599 Parse *pParse, /* Parse context */
106600 ExprList *pList, /* Expression list to search */
106601 int iBase, /* Cursor for table associated with pIdx */
106602 Index *pIdx, /* Index to match column of */
106603 int iCol /* Column of index to match */
106605 int i;
106606 const char *zColl = pIdx->azColl[iCol];
106608 for(i=0; i<pList->nExpr; i++){
106609 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
106610 if( p->op==TK_COLUMN
106611 && p->iColumn==pIdx->aiColumn[iCol]
106612 && p->iTable==iBase
106614 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
106615 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
106616 return i;
106621 return -1;
106625 ** Return true if the DISTINCT expression-list passed as the third argument
106626 ** is redundant.
106628 ** A DISTINCT list is redundant if the database contains some subset of
106629 ** columns that are unique and non-null.
106631 static int isDistinctRedundant(
106632 Parse *pParse, /* Parsing context */
106633 SrcList *pTabList, /* The FROM clause */
106634 WhereClause *pWC, /* The WHERE clause */
106635 ExprList *pDistinct /* The result set that needs to be DISTINCT */
106637 Table *pTab;
106638 Index *pIdx;
106639 int i;
106640 int iBase;
106642 /* If there is more than one table or sub-select in the FROM clause of
106643 ** this query, then it will not be possible to show that the DISTINCT
106644 ** clause is redundant. */
106645 if( pTabList->nSrc!=1 ) return 0;
106646 iBase = pTabList->a[0].iCursor;
106647 pTab = pTabList->a[0].pTab;
106649 /* If any of the expressions is an IPK column on table iBase, then return
106650 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
106651 ** current SELECT is a correlated sub-query.
106653 for(i=0; i<pDistinct->nExpr; i++){
106654 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
106655 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
106658 /* Loop through all indices on the table, checking each to see if it makes
106659 ** the DISTINCT qualifier redundant. It does so if:
106661 ** 1. The index is itself UNIQUE, and
106663 ** 2. All of the columns in the index are either part of the pDistinct
106664 ** list, or else the WHERE clause contains a term of the form "col=X",
106665 ** where X is a constant value. The collation sequences of the
106666 ** comparison and select-list expressions must match those of the index.
106668 ** 3. All of those index columns for which the WHERE clause does not
106669 ** contain a "col=X" term are subject to a NOT NULL constraint.
106671 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
106672 if( pIdx->onError==OE_None ) continue;
106673 for(i=0; i<pIdx->nColumn; i++){
106674 int iCol = pIdx->aiColumn[i];
106675 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
106676 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
106677 if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
106678 break;
106682 if( i==pIdx->nColumn ){
106683 /* This index implies that the DISTINCT qualifier is redundant. */
106684 return 1;
106688 return 0;
106692 ** Find (an approximate) sum of two WhereCosts. This computation is
106693 ** not a simple "+" operator because WhereCost is stored as a logarithmic
106694 ** value.
106697 static WhereCost whereCostAdd(WhereCost a, WhereCost b){
106698 static const unsigned char x[] = {
106699 10, 10, /* 0,1 */
106700 9, 9, /* 2,3 */
106701 8, 8, /* 4,5 */
106702 7, 7, 7, /* 6,7,8 */
106703 6, 6, 6, /* 9,10,11 */
106704 5, 5, 5, /* 12-14 */
106705 4, 4, 4, 4, /* 15-18 */
106706 3, 3, 3, 3, 3, 3, /* 19-24 */
106707 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
106709 if( a>=b ){
106710 if( a>b+49 ) return a;
106711 if( a>b+31 ) return a+1;
106712 return a+x[a-b];
106713 }else{
106714 if( b>a+49 ) return b;
106715 if( b>a+31 ) return b+1;
106716 return b+x[b-a];
106721 ** Convert an integer into a WhereCost. In other words, compute a
106722 ** good approximatation for 10*log2(x).
106724 static WhereCost whereCost(tRowcnt x){
106725 static WhereCost a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
106726 WhereCost y = 40;
106727 if( x<8 ){
106728 if( x<2 ) return 0;
106729 while( x<8 ){ y -= 10; x <<= 1; }
106730 }else{
106731 while( x>255 ){ y += 40; x >>= 4; }
106732 while( x>15 ){ y += 10; x >>= 1; }
106734 return a[x&7] + y - 10;
106737 #ifndef SQLITE_OMIT_VIRTUALTABLE
106739 ** Convert a double (as received from xBestIndex of a virtual table)
106740 ** into a WhereCost. In other words, compute an approximation for
106741 ** 10*log2(x).
106743 static WhereCost whereCostFromDouble(double x){
106744 u64 a;
106745 WhereCost e;
106746 assert( sizeof(x)==8 && sizeof(a)==8 );
106747 if( x<=1 ) return 0;
106748 if( x<=2000000000 ) return whereCost((tRowcnt)x);
106749 memcpy(&a, &x, 8);
106750 e = (a>>52) - 1022;
106751 return e*10;
106753 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106756 ** Estimate the logarithm of the input value to base 2.
106758 static WhereCost estLog(WhereCost N){
106759 WhereCost x = whereCost(N);
106760 return x>33 ? x - 33 : 0;
106764 ** Two routines for printing the content of an sqlite3_index_info
106765 ** structure. Used for testing and debugging only. If neither
106766 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
106767 ** are no-ops.
106769 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
106770 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
106771 int i;
106772 if( !sqlite3WhereTrace ) return;
106773 for(i=0; i<p->nConstraint; i++){
106774 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
106776 p->aConstraint[i].iColumn,
106777 p->aConstraint[i].iTermOffset,
106778 p->aConstraint[i].op,
106779 p->aConstraint[i].usable);
106781 for(i=0; i<p->nOrderBy; i++){
106782 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
106784 p->aOrderBy[i].iColumn,
106785 p->aOrderBy[i].desc);
106788 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
106789 int i;
106790 if( !sqlite3WhereTrace ) return;
106791 for(i=0; i<p->nConstraint; i++){
106792 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
106794 p->aConstraintUsage[i].argvIndex,
106795 p->aConstraintUsage[i].omit);
106797 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
106798 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
106799 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
106800 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
106802 #else
106803 #define TRACE_IDX_INPUTS(A)
106804 #define TRACE_IDX_OUTPUTS(A)
106805 #endif
106807 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106809 ** Return TRUE if the WHERE clause term pTerm is of a form where it
106810 ** could be used with an index to access pSrc, assuming an appropriate
106811 ** index existed.
106813 static int termCanDriveIndex(
106814 WhereTerm *pTerm, /* WHERE clause term to check */
106815 struct SrcList_item *pSrc, /* Table we are trying to access */
106816 Bitmask notReady /* Tables in outer loops of the join */
106818 char aff;
106819 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
106820 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
106821 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
106822 if( pTerm->u.leftColumn<0 ) return 0;
106823 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
106824 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
106825 return 1;
106827 #endif
106830 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106832 ** Generate code to construct the Index object for an automatic index
106833 ** and to set up the WhereLevel object pLevel so that the code generator
106834 ** makes use of the automatic index.
106836 static void constructAutomaticIndex(
106837 Parse *pParse, /* The parsing context */
106838 WhereClause *pWC, /* The WHERE clause */
106839 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
106840 Bitmask notReady, /* Mask of cursors that are not available */
106841 WhereLevel *pLevel /* Write new index here */
106843 int nColumn; /* Number of columns in the constructed index */
106844 WhereTerm *pTerm; /* A single term of the WHERE clause */
106845 WhereTerm *pWCEnd; /* End of pWC->a[] */
106846 int nByte; /* Byte of memory needed for pIdx */
106847 Index *pIdx; /* Object describing the transient index */
106848 Vdbe *v; /* Prepared statement under construction */
106849 int addrInit; /* Address of the initialization bypass jump */
106850 Table *pTable; /* The table being indexed */
106851 KeyInfo *pKeyinfo; /* Key information for the index */
106852 int addrTop; /* Top of the index fill loop */
106853 int regRecord; /* Register holding an index record */
106854 int n; /* Column counter */
106855 int i; /* Loop counter */
106856 int mxBitCol; /* Maximum column in pSrc->colUsed */
106857 CollSeq *pColl; /* Collating sequence to on a column */
106858 WhereLoop *pLoop; /* The Loop object */
106859 Bitmask idxCols; /* Bitmap of columns used for indexing */
106860 Bitmask extraCols; /* Bitmap of additional columns */
106861 u8 sentWarning = 0; /* True if a warnning has been issued */
106863 /* Generate code to skip over the creation and initialization of the
106864 ** transient index on 2nd and subsequent iterations of the loop. */
106865 v = pParse->pVdbe;
106866 assert( v!=0 );
106867 addrInit = sqlite3CodeOnce(pParse);
106869 /* Count the number of columns that will be added to the index
106870 ** and used to match WHERE clause constraints */
106871 nColumn = 0;
106872 pTable = pSrc->pTab;
106873 pWCEnd = &pWC->a[pWC->nTerm];
106874 pLoop = pLevel->pWLoop;
106875 idxCols = 0;
106876 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106877 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106878 int iCol = pTerm->u.leftColumn;
106879 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
106880 testcase( iCol==BMS );
106881 testcase( iCol==BMS-1 );
106882 if( !sentWarning ){
106883 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
106884 "automatic index on %s(%s)", pTable->zName,
106885 pTable->aCol[iCol].zName);
106886 sentWarning = 1;
106888 if( (idxCols & cMask)==0 ){
106889 if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
106890 pLoop->aLTerm[nColumn++] = pTerm;
106891 idxCols |= cMask;
106895 assert( nColumn>0 );
106896 pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
106897 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
106898 | WHERE_AUTO_INDEX;
106900 /* Count the number of additional columns needed to create a
106901 ** covering index. A "covering index" is an index that contains all
106902 ** columns that are needed by the query. With a covering index, the
106903 ** original table never needs to be accessed. Automatic indices must
106904 ** be a covering index because the index will not be updated if the
106905 ** original table changes and the index and table cannot both be used
106906 ** if they go out of sync.
106908 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
106909 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
106910 testcase( pTable->nCol==BMS-1 );
106911 testcase( pTable->nCol==BMS-2 );
106912 for(i=0; i<mxBitCol; i++){
106913 if( extraCols & MASKBIT(i) ) nColumn++;
106915 if( pSrc->colUsed & MASKBIT(BMS-1) ){
106916 nColumn += pTable->nCol - BMS + 1;
106918 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
106920 /* Construct the Index object to describe this index */
106921 nByte = sizeof(Index);
106922 nByte += nColumn*sizeof(int); /* Index.aiColumn */
106923 nByte += nColumn*sizeof(char*); /* Index.azColl */
106924 nByte += nColumn; /* Index.aSortOrder */
106925 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
106926 if( pIdx==0 ) return;
106927 pLoop->u.btree.pIndex = pIdx;
106928 pIdx->azColl = (char**)&pIdx[1];
106929 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
106930 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
106931 pIdx->zName = "auto-index";
106932 pIdx->nColumn = nColumn;
106933 pIdx->pTable = pTable;
106934 n = 0;
106935 idxCols = 0;
106936 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106937 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106938 int iCol = pTerm->u.leftColumn;
106939 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
106940 testcase( iCol==BMS-1 );
106941 testcase( iCol==BMS );
106942 if( (idxCols & cMask)==0 ){
106943 Expr *pX = pTerm->pExpr;
106944 idxCols |= cMask;
106945 pIdx->aiColumn[n] = pTerm->u.leftColumn;
106946 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
106947 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
106952 assert( (u32)n==pLoop->u.btree.nEq );
106954 /* Add additional columns needed to make the automatic index into
106955 ** a covering index */
106956 for(i=0; i<mxBitCol; i++){
106957 if( extraCols & MASKBIT(i) ){
106958 pIdx->aiColumn[n] = i;
106959 pIdx->azColl[n] = "BINARY";
106963 if( pSrc->colUsed & MASKBIT(BMS-1) ){
106964 for(i=BMS-1; i<pTable->nCol; i++){
106965 pIdx->aiColumn[n] = i;
106966 pIdx->azColl[n] = "BINARY";
106970 assert( n==nColumn );
106972 /* Create the automatic index */
106973 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
106974 assert( pLevel->iIdxCur>=0 );
106975 pLevel->iIdxCur = pParse->nTab++;
106976 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
106977 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
106978 VdbeComment((v, "for %s", pTable->zName));
106980 /* Fill the automatic index with content */
106981 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
106982 regRecord = sqlite3GetTempReg(pParse);
106983 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0);
106984 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
106985 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
106986 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
106987 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
106988 sqlite3VdbeJumpHere(v, addrTop);
106989 sqlite3ReleaseTempReg(pParse, regRecord);
106991 /* Jump here when skipping the initialization */
106992 sqlite3VdbeJumpHere(v, addrInit);
106994 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
106996 #ifndef SQLITE_OMIT_VIRTUALTABLE
106998 ** Allocate and populate an sqlite3_index_info structure. It is the
106999 ** responsibility of the caller to eventually release the structure
107000 ** by passing the pointer returned by this function to sqlite3_free().
107002 static sqlite3_index_info *allocateIndexInfo(
107003 Parse *pParse,
107004 WhereClause *pWC,
107005 struct SrcList_item *pSrc,
107006 ExprList *pOrderBy
107008 int i, j;
107009 int nTerm;
107010 struct sqlite3_index_constraint *pIdxCons;
107011 struct sqlite3_index_orderby *pIdxOrderBy;
107012 struct sqlite3_index_constraint_usage *pUsage;
107013 WhereTerm *pTerm;
107014 int nOrderBy;
107015 sqlite3_index_info *pIdxInfo;
107017 /* Count the number of possible WHERE clause constraints referring
107018 ** to this virtual table */
107019 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
107020 if( pTerm->leftCursor != pSrc->iCursor ) continue;
107021 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
107022 testcase( pTerm->eOperator & WO_IN );
107023 testcase( pTerm->eOperator & WO_ISNULL );
107024 if( pTerm->eOperator & (WO_ISNULL) ) continue;
107025 if( pTerm->wtFlags & TERM_VNULL ) continue;
107026 nTerm++;
107029 /* If the ORDER BY clause contains only columns in the current
107030 ** virtual table then allocate space for the aOrderBy part of
107031 ** the sqlite3_index_info structure.
107033 nOrderBy = 0;
107034 if( pOrderBy ){
107035 int n = pOrderBy->nExpr;
107036 for(i=0; i<n; i++){
107037 Expr *pExpr = pOrderBy->a[i].pExpr;
107038 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
107040 if( i==n){
107041 nOrderBy = n;
107045 /* Allocate the sqlite3_index_info structure
107047 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
107048 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
107049 + sizeof(*pIdxOrderBy)*nOrderBy );
107050 if( pIdxInfo==0 ){
107051 sqlite3ErrorMsg(pParse, "out of memory");
107052 return 0;
107055 /* Initialize the structure. The sqlite3_index_info structure contains
107056 ** many fields that are declared "const" to prevent xBestIndex from
107057 ** changing them. We have to do some funky casting in order to
107058 ** initialize those fields.
107060 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
107061 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
107062 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
107063 *(int*)&pIdxInfo->nConstraint = nTerm;
107064 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
107065 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
107066 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
107067 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
107068 pUsage;
107070 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
107071 u8 op;
107072 if( pTerm->leftCursor != pSrc->iCursor ) continue;
107073 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
107074 testcase( pTerm->eOperator & WO_IN );
107075 testcase( pTerm->eOperator & WO_ISNULL );
107076 if( pTerm->eOperator & (WO_ISNULL) ) continue;
107077 if( pTerm->wtFlags & TERM_VNULL ) continue;
107078 pIdxCons[j].iColumn = pTerm->u.leftColumn;
107079 pIdxCons[j].iTermOffset = i;
107080 op = (u8)pTerm->eOperator & WO_ALL;
107081 if( op==WO_IN ) op = WO_EQ;
107082 pIdxCons[j].op = op;
107083 /* The direct assignment in the previous line is possible only because
107084 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
107085 ** following asserts verify this fact. */
107086 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
107087 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
107088 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
107089 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
107090 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
107091 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
107092 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
107095 for(i=0; i<nOrderBy; i++){
107096 Expr *pExpr = pOrderBy->a[i].pExpr;
107097 pIdxOrderBy[i].iColumn = pExpr->iColumn;
107098 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
107101 return pIdxInfo;
107105 ** The table object reference passed as the second argument to this function
107106 ** must represent a virtual table. This function invokes the xBestIndex()
107107 ** method of the virtual table with the sqlite3_index_info object that
107108 ** comes in as the 3rd argument to this function.
107110 ** If an error occurs, pParse is populated with an error message and a
107111 ** non-zero value is returned. Otherwise, 0 is returned and the output
107112 ** part of the sqlite3_index_info structure is left populated.
107114 ** Whether or not an error is returned, it is the responsibility of the
107115 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
107116 ** that this is required.
107118 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
107119 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
107120 int i;
107121 int rc;
107123 TRACE_IDX_INPUTS(p);
107124 rc = pVtab->pModule->xBestIndex(pVtab, p);
107125 TRACE_IDX_OUTPUTS(p);
107127 if( rc!=SQLITE_OK ){
107128 if( rc==SQLITE_NOMEM ){
107129 pParse->db->mallocFailed = 1;
107130 }else if( !pVtab->zErrMsg ){
107131 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
107132 }else{
107133 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
107136 sqlite3_free(pVtab->zErrMsg);
107137 pVtab->zErrMsg = 0;
107139 for(i=0; i<p->nConstraint; i++){
107140 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
107141 sqlite3ErrorMsg(pParse,
107142 "table %s: xBestIndex returned an invalid plan", pTab->zName);
107146 return pParse->nErr;
107148 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
107151 #ifdef SQLITE_ENABLE_STAT3
107153 ** Estimate the location of a particular key among all keys in an
107154 ** index. Store the results in aStat as follows:
107156 ** aStat[0] Est. number of rows less than pVal
107157 ** aStat[1] Est. number of rows equal to pVal
107159 ** Return SQLITE_OK on success.
107161 static int whereKeyStats(
107162 Parse *pParse, /* Database connection */
107163 Index *pIdx, /* Index to consider domain of */
107164 sqlite3_value *pVal, /* Value to consider */
107165 int roundUp, /* Round up if true. Round down if false */
107166 tRowcnt *aStat /* OUT: stats written here */
107168 tRowcnt n;
107169 IndexSample *aSample;
107170 int i, eType;
107171 int isEq = 0;
107172 i64 v;
107173 double r, rS;
107175 assert( roundUp==0 || roundUp==1 );
107176 assert( pIdx->nSample>0 );
107177 if( pVal==0 ) return SQLITE_ERROR;
107178 n = pIdx->aiRowEst[0];
107179 aSample = pIdx->aSample;
107180 eType = sqlite3_value_type(pVal);
107182 if( eType==SQLITE_INTEGER ){
107183 v = sqlite3_value_int64(pVal);
107184 r = (i64)v;
107185 for(i=0; i<pIdx->nSample; i++){
107186 if( aSample[i].eType==SQLITE_NULL ) continue;
107187 if( aSample[i].eType>=SQLITE_TEXT ) break;
107188 if( aSample[i].eType==SQLITE_INTEGER ){
107189 if( aSample[i].u.i>=v ){
107190 isEq = aSample[i].u.i==v;
107191 break;
107193 }else{
107194 assert( aSample[i].eType==SQLITE_FLOAT );
107195 if( aSample[i].u.r>=r ){
107196 isEq = aSample[i].u.r==r;
107197 break;
107201 }else if( eType==SQLITE_FLOAT ){
107202 r = sqlite3_value_double(pVal);
107203 for(i=0; i<pIdx->nSample; i++){
107204 if( aSample[i].eType==SQLITE_NULL ) continue;
107205 if( aSample[i].eType>=SQLITE_TEXT ) break;
107206 if( aSample[i].eType==SQLITE_FLOAT ){
107207 rS = aSample[i].u.r;
107208 }else{
107209 rS = aSample[i].u.i;
107211 if( rS>=r ){
107212 isEq = rS==r;
107213 break;
107216 }else if( eType==SQLITE_NULL ){
107217 i = 0;
107218 if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
107219 }else{
107220 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
107221 for(i=0; i<pIdx->nSample; i++){
107222 if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
107223 break;
107226 if( i<pIdx->nSample ){
107227 sqlite3 *db = pParse->db;
107228 CollSeq *pColl;
107229 const u8 *z;
107230 if( eType==SQLITE_BLOB ){
107231 z = (const u8 *)sqlite3_value_blob(pVal);
107232 pColl = db->pDfltColl;
107233 assert( pColl->enc==SQLITE_UTF8 );
107234 }else{
107235 pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
107236 /* If the collating sequence was unavailable, we should have failed
107237 ** long ago and never reached this point. But we'll check just to
107238 ** be doubly sure. */
107239 if( NEVER(pColl==0) ) return SQLITE_ERROR;
107240 z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
107241 if( !z ){
107242 return SQLITE_NOMEM;
107244 assert( z && pColl && pColl->xCmp );
107246 n = sqlite3ValueBytes(pVal, pColl->enc);
107248 for(; i<pIdx->nSample; i++){
107249 int c;
107250 int eSampletype = aSample[i].eType;
107251 if( eSampletype<eType ) continue;
107252 if( eSampletype!=eType ) break;
107253 #ifndef SQLITE_OMIT_UTF16
107254 if( pColl->enc!=SQLITE_UTF8 ){
107255 int nSample;
107256 char *zSample = sqlite3Utf8to16(
107257 db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
107259 if( !zSample ){
107260 assert( db->mallocFailed );
107261 return SQLITE_NOMEM;
107263 c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
107264 sqlite3DbFree(db, zSample);
107265 }else
107266 #endif
107268 c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
107270 if( c>=0 ){
107271 if( c==0 ) isEq = 1;
107272 break;
107278 /* At this point, aSample[i] is the first sample that is greater than
107279 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
107280 ** than pVal. If aSample[i]==pVal, then isEq==1.
107282 if( isEq ){
107283 assert( i<pIdx->nSample );
107284 aStat[0] = aSample[i].nLt;
107285 aStat[1] = aSample[i].nEq;
107286 }else{
107287 tRowcnt iLower, iUpper, iGap;
107288 if( i==0 ){
107289 iLower = 0;
107290 iUpper = aSample[0].nLt;
107291 }else{
107292 iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
107293 iLower = aSample[i-1].nEq + aSample[i-1].nLt;
107295 aStat[1] = pIdx->avgEq;
107296 if( iLower>=iUpper ){
107297 iGap = 0;
107298 }else{
107299 iGap = iUpper - iLower;
107301 if( roundUp ){
107302 iGap = (iGap*2)/3;
107303 }else{
107304 iGap = iGap/3;
107306 aStat[0] = iLower + iGap;
107308 return SQLITE_OK;
107310 #endif /* SQLITE_ENABLE_STAT3 */
107313 ** If expression pExpr represents a literal value, set *pp to point to
107314 ** an sqlite3_value structure containing the same value, with affinity
107315 ** aff applied to it, before returning. It is the responsibility of the
107316 ** caller to eventually release this structure by passing it to
107317 ** sqlite3ValueFree().
107319 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
107320 ** is an SQL variable that currently has a non-NULL value bound to it,
107321 ** create an sqlite3_value structure containing this value, again with
107322 ** affinity aff applied to it, instead.
107324 ** If neither of the above apply, set *pp to NULL.
107326 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
107328 #ifdef SQLITE_ENABLE_STAT3
107329 static int valueFromExpr(
107330 Parse *pParse,
107331 Expr *pExpr,
107332 u8 aff,
107333 sqlite3_value **pp
107335 if( pExpr->op==TK_VARIABLE
107336 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
107338 int iVar = pExpr->iColumn;
107339 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
107340 *pp = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, aff);
107341 return SQLITE_OK;
107343 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
107345 #endif
107348 ** This function is used to estimate the number of rows that will be visited
107349 ** by scanning an index for a range of values. The range may have an upper
107350 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
107351 ** and lower bounds are represented by pLower and pUpper respectively. For
107352 ** example, assuming that index p is on t1(a):
107354 ** ... FROM t1 WHERE a > ? AND a < ? ...
107355 ** |_____| |_____|
107356 ** | |
107357 ** pLower pUpper
107359 ** If either of the upper or lower bound is not present, then NULL is passed in
107360 ** place of the corresponding WhereTerm.
107362 ** The nEq parameter is passed the index of the index column subject to the
107363 ** range constraint. Or, equivalently, the number of equality constraints
107364 ** optimized by the proposed index scan. For example, assuming index p is
107365 ** on t1(a, b), and the SQL query is:
107367 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
107369 ** then nEq should be passed the value 1 (as the range restricted column,
107370 ** b, is the second left-most column of the index). Or, if the query is:
107372 ** ... FROM t1 WHERE a > ? AND a < ? ...
107374 ** then nEq should be passed 0.
107376 ** The returned value is an integer divisor to reduce the estimated
107377 ** search space. A return value of 1 means that range constraints are
107378 ** no help at all. A return value of 2 means range constraints are
107379 ** expected to reduce the search space by half. And so forth...
107381 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
107382 ** reduces the search space by a factor of 4. Hence a single constraint (x>?)
107383 ** results in a return of 4 and a range constraint (x>? AND x<?) results
107384 ** in a return of 16.
107386 static int whereRangeScanEst(
107387 Parse *pParse, /* Parsing & code generating context */
107388 Index *p, /* The index containing the range-compared column; "x" */
107389 int nEq, /* index into p->aCol[] of the range-compared column */
107390 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
107391 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
107392 WhereCost *pRangeDiv /* OUT: Reduce search space by this divisor */
107394 int rc = SQLITE_OK;
107396 #ifdef SQLITE_ENABLE_STAT3
107398 if( nEq==0 && p->nSample && OptimizationEnabled(pParse->db, SQLITE_Stat3) ){
107399 sqlite3_value *pRangeVal;
107400 tRowcnt iLower = 0;
107401 tRowcnt iUpper = p->aiRowEst[0];
107402 tRowcnt a[2];
107403 u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
107405 if( pLower ){
107406 Expr *pExpr = pLower->pExpr->pRight;
107407 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
107408 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
107409 if( rc==SQLITE_OK
107410 && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
107412 iLower = a[0];
107413 if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
107415 sqlite3ValueFree(pRangeVal);
107417 if( rc==SQLITE_OK && pUpper ){
107418 Expr *pExpr = pUpper->pExpr->pRight;
107419 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
107420 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
107421 if( rc==SQLITE_OK
107422 && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
107424 iUpper = a[0];
107425 if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
107427 sqlite3ValueFree(pRangeVal);
107429 if( rc==SQLITE_OK ){
107430 WhereCost iBase = whereCost(p->aiRowEst[0]);
107431 if( iUpper>iLower ){
107432 iBase -= whereCost(iUpper - iLower);
107434 *pRangeDiv = iBase;
107435 WHERETRACE(0x100, ("range scan regions: %u..%u div=%d\n",
107436 (u32)iLower, (u32)iUpper, *pRangeDiv));
107437 return SQLITE_OK;
107440 #else
107441 UNUSED_PARAMETER(pParse);
107442 UNUSED_PARAMETER(p);
107443 UNUSED_PARAMETER(nEq);
107444 #endif
107445 assert( pLower || pUpper );
107446 *pRangeDiv = 0;
107447 /* TUNING: Each inequality constraint reduces the search space 4-fold.
107448 ** A BETWEEN operator, therefore, reduces the search space 16-fold */
107449 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
107450 *pRangeDiv += 20; assert( 20==whereCost(4) );
107452 if( pUpper ){
107453 *pRangeDiv += 20; assert( 20==whereCost(4) );
107455 return rc;
107458 #ifdef SQLITE_ENABLE_STAT3
107460 ** Estimate the number of rows that will be returned based on
107461 ** an equality constraint x=VALUE and where that VALUE occurs in
107462 ** the histogram data. This only works when x is the left-most
107463 ** column of an index and sqlite_stat3 histogram data is available
107464 ** for that index. When pExpr==NULL that means the constraint is
107465 ** "x IS NULL" instead of "x=VALUE".
107467 ** Write the estimated row count into *pnRow and return SQLITE_OK.
107468 ** If unable to make an estimate, leave *pnRow unchanged and return
107469 ** non-zero.
107471 ** This routine can fail if it is unable to load a collating sequence
107472 ** required for string comparison, or if unable to allocate memory
107473 ** for a UTF conversion required for comparison. The error is stored
107474 ** in the pParse structure.
107476 static int whereEqualScanEst(
107477 Parse *pParse, /* Parsing & code generating context */
107478 Index *p, /* The index whose left-most column is pTerm */
107479 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
107480 tRowcnt *pnRow /* Write the revised row estimate here */
107482 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
107483 u8 aff; /* Column affinity */
107484 int rc; /* Subfunction return code */
107485 tRowcnt a[2]; /* Statistics */
107487 assert( p->aSample!=0 );
107488 assert( p->nSample>0 );
107489 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
107490 if( pExpr ){
107491 rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
107492 if( rc ) goto whereEqualScanEst_cancel;
107493 }else{
107494 pRhs = sqlite3ValueNew(pParse->db);
107496 if( pRhs==0 ) return SQLITE_NOTFOUND;
107497 rc = whereKeyStats(pParse, p, pRhs, 0, a);
107498 if( rc==SQLITE_OK ){
107499 WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
107500 *pnRow = a[1];
107502 whereEqualScanEst_cancel:
107503 sqlite3ValueFree(pRhs);
107504 return rc;
107506 #endif /* defined(SQLITE_ENABLE_STAT3) */
107508 #ifdef SQLITE_ENABLE_STAT3
107510 ** Estimate the number of rows that will be returned based on
107511 ** an IN constraint where the right-hand side of the IN operator
107512 ** is a list of values. Example:
107514 ** WHERE x IN (1,2,3,4)
107516 ** Write the estimated row count into *pnRow and return SQLITE_OK.
107517 ** If unable to make an estimate, leave *pnRow unchanged and return
107518 ** non-zero.
107520 ** This routine can fail if it is unable to load a collating sequence
107521 ** required for string comparison, or if unable to allocate memory
107522 ** for a UTF conversion required for comparison. The error is stored
107523 ** in the pParse structure.
107525 static int whereInScanEst(
107526 Parse *pParse, /* Parsing & code generating context */
107527 Index *p, /* The index whose left-most column is pTerm */
107528 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
107529 tRowcnt *pnRow /* Write the revised row estimate here */
107531 int rc = SQLITE_OK; /* Subfunction return code */
107532 tRowcnt nEst; /* Number of rows for a single term */
107533 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
107534 int i; /* Loop counter */
107536 assert( p->aSample!=0 );
107537 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
107538 nEst = p->aiRowEst[0];
107539 rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
107540 nRowEst += nEst;
107542 if( rc==SQLITE_OK ){
107543 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
107544 *pnRow = nRowEst;
107545 WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
107547 return rc;
107549 #endif /* defined(SQLITE_ENABLE_STAT3) */
107552 ** Disable a term in the WHERE clause. Except, do not disable the term
107553 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
107554 ** or USING clause of that join.
107556 ** Consider the term t2.z='ok' in the following queries:
107558 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
107559 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
107560 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
107562 ** The t2.z='ok' is disabled in the in (2) because it originates
107563 ** in the ON clause. The term is disabled in (3) because it is not part
107564 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
107566 ** Disabling a term causes that term to not be tested in the inner loop
107567 ** of the join. Disabling is an optimization. When terms are satisfied
107568 ** by indices, we disable them to prevent redundant tests in the inner
107569 ** loop. We would get the correct results if nothing were ever disabled,
107570 ** but joins might run a little slower. The trick is to disable as much
107571 ** as we can without disabling too much. If we disabled in (1), we'd get
107572 ** the wrong answer. See ticket #813.
107574 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
107575 if( pTerm
107576 && (pTerm->wtFlags & TERM_CODED)==0
107577 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
107579 pTerm->wtFlags |= TERM_CODED;
107580 if( pTerm->iParent>=0 ){
107581 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
107582 if( (--pOther->nChild)==0 ){
107583 disableTerm(pLevel, pOther);
107590 ** Code an OP_Affinity opcode to apply the column affinity string zAff
107591 ** to the n registers starting at base.
107593 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
107594 ** beginning and end of zAff are ignored. If all entries in zAff are
107595 ** SQLITE_AFF_NONE, then no code gets generated.
107597 ** This routine makes its own copy of zAff so that the caller is free
107598 ** to modify zAff after this routine returns.
107600 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
107601 Vdbe *v = pParse->pVdbe;
107602 if( zAff==0 ){
107603 assert( pParse->db->mallocFailed );
107604 return;
107606 assert( v!=0 );
107608 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
107609 ** and end of the affinity string.
107611 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
107613 base++;
107614 zAff++;
107616 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
107620 /* Code the OP_Affinity opcode if there is anything left to do. */
107621 if( n>0 ){
107622 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
107623 sqlite3VdbeChangeP4(v, -1, zAff, n);
107624 sqlite3ExprCacheAffinityChange(pParse, base, n);
107630 ** Generate code for a single equality term of the WHERE clause. An equality
107631 ** term can be either X=expr or X IN (...). pTerm is the term to be
107632 ** coded.
107634 ** The current value for the constraint is left in register iReg.
107636 ** For a constraint of the form X=expr, the expression is evaluated and its
107637 ** result is left on the stack. For constraints of the form X IN (...)
107638 ** this routine sets up a loop that will iterate over all values of X.
107640 static int codeEqualityTerm(
107641 Parse *pParse, /* The parsing context */
107642 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
107643 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
107644 int iEq, /* Index of the equality term within this level */
107645 int bRev, /* True for reverse-order IN operations */
107646 int iTarget /* Attempt to leave results in this register */
107648 Expr *pX = pTerm->pExpr;
107649 Vdbe *v = pParse->pVdbe;
107650 int iReg; /* Register holding results */
107652 assert( iTarget>0 );
107653 if( pX->op==TK_EQ ){
107654 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
107655 }else if( pX->op==TK_ISNULL ){
107656 iReg = iTarget;
107657 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
107658 #ifndef SQLITE_OMIT_SUBQUERY
107659 }else{
107660 int eType;
107661 int iTab;
107662 struct InLoop *pIn;
107663 WhereLoop *pLoop = pLevel->pWLoop;
107665 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
107666 && pLoop->u.btree.pIndex!=0
107667 && pLoop->u.btree.pIndex->aSortOrder[iEq]
107669 testcase( iEq==0 );
107670 testcase( bRev );
107671 bRev = !bRev;
107673 assert( pX->op==TK_IN );
107674 iReg = iTarget;
107675 eType = sqlite3FindInIndex(pParse, pX, 0);
107676 if( eType==IN_INDEX_INDEX_DESC ){
107677 testcase( bRev );
107678 bRev = !bRev;
107680 iTab = pX->iTable;
107681 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
107682 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
107683 pLoop->wsFlags |= WHERE_IN_ABLE;
107684 if( pLevel->u.in.nIn==0 ){
107685 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
107687 pLevel->u.in.nIn++;
107688 pLevel->u.in.aInLoop =
107689 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
107690 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
107691 pIn = pLevel->u.in.aInLoop;
107692 if( pIn ){
107693 pIn += pLevel->u.in.nIn - 1;
107694 pIn->iCur = iTab;
107695 if( eType==IN_INDEX_ROWID ){
107696 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
107697 }else{
107698 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
107700 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
107701 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
107702 }else{
107703 pLevel->u.in.nIn = 0;
107705 #endif
107707 disableTerm(pLevel, pTerm);
107708 return iReg;
107712 ** Generate code that will evaluate all == and IN constraints for an
107713 ** index.
107715 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
107716 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
107717 ** The index has as many as three equality constraints, but in this
107718 ** example, the third "c" value is an inequality. So only two
107719 ** constraints are coded. This routine will generate code to evaluate
107720 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
107721 ** in consecutive registers and the index of the first register is returned.
107723 ** In the example above nEq==2. But this subroutine works for any value
107724 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
107725 ** The only thing it does is allocate the pLevel->iMem memory cell and
107726 ** compute the affinity string.
107728 ** This routine always allocates at least one memory cell and returns
107729 ** the index of that memory cell. The code that
107730 ** calls this routine will use that memory cell to store the termination
107731 ** key value of the loop. If one or more IN operators appear, then
107732 ** this routine allocates an additional nEq memory cells for internal
107733 ** use.
107735 ** Before returning, *pzAff is set to point to a buffer containing a
107736 ** copy of the column affinity string of the index allocated using
107737 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
107738 ** with equality constraints that use NONE affinity are set to
107739 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
107741 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
107742 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
107744 ** In the example above, the index on t1(a) has TEXT affinity. But since
107745 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
107746 ** no conversion should be attempted before using a t2.b value as part of
107747 ** a key to search the index. Hence the first byte in the returned affinity
107748 ** string in this example would be set to SQLITE_AFF_NONE.
107750 static int codeAllEqualityTerms(
107751 Parse *pParse, /* Parsing context */
107752 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
107753 int bRev, /* Reverse the order of IN operators */
107754 int nExtraReg, /* Number of extra registers to allocate */
107755 char **pzAff /* OUT: Set to point to affinity string */
107757 int nEq; /* The number of == or IN constraints to code */
107758 Vdbe *v = pParse->pVdbe; /* The vm under construction */
107759 Index *pIdx; /* The index being used for this loop */
107760 WhereTerm *pTerm; /* A single constraint term */
107761 WhereLoop *pLoop; /* The WhereLoop object */
107762 int j; /* Loop counter */
107763 int regBase; /* Base register */
107764 int nReg; /* Number of registers to allocate */
107765 char *zAff; /* Affinity string to return */
107767 /* This module is only called on query plans that use an index. */
107768 pLoop = pLevel->pWLoop;
107769 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
107770 nEq = pLoop->u.btree.nEq;
107771 pIdx = pLoop->u.btree.pIndex;
107772 assert( pIdx!=0 );
107774 /* Figure out how many memory cells we will need then allocate them.
107776 regBase = pParse->nMem + 1;
107777 nReg = pLoop->u.btree.nEq + nExtraReg;
107778 pParse->nMem += nReg;
107780 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
107781 if( !zAff ){
107782 pParse->db->mallocFailed = 1;
107785 /* Evaluate the equality constraints
107787 assert( zAff==0 || strlen(zAff)>=nEq );
107788 for(j=0; j<nEq; j++){
107789 int r1;
107790 pTerm = pLoop->aLTerm[j];
107791 assert( pTerm!=0 );
107792 /* The following true for indices with redundant columns.
107793 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
107794 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
107795 testcase( pTerm->wtFlags & TERM_VIRTUAL );
107796 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
107797 if( r1!=regBase+j ){
107798 if( nReg==1 ){
107799 sqlite3ReleaseTempReg(pParse, regBase);
107800 regBase = r1;
107801 }else{
107802 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
107805 testcase( pTerm->eOperator & WO_ISNULL );
107806 testcase( pTerm->eOperator & WO_IN );
107807 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
107808 Expr *pRight = pTerm->pExpr->pRight;
107809 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
107810 if( zAff ){
107811 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
107812 zAff[j] = SQLITE_AFF_NONE;
107814 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
107815 zAff[j] = SQLITE_AFF_NONE;
107820 *pzAff = zAff;
107821 return regBase;
107824 #ifndef SQLITE_OMIT_EXPLAIN
107826 ** This routine is a helper for explainIndexRange() below
107828 ** pStr holds the text of an expression that we are building up one term
107829 ** at a time. This routine adds a new term to the end of the expression.
107830 ** Terms are separated by AND so add the "AND" text for second and subsequent
107831 ** terms only.
107833 static void explainAppendTerm(
107834 StrAccum *pStr, /* The text expression being built */
107835 int iTerm, /* Index of this term. First is zero */
107836 const char *zColumn, /* Name of the column */
107837 const char *zOp /* Name of the operator */
107839 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
107840 sqlite3StrAccumAppend(pStr, zColumn, -1);
107841 sqlite3StrAccumAppend(pStr, zOp, 1);
107842 sqlite3StrAccumAppend(pStr, "?", 1);
107846 ** Argument pLevel describes a strategy for scanning table pTab. This
107847 ** function returns a pointer to a string buffer containing a description
107848 ** of the subset of table rows scanned by the strategy in the form of an
107849 ** SQL expression. Or, if all rows are scanned, NULL is returned.
107851 ** For example, if the query:
107853 ** SELECT * FROM t1 WHERE a=1 AND b>2;
107855 ** is run and there is an index on (a, b), then this function returns a
107856 ** string similar to:
107858 ** "a=? AND b>?"
107860 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
107861 ** It is the responsibility of the caller to free the buffer when it is
107862 ** no longer required.
107864 static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
107865 Index *pIndex = pLoop->u.btree.pIndex;
107866 int nEq = pLoop->u.btree.nEq;
107867 int i, j;
107868 Column *aCol = pTab->aCol;
107869 int *aiColumn = pIndex->aiColumn;
107870 StrAccum txt;
107872 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
107873 return 0;
107875 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
107876 txt.db = db;
107877 sqlite3StrAccumAppend(&txt, " (", 2);
107878 for(i=0; i<nEq; i++){
107879 char *z = (i==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[i]].zName;
107880 explainAppendTerm(&txt, i, z, "=");
107883 j = i;
107884 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
107885 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
107886 explainAppendTerm(&txt, i++, z, ">");
107888 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
107889 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
107890 explainAppendTerm(&txt, i, z, "<");
107892 sqlite3StrAccumAppend(&txt, ")", 1);
107893 return sqlite3StrAccumFinish(&txt);
107897 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
107898 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
107899 ** record is added to the output to describe the table scan strategy in
107900 ** pLevel.
107902 static void explainOneScan(
107903 Parse *pParse, /* Parse context */
107904 SrcList *pTabList, /* Table list this loop refers to */
107905 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
107906 int iLevel, /* Value for "level" column of output */
107907 int iFrom, /* Value for "from" column of output */
107908 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
107910 if( pParse->explain==2 ){
107911 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
107912 Vdbe *v = pParse->pVdbe; /* VM being constructed */
107913 sqlite3 *db = pParse->db; /* Database handle */
107914 char *zMsg; /* Text to add to EQP output */
107915 int iId = pParse->iSelectId; /* Select id (left-most output column) */
107916 int isSearch; /* True for a SEARCH. False for SCAN. */
107917 WhereLoop *pLoop; /* The controlling WhereLoop object */
107918 u32 flags; /* Flags that describe this loop */
107920 pLoop = pLevel->pWLoop;
107921 flags = pLoop->wsFlags;
107922 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
107924 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
107925 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
107926 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
107928 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
107929 if( pItem->pSelect ){
107930 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
107931 }else{
107932 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
107935 if( pItem->zAlias ){
107936 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
107938 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
107939 && ALWAYS(pLoop->u.btree.pIndex!=0)
107941 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
107942 zMsg = sqlite3MAppendf(db, zMsg,
107943 ((flags & WHERE_AUTO_INDEX) ?
107944 "%s USING AUTOMATIC %sINDEX%.0s%s" :
107945 "%s USING %sINDEX %s%s"),
107946 zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
107947 pLoop->u.btree.pIndex->zName, zWhere);
107948 sqlite3DbFree(db, zWhere);
107949 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
107950 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
107952 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
107953 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
107954 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
107955 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
107956 }else if( flags&WHERE_BTM_LIMIT ){
107957 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
107958 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
107959 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
107962 #ifndef SQLITE_OMIT_VIRTUALTABLE
107963 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
107964 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
107965 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
107967 #endif
107968 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
107969 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
107972 #else
107973 # define explainOneScan(u,v,w,x,y,z)
107974 #endif /* SQLITE_OMIT_EXPLAIN */
107978 ** Generate code for the start of the iLevel-th loop in the WHERE clause
107979 ** implementation described by pWInfo.
107981 static Bitmask codeOneLoopStart(
107982 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
107983 int iLevel, /* Which level of pWInfo->a[] should be coded */
107984 Bitmask notReady /* Which tables are currently available */
107986 int j, k; /* Loop counters */
107987 int iCur; /* The VDBE cursor for the table */
107988 int addrNxt; /* Where to jump to continue with the next IN case */
107989 int omitTable; /* True if we use the index only */
107990 int bRev; /* True if we need to scan in reverse order */
107991 WhereLevel *pLevel; /* The where level to be coded */
107992 WhereLoop *pLoop; /* The WhereLoop object being coded */
107993 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
107994 WhereTerm *pTerm; /* A WHERE clause term */
107995 Parse *pParse; /* Parsing context */
107996 sqlite3 *db; /* Database connection */
107997 Vdbe *v; /* The prepared stmt under constructions */
107998 struct SrcList_item *pTabItem; /* FROM clause term being coded */
107999 int addrBrk; /* Jump here to break out of the loop */
108000 int addrCont; /* Jump here to continue with next cycle */
108001 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
108002 int iReleaseReg = 0; /* Temp register to free before returning */
108003 Bitmask newNotReady; /* Return value */
108005 pParse = pWInfo->pParse;
108006 v = pParse->pVdbe;
108007 pWC = &pWInfo->sWC;
108008 db = pParse->db;
108009 pLevel = &pWInfo->a[iLevel];
108010 pLoop = pLevel->pWLoop;
108011 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
108012 iCur = pTabItem->iCursor;
108013 bRev = (pWInfo->revMask>>iLevel)&1;
108014 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
108015 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
108016 VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
108018 /* Create labels for the "break" and "continue" instructions
108019 ** for the current loop. Jump to addrBrk to break out of a loop.
108020 ** Jump to cont to go immediately to the next iteration of the
108021 ** loop.
108023 ** When there is an IN operator, we also have a "addrNxt" label that
108024 ** means to continue with the next IN value combination. When
108025 ** there are no IN operators in the constraints, the "addrNxt" label
108026 ** is the same as "addrBrk".
108028 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
108029 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
108031 /* If this is the right table of a LEFT OUTER JOIN, allocate and
108032 ** initialize a memory cell that records if this table matches any
108033 ** row of the left table of the join.
108035 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
108036 pLevel->iLeftJoin = ++pParse->nMem;
108037 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
108038 VdbeComment((v, "init LEFT JOIN no-match flag"));
108041 /* Special case of a FROM clause subquery implemented as a co-routine */
108042 if( pTabItem->viaCoroutine ){
108043 int regYield = pTabItem->regReturn;
108044 sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
108045 pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
108046 VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
108047 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
108048 pLevel->op = OP_Goto;
108049 }else
108051 #ifndef SQLITE_OMIT_VIRTUALTABLE
108052 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
108053 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
108054 ** to access the data.
108056 int iReg; /* P3 Value for OP_VFilter */
108057 int addrNotFound;
108058 int nConstraint = pLoop->nLTerm;
108060 sqlite3ExprCachePush(pParse);
108061 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
108062 addrNotFound = pLevel->addrBrk;
108063 for(j=0; j<nConstraint; j++){
108064 int iTarget = iReg+j+2;
108065 pTerm = pLoop->aLTerm[j];
108066 if( pTerm==0 ) continue;
108067 if( pTerm->eOperator & WO_IN ){
108068 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
108069 addrNotFound = pLevel->addrNxt;
108070 }else{
108071 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
108074 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
108075 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
108076 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
108077 pLoop->u.vtab.idxStr,
108078 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
108079 pLoop->u.vtab.needFree = 0;
108080 for(j=0; j<nConstraint && j<16; j++){
108081 if( (pLoop->u.vtab.omitMask>>j)&1 ){
108082 disableTerm(pLevel, pLoop->aLTerm[j]);
108085 pLevel->op = OP_VNext;
108086 pLevel->p1 = iCur;
108087 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
108088 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
108089 sqlite3ExprCachePop(pParse, 1);
108090 }else
108091 #endif /* SQLITE_OMIT_VIRTUALTABLE */
108093 if( (pLoop->wsFlags & WHERE_IPK)!=0
108094 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
108096 /* Case 2: We can directly reference a single row using an
108097 ** equality comparison against the ROWID field. Or
108098 ** we reference multiple rows using a "rowid IN (...)"
108099 ** construct.
108101 assert( pLoop->u.btree.nEq==1 );
108102 iReleaseReg = sqlite3GetTempReg(pParse);
108103 pTerm = pLoop->aLTerm[0];
108104 assert( pTerm!=0 );
108105 assert( pTerm->pExpr!=0 );
108106 assert( omitTable==0 );
108107 testcase( pTerm->wtFlags & TERM_VIRTUAL );
108108 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
108109 addrNxt = pLevel->addrNxt;
108110 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
108111 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
108112 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
108113 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108114 VdbeComment((v, "pk"));
108115 pLevel->op = OP_Noop;
108116 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
108117 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
108119 /* Case 3: We have an inequality comparison against the ROWID field.
108121 int testOp = OP_Noop;
108122 int start;
108123 int memEndValue = 0;
108124 WhereTerm *pStart, *pEnd;
108126 assert( omitTable==0 );
108127 j = 0;
108128 pStart = pEnd = 0;
108129 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
108130 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
108131 assert( pStart!=0 || pEnd!=0 );
108132 if( bRev ){
108133 pTerm = pStart;
108134 pStart = pEnd;
108135 pEnd = pTerm;
108137 if( pStart ){
108138 Expr *pX; /* The expression that defines the start bound */
108139 int r1, rTemp; /* Registers for holding the start boundary */
108141 /* The following constant maps TK_xx codes into corresponding
108142 ** seek opcodes. It depends on a particular ordering of TK_xx
108144 const u8 aMoveOp[] = {
108145 /* TK_GT */ OP_SeekGt,
108146 /* TK_LE */ OP_SeekLe,
108147 /* TK_LT */ OP_SeekLt,
108148 /* TK_GE */ OP_SeekGe
108150 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
108151 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
108152 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
108154 assert( (pStart->wtFlags & TERM_VNULL)==0 );
108155 testcase( pStart->wtFlags & TERM_VIRTUAL );
108156 pX = pStart->pExpr;
108157 assert( pX!=0 );
108158 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
108159 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
108160 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
108161 VdbeComment((v, "pk"));
108162 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
108163 sqlite3ReleaseTempReg(pParse, rTemp);
108164 disableTerm(pLevel, pStart);
108165 }else{
108166 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
108168 if( pEnd ){
108169 Expr *pX;
108170 pX = pEnd->pExpr;
108171 assert( pX!=0 );
108172 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
108173 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
108174 testcase( pEnd->wtFlags & TERM_VIRTUAL );
108175 memEndValue = ++pParse->nMem;
108176 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
108177 if( pX->op==TK_LT || pX->op==TK_GT ){
108178 testOp = bRev ? OP_Le : OP_Ge;
108179 }else{
108180 testOp = bRev ? OP_Lt : OP_Gt;
108182 disableTerm(pLevel, pEnd);
108184 start = sqlite3VdbeCurrentAddr(v);
108185 pLevel->op = bRev ? OP_Prev : OP_Next;
108186 pLevel->p1 = iCur;
108187 pLevel->p2 = start;
108188 assert( pLevel->p5==0 );
108189 if( testOp!=OP_Noop ){
108190 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108191 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
108192 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108193 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
108194 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
108196 }else if( pLoop->wsFlags & WHERE_INDEXED ){
108197 /* Case 4: A scan using an index.
108199 ** The WHERE clause may contain zero or more equality
108200 ** terms ("==" or "IN" operators) that refer to the N
108201 ** left-most columns of the index. It may also contain
108202 ** inequality constraints (>, <, >= or <=) on the indexed
108203 ** column that immediately follows the N equalities. Only
108204 ** the right-most column can be an inequality - the rest must
108205 ** use the "==" and "IN" operators. For example, if the
108206 ** index is on (x,y,z), then the following clauses are all
108207 ** optimized:
108209 ** x=5
108210 ** x=5 AND y=10
108211 ** x=5 AND y<10
108212 ** x=5 AND y>5 AND y<10
108213 ** x=5 AND y=5 AND z<=10
108215 ** The z<10 term of the following cannot be used, only
108216 ** the x=5 term:
108218 ** x=5 AND z<10
108220 ** N may be zero if there are inequality constraints.
108221 ** If there are no inequality constraints, then N is at
108222 ** least one.
108224 ** This case is also used when there are no WHERE clause
108225 ** constraints but an index is selected anyway, in order
108226 ** to force the output order to conform to an ORDER BY.
108228 static const u8 aStartOp[] = {
108231 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
108232 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
108233 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
108234 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
108235 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
108236 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
108238 static const u8 aEndOp[] = {
108239 OP_Noop, /* 0: (!end_constraints) */
108240 OP_IdxGE, /* 1: (end_constraints && !bRev) */
108241 OP_IdxLT /* 2: (end_constraints && bRev) */
108243 int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
108244 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
108245 int regBase; /* Base register holding constraint values */
108246 int r1; /* Temp register */
108247 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
108248 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
108249 int startEq; /* True if range start uses ==, >= or <= */
108250 int endEq; /* True if range end uses ==, >= or <= */
108251 int start_constraints; /* Start of range is constrained */
108252 int nConstraint; /* Number of constraint terms */
108253 Index *pIdx; /* The index we will be using */
108254 int iIdxCur; /* The VDBE cursor for the index */
108255 int nExtraReg = 0; /* Number of extra registers needed */
108256 int op; /* Instruction opcode */
108257 char *zStartAff; /* Affinity for start of range constraint */
108258 char *zEndAff; /* Affinity for end of range constraint */
108260 pIdx = pLoop->u.btree.pIndex;
108261 iIdxCur = pLevel->iIdxCur;
108263 /* If this loop satisfies a sort order (pOrderBy) request that
108264 ** was passed to this function to implement a "SELECT min(x) ..."
108265 ** query, then the caller will only allow the loop to run for
108266 ** a single iteration. This means that the first row returned
108267 ** should not have a NULL value stored in 'x'. If column 'x' is
108268 ** the first one after the nEq equality constraints in the index,
108269 ** this requires some special handling.
108271 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
108272 && (pWInfo->bOBSat!=0)
108273 && (pIdx->nColumn>nEq)
108275 /* assert( pOrderBy->nExpr==1 ); */
108276 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
108277 isMinQuery = 1;
108278 nExtraReg = 1;
108281 /* Find any inequality constraint terms for the start and end
108282 ** of the range.
108284 j = nEq;
108285 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
108286 pRangeStart = pLoop->aLTerm[j++];
108287 nExtraReg = 1;
108289 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
108290 pRangeEnd = pLoop->aLTerm[j++];
108291 nExtraReg = 1;
108294 /* Generate code to evaluate all constraint terms using == or IN
108295 ** and store the values of those terms in an array of registers
108296 ** starting at regBase.
108298 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
108299 zEndAff = sqlite3DbStrDup(db, zStartAff);
108300 addrNxt = pLevel->addrNxt;
108302 /* If we are doing a reverse order scan on an ascending index, or
108303 ** a forward order scan on a descending index, interchange the
108304 ** start and end terms (pRangeStart and pRangeEnd).
108306 if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
108307 || (bRev && pIdx->nColumn==nEq)
108309 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
108312 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
108313 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
108314 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
108315 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
108316 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
108317 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
108318 start_constraints = pRangeStart || nEq>0;
108320 /* Seek the index cursor to the start of the range. */
108321 nConstraint = nEq;
108322 if( pRangeStart ){
108323 Expr *pRight = pRangeStart->pExpr->pRight;
108324 sqlite3ExprCode(pParse, pRight, regBase+nEq);
108325 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
108326 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
108328 if( zStartAff ){
108329 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
108330 /* Since the comparison is to be performed with no conversions
108331 ** applied to the operands, set the affinity to apply to pRight to
108332 ** SQLITE_AFF_NONE. */
108333 zStartAff[nEq] = SQLITE_AFF_NONE;
108335 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
108336 zStartAff[nEq] = SQLITE_AFF_NONE;
108339 nConstraint++;
108340 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
108341 }else if( isMinQuery ){
108342 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
108343 nConstraint++;
108344 startEq = 0;
108345 start_constraints = 1;
108347 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
108348 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
108349 assert( op!=0 );
108350 testcase( op==OP_Rewind );
108351 testcase( op==OP_Last );
108352 testcase( op==OP_SeekGt );
108353 testcase( op==OP_SeekGe );
108354 testcase( op==OP_SeekLe );
108355 testcase( op==OP_SeekLt );
108356 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
108358 /* Load the value for the inequality constraint at the end of the
108359 ** range (if any).
108361 nConstraint = nEq;
108362 if( pRangeEnd ){
108363 Expr *pRight = pRangeEnd->pExpr->pRight;
108364 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
108365 sqlite3ExprCode(pParse, pRight, regBase+nEq);
108366 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
108367 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
108369 if( zEndAff ){
108370 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
108371 /* Since the comparison is to be performed with no conversions
108372 ** applied to the operands, set the affinity to apply to pRight to
108373 ** SQLITE_AFF_NONE. */
108374 zEndAff[nEq] = SQLITE_AFF_NONE;
108376 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
108377 zEndAff[nEq] = SQLITE_AFF_NONE;
108380 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
108381 nConstraint++;
108382 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
108384 sqlite3DbFree(db, zStartAff);
108385 sqlite3DbFree(db, zEndAff);
108387 /* Top of the loop body */
108388 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
108390 /* Check if the index cursor is past the end of the range. */
108391 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
108392 testcase( op==OP_Noop );
108393 testcase( op==OP_IdxGE );
108394 testcase( op==OP_IdxLT );
108395 if( op!=OP_Noop ){
108396 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
108397 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
108400 /* If there are inequality constraints, check that the value
108401 ** of the table column that the inequality contrains is not NULL.
108402 ** If it is, jump to the next iteration of the loop.
108404 r1 = sqlite3GetTempReg(pParse);
108405 testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
108406 testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
108407 if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
108408 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
108409 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
108411 sqlite3ReleaseTempReg(pParse, r1);
108413 /* Seek the table cursor, if required */
108414 disableTerm(pLevel, pRangeStart);
108415 disableTerm(pLevel, pRangeEnd);
108416 if( !omitTable ){
108417 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108418 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
108419 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108420 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
108423 /* Record the instruction used to terminate the loop. Disable
108424 ** WHERE clause terms made redundant by the index range scan.
108426 if( pLoop->wsFlags & WHERE_ONEROW ){
108427 pLevel->op = OP_Noop;
108428 }else if( bRev ){
108429 pLevel->op = OP_Prev;
108430 }else{
108431 pLevel->op = OP_Next;
108433 pLevel->p1 = iIdxCur;
108434 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
108435 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108436 }else{
108437 assert( pLevel->p5==0 );
108439 }else
108441 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
108442 if( pLoop->wsFlags & WHERE_MULTI_OR ){
108443 /* Case 5: Two or more separately indexed terms connected by OR
108445 ** Example:
108447 ** CREATE TABLE t1(a,b,c,d);
108448 ** CREATE INDEX i1 ON t1(a);
108449 ** CREATE INDEX i2 ON t1(b);
108450 ** CREATE INDEX i3 ON t1(c);
108452 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
108454 ** In the example, there are three indexed terms connected by OR.
108455 ** The top of the loop looks like this:
108457 ** Null 1 # Zero the rowset in reg 1
108459 ** Then, for each indexed term, the following. The arguments to
108460 ** RowSetTest are such that the rowid of the current row is inserted
108461 ** into the RowSet. If it is already present, control skips the
108462 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
108464 ** sqlite3WhereBegin(<term>)
108465 ** RowSetTest # Insert rowid into rowset
108466 ** Gosub 2 A
108467 ** sqlite3WhereEnd()
108469 ** Following the above, code to terminate the loop. Label A, the target
108470 ** of the Gosub above, jumps to the instruction right after the Goto.
108472 ** Null 1 # Zero the rowset in reg 1
108473 ** Goto B # The loop is finished.
108475 ** A: <loop body> # Return data, whatever.
108477 ** Return 2 # Jump back to the Gosub
108479 ** B: <after the loop>
108482 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
108483 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
108484 Index *pCov = 0; /* Potential covering index (or NULL) */
108485 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
108487 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
108488 int regRowset = 0; /* Register for RowSet object */
108489 int regRowid = 0; /* Register holding rowid */
108490 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
108491 int iRetInit; /* Address of regReturn init */
108492 int untestedTerms = 0; /* Some terms not completely tested */
108493 int ii; /* Loop counter */
108494 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
108496 pTerm = pLoop->aLTerm[0];
108497 assert( pTerm!=0 );
108498 assert( pTerm->eOperator & WO_OR );
108499 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
108500 pOrWc = &pTerm->u.pOrInfo->wc;
108501 pLevel->op = OP_Return;
108502 pLevel->p1 = regReturn;
108504 /* Set up a new SrcList in pOrTab containing the table being scanned
108505 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
108506 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
108508 if( pWInfo->nLevel>1 ){
108509 int nNotReady; /* The number of notReady tables */
108510 struct SrcList_item *origSrc; /* Original list of tables */
108511 nNotReady = pWInfo->nLevel - iLevel - 1;
108512 pOrTab = sqlite3StackAllocRaw(db,
108513 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
108514 if( pOrTab==0 ) return notReady;
108515 pOrTab->nAlloc = (u8)(nNotReady + 1);
108516 pOrTab->nSrc = pOrTab->nAlloc;
108517 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
108518 origSrc = pWInfo->pTabList->a;
108519 for(k=1; k<=nNotReady; k++){
108520 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
108522 }else{
108523 pOrTab = pWInfo->pTabList;
108526 /* Initialize the rowset register to contain NULL. An SQL NULL is
108527 ** equivalent to an empty rowset.
108529 ** Also initialize regReturn to contain the address of the instruction
108530 ** immediately following the OP_Return at the bottom of the loop. This
108531 ** is required in a few obscure LEFT JOIN cases where control jumps
108532 ** over the top of the loop into the body of it. In this case the
108533 ** correct response for the end-of-loop code (the OP_Return) is to
108534 ** fall through to the next instruction, just as an OP_Next does if
108535 ** called on an uninitialized cursor.
108537 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108538 regRowset = ++pParse->nMem;
108539 regRowid = ++pParse->nMem;
108540 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
108542 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
108544 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
108545 ** Then for every term xN, evaluate as the subexpression: xN AND z
108546 ** That way, terms in y that are factored into the disjunction will
108547 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
108549 ** Actually, each subexpression is converted to "xN AND w" where w is
108550 ** the "interesting" terms of z - terms that did not originate in the
108551 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
108552 ** indices.
108554 ** This optimization also only applies if the (x1 OR x2 OR ...) term
108555 ** is not contained in the ON clause of a LEFT JOIN.
108556 ** See ticket http://www.sqlite.org/src/info/f2369304e4
108558 if( pWC->nTerm>1 ){
108559 int iTerm;
108560 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
108561 Expr *pExpr = pWC->a[iTerm].pExpr;
108562 if( &pWC->a[iTerm] == pTerm ) continue;
108563 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
108564 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
108565 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
108566 pExpr = sqlite3ExprDup(db, pExpr, 0);
108567 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
108569 if( pAndExpr ){
108570 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
108574 for(ii=0; ii<pOrWc->nTerm; ii++){
108575 WhereTerm *pOrTerm = &pOrWc->a[ii];
108576 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
108577 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
108578 Expr *pOrExpr = pOrTerm->pExpr;
108579 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
108580 pAndExpr->pLeft = pOrExpr;
108581 pOrExpr = pAndExpr;
108583 /* Loop through table entries that match term pOrTerm. */
108584 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
108585 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
108586 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
108587 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
108588 if( pSubWInfo ){
108589 WhereLoop *pSubLoop;
108590 explainOneScan(
108591 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
108593 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108594 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
108595 int r;
108596 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
108597 regRowid, 0);
108598 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
108599 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
108601 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
108603 /* The pSubWInfo->untestedTerms flag means that this OR term
108604 ** contained one or more AND term from a notReady table. The
108605 ** terms from the notReady table could not be tested and will
108606 ** need to be tested later.
108608 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
108610 /* If all of the OR-connected terms are optimized using the same
108611 ** index, and the index is opened using the same cursor number
108612 ** by each call to sqlite3WhereBegin() made by this loop, it may
108613 ** be possible to use that index as a covering index.
108615 ** If the call to sqlite3WhereBegin() above resulted in a scan that
108616 ** uses an index, and this is either the first OR-connected term
108617 ** processed or the index is the same as that used by all previous
108618 ** terms, set pCov to the candidate covering index. Otherwise, set
108619 ** pCov to NULL to indicate that no candidate covering index will
108620 ** be available.
108622 pSubLoop = pSubWInfo->a[0].pWLoop;
108623 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
108624 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
108625 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
108627 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
108628 pCov = pSubLoop->u.btree.pIndex;
108629 }else{
108630 pCov = 0;
108633 /* Finish the loop through table entries that match term pOrTerm. */
108634 sqlite3WhereEnd(pSubWInfo);
108638 pLevel->u.pCovidx = pCov;
108639 if( pCov ) pLevel->iIdxCur = iCovCur;
108640 if( pAndExpr ){
108641 pAndExpr->pLeft = 0;
108642 sqlite3ExprDelete(db, pAndExpr);
108644 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
108645 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
108646 sqlite3VdbeResolveLabel(v, iLoopBody);
108648 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
108649 if( !untestedTerms ) disableTerm(pLevel, pTerm);
108650 }else
108651 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
108654 /* Case 6: There is no usable index. We must do a complete
108655 ** scan of the entire table.
108657 static const u8 aStep[] = { OP_Next, OP_Prev };
108658 static const u8 aStart[] = { OP_Rewind, OP_Last };
108659 assert( bRev==0 || bRev==1 );
108660 pLevel->op = aStep[bRev];
108661 pLevel->p1 = iCur;
108662 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
108663 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108665 newNotReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
108667 /* Insert code to test every subexpression that can be completely
108668 ** computed using the current set of tables.
108670 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
108671 Expr *pE;
108672 testcase( pTerm->wtFlags & TERM_VIRTUAL );
108673 testcase( pTerm->wtFlags & TERM_CODED );
108674 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
108675 if( (pTerm->prereqAll & newNotReady)!=0 ){
108676 testcase( pWInfo->untestedTerms==0
108677 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
108678 pWInfo->untestedTerms = 1;
108679 continue;
108681 pE = pTerm->pExpr;
108682 assert( pE!=0 );
108683 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
108684 continue;
108686 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
108687 pTerm->wtFlags |= TERM_CODED;
108690 /* Insert code to test for implied constraints based on transitivity
108691 ** of the "==" operator.
108693 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
108694 ** and we are coding the t1 loop and the t2 loop has not yet coded,
108695 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
108696 ** the implied "t1.a=123" constraint.
108698 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
108699 Expr *pE, *pEAlt;
108700 WhereTerm *pAlt;
108701 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
108702 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
108703 if( pTerm->leftCursor!=iCur ) continue;
108704 if( pLevel->iLeftJoin ) continue;
108705 pE = pTerm->pExpr;
108706 assert( !ExprHasProperty(pE, EP_FromJoin) );
108707 assert( (pTerm->prereqRight & newNotReady)!=0 );
108708 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
108709 if( pAlt==0 ) continue;
108710 if( pAlt->wtFlags & (TERM_CODED) ) continue;
108711 testcase( pAlt->eOperator & WO_EQ );
108712 testcase( pAlt->eOperator & WO_IN );
108713 VdbeNoopComment((v, "begin transitive constraint"));
108714 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
108715 if( pEAlt ){
108716 *pEAlt = *pAlt->pExpr;
108717 pEAlt->pLeft = pE->pLeft;
108718 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
108719 sqlite3StackFree(db, pEAlt);
108723 /* For a LEFT OUTER JOIN, generate code that will record the fact that
108724 ** at least one row of the right table has matched the left table.
108726 if( pLevel->iLeftJoin ){
108727 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
108728 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
108729 VdbeComment((v, "record LEFT JOIN hit"));
108730 sqlite3ExprCacheClear(pParse);
108731 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
108732 testcase( pTerm->wtFlags & TERM_VIRTUAL );
108733 testcase( pTerm->wtFlags & TERM_CODED );
108734 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
108735 if( (pTerm->prereqAll & newNotReady)!=0 ){
108736 assert( pWInfo->untestedTerms );
108737 continue;
108739 assert( pTerm->pExpr );
108740 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
108741 pTerm->wtFlags |= TERM_CODED;
108744 sqlite3ReleaseTempReg(pParse, iReleaseReg);
108746 return newNotReady;
108749 #ifdef WHERETRACE_ENABLED
108751 ** Print a WhereLoop object for debugging purposes
108753 static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
108754 int nb = 1+(pTabList->nSrc+7)/8;
108755 struct SrcList_item *pItem = pTabList->a + p->iTab;
108756 Table *pTab = pItem->pTab;
108757 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
108758 p->iTab, nb, p->maskSelf, nb, p->prereq);
108759 sqlite3DebugPrintf(" %12s",
108760 pItem->zAlias ? pItem->zAlias : pTab->zName);
108761 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
108762 if( p->u.btree.pIndex ){
108763 const char *zName = p->u.btree.pIndex->zName;
108764 if( zName==0 ) zName = "ipk";
108765 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
108766 int i = sqlite3Strlen30(zName) - 1;
108767 while( zName[i]!='_' ) i--;
108768 zName += i;
108770 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
108771 }else{
108772 sqlite3DebugPrintf("%20s","");
108774 }else{
108775 char *z;
108776 if( p->u.vtab.idxStr ){
108777 z = sqlite3_mprintf("(%d,\"%s\",%x)",
108778 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
108779 }else{
108780 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
108782 sqlite3DebugPrintf(" %-19s", z);
108783 sqlite3_free(z);
108785 sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
108786 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
108788 #endif
108791 ** Convert bulk memory into a valid WhereLoop that can be passed
108792 ** to whereLoopClear harmlessly.
108794 static void whereLoopInit(WhereLoop *p){
108795 p->aLTerm = p->aLTermSpace;
108796 p->nLTerm = 0;
108797 p->nLSlot = ArraySize(p->aLTermSpace);
108798 p->wsFlags = 0;
108802 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
108804 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
108805 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
108806 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
108807 sqlite3_free(p->u.vtab.idxStr);
108808 p->u.vtab.needFree = 0;
108809 p->u.vtab.idxStr = 0;
108810 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
108811 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
108812 sqlite3DbFree(db, p->u.btree.pIndex);
108813 p->u.btree.pIndex = 0;
108819 ** Deallocate internal memory used by a WhereLoop object
108821 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
108822 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
108823 whereLoopClearUnion(db, p);
108824 whereLoopInit(p);
108828 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
108830 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
108831 WhereTerm **paNew;
108832 if( p->nLSlot>=n ) return SQLITE_OK;
108833 n = (n+7)&~7;
108834 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
108835 if( paNew==0 ) return SQLITE_NOMEM;
108836 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
108837 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
108838 p->aLTerm = paNew;
108839 p->nLSlot = n;
108840 return SQLITE_OK;
108844 ** Transfer content from the second pLoop into the first.
108846 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
108847 if( whereLoopResize(db, pTo, pFrom->nLTerm) ) return SQLITE_NOMEM;
108848 whereLoopClearUnion(db, pTo);
108849 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
108850 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
108851 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
108852 pFrom->u.vtab.needFree = 0;
108853 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
108854 pFrom->u.btree.pIndex = 0;
108856 return SQLITE_OK;
108860 ** Delete a WhereLoop object
108862 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
108863 whereLoopClear(db, p);
108864 sqlite3DbFree(db, p);
108868 ** Free a WhereInfo structure
108870 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
108871 if( ALWAYS(pWInfo) ){
108872 whereClauseClear(&pWInfo->sWC);
108873 while( pWInfo->pLoops ){
108874 WhereLoop *p = pWInfo->pLoops;
108875 pWInfo->pLoops = p->pNextLoop;
108876 whereLoopDelete(db, p);
108878 sqlite3DbFree(db, pWInfo);
108883 ** Insert or replace a WhereLoop entry using the template supplied.
108885 ** An existing WhereLoop entry might be overwritten if the new template
108886 ** is better and has fewer dependencies. Or the template will be ignored
108887 ** and no insert will occur if an existing WhereLoop is faster and has
108888 ** fewer dependencies than the template. Otherwise a new WhereLoop is
108889 ** added based on the template.
108891 ** If pBuilder->pOrSet is not NULL then we only care about only the
108892 ** prerequisites and rRun and nOut costs of the N best loops. That
108893 ** information is gathered in the pBuilder->pOrSet object. This special
108894 ** processing mode is used only for OR clause processing.
108896 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
108897 ** still might overwrite similar loops with the new template if the
108898 ** template is better. Loops may be overwritten if the following
108899 ** conditions are met:
108901 ** (1) They have the same iTab.
108902 ** (2) They have the same iSortIdx.
108903 ** (3) The template has same or fewer dependencies than the current loop
108904 ** (4) The template has the same or lower cost than the current loop
108905 ** (5) The template uses more terms of the same index but has no additional
108906 ** dependencies
108908 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
108909 WhereLoop **ppPrev, *p, *pNext = 0;
108910 WhereInfo *pWInfo = pBuilder->pWInfo;
108911 sqlite3 *db = pWInfo->pParse->db;
108913 /* If pBuilder->pOrSet is defined, then only keep track of the costs
108914 ** and prereqs.
108916 if( pBuilder->pOrSet!=0 ){
108917 #if WHERETRACE_ENABLED
108918 u16 n = pBuilder->pOrSet->n;
108919 int x =
108920 #endif
108921 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
108922 pTemplate->nOut);
108923 #if WHERETRACE_ENABLED
108924 if( sqlite3WhereTrace & 0x8 ){
108925 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
108926 whereLoopPrint(pTemplate, pWInfo->pTabList);
108928 #endif
108929 return SQLITE_OK;
108932 /* Search for an existing WhereLoop to overwrite, or which takes
108933 ** priority over pTemplate.
108935 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
108936 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
108937 /* If either the iTab or iSortIdx values for two WhereLoop are different
108938 ** then those WhereLoops need to be considered separately. Neither is
108939 ** a candidate to replace the other. */
108940 continue;
108942 /* In the current implementation, the rSetup value is either zero
108943 ** or the cost of building an automatic index (NlogN) and the NlogN
108944 ** is the same for compatible WhereLoops. */
108945 assert( p->rSetup==0 || pTemplate->rSetup==0
108946 || p->rSetup==pTemplate->rSetup );
108948 /* whereLoopAddBtree() always generates and inserts the automatic index
108949 ** case first. Hence compatible candidate WhereLoops never have a larger
108950 ** rSetup. Call this SETUP-INVARIANT */
108951 assert( p->rSetup>=pTemplate->rSetup );
108953 if( (p->prereq & pTemplate->prereq)==p->prereq
108954 && p->rSetup<=pTemplate->rSetup
108955 && p->rRun<=pTemplate->rRun
108957 /* This branch taken when p is equal or better than pTemplate in
108958 ** all of (1) dependences (2) setup-cost, and (3) run-cost. */
108959 assert( p->rSetup==pTemplate->rSetup );
108960 if( p->nLTerm<pTemplate->nLTerm
108961 && (p->wsFlags & WHERE_INDEXED)!=0
108962 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
108963 && p->u.btree.pIndex==pTemplate->u.btree.pIndex
108964 && p->prereq==pTemplate->prereq
108966 /* Overwrite an existing WhereLoop with an similar one that uses
108967 ** more terms of the index */
108968 pNext = p->pNextLoop;
108969 break;
108970 }else{
108971 /* pTemplate is not helpful.
108972 ** Return without changing or adding anything */
108973 goto whereLoopInsert_noop;
108976 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
108977 && p->rRun>=pTemplate->rRun
108978 && ALWAYS(p->rSetup>=pTemplate->rSetup) /* See SETUP-INVARIANT above */
108980 /* Overwrite an existing WhereLoop with a better one: one that is
108981 ** better at one of (1) dependences, (2) setup-cost, or (3) run-cost
108982 ** and is no worse in any of those categories. */
108983 pNext = p->pNextLoop;
108984 break;
108988 /* If we reach this point it means that either p[] should be overwritten
108989 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
108990 ** WhereLoop and insert it.
108992 #if WHERETRACE_ENABLED
108993 if( sqlite3WhereTrace & 0x8 ){
108994 if( p!=0 ){
108995 sqlite3DebugPrintf("ins-del: ");
108996 whereLoopPrint(p, pWInfo->pTabList);
108998 sqlite3DebugPrintf("ins-new: ");
108999 whereLoopPrint(pTemplate, pWInfo->pTabList);
109001 #endif
109002 if( p==0 ){
109003 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
109004 if( p==0 ) return SQLITE_NOMEM;
109005 whereLoopInit(p);
109007 whereLoopXfer(db, p, pTemplate);
109008 p->pNextLoop = pNext;
109009 *ppPrev = p;
109010 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
109011 Index *pIndex = p->u.btree.pIndex;
109012 if( pIndex && pIndex->tnum==0 ){
109013 p->u.btree.pIndex = 0;
109016 return SQLITE_OK;
109018 /* Jump here if the insert is a no-op */
109019 whereLoopInsert_noop:
109020 #if WHERETRACE_ENABLED
109021 if( sqlite3WhereTrace & 0x8 ){
109022 sqlite3DebugPrintf("ins-noop: ");
109023 whereLoopPrint(pTemplate, pWInfo->pTabList);
109025 #endif
109026 return SQLITE_OK;
109030 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
109031 ** Try to match one more.
109033 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
109034 ** INTEGER PRIMARY KEY.
109036 static int whereLoopAddBtreeIndex(
109037 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
109038 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
109039 Index *pProbe, /* An index on pSrc */
109040 WhereCost nInMul /* log(Number of iterations due to IN) */
109042 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
109043 Parse *pParse = pWInfo->pParse; /* Parsing context */
109044 sqlite3 *db = pParse->db; /* Database connection malloc context */
109045 WhereLoop *pNew; /* Template WhereLoop under construction */
109046 WhereTerm *pTerm; /* A WhereTerm under consideration */
109047 int opMask; /* Valid operators for constraints */
109048 WhereScan scan; /* Iterator for WHERE terms */
109049 Bitmask saved_prereq; /* Original value of pNew->prereq */
109050 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
109051 int saved_nEq; /* Original value of pNew->u.btree.nEq */
109052 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
109053 WhereCost saved_nOut; /* Original value of pNew->nOut */
109054 int iCol; /* Index of the column in the table */
109055 int rc = SQLITE_OK; /* Return code */
109056 WhereCost nRowEst; /* Estimated index selectivity */
109057 WhereCost rLogSize; /* Logarithm of table size */
109058 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
109060 pNew = pBuilder->pNew;
109061 if( db->mallocFailed ) return SQLITE_NOMEM;
109063 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
109064 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
109065 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
109066 opMask = WO_LT|WO_LE;
109067 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
109068 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
109069 }else{
109070 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
109072 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
109074 assert( pNew->u.btree.nEq<=pProbe->nColumn );
109075 if( pNew->u.btree.nEq < pProbe->nColumn ){
109076 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
109077 nRowEst = whereCost(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
109078 if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
109079 }else{
109080 iCol = -1;
109081 nRowEst = 0;
109083 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
109084 opMask, pProbe);
109085 saved_nEq = pNew->u.btree.nEq;
109086 saved_nLTerm = pNew->nLTerm;
109087 saved_wsFlags = pNew->wsFlags;
109088 saved_prereq = pNew->prereq;
109089 saved_nOut = pNew->nOut;
109090 pNew->rSetup = 0;
109091 rLogSize = estLog(whereCost(pProbe->aiRowEst[0]));
109092 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
109093 int nIn = 0;
109094 if( pTerm->prereqRight & pNew->maskSelf ) continue;
109095 if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
109096 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
109098 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
109100 pNew->wsFlags = saved_wsFlags;
109101 pNew->u.btree.nEq = saved_nEq;
109102 pNew->nLTerm = saved_nLTerm;
109103 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
109104 pNew->aLTerm[pNew->nLTerm++] = pTerm;
109105 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
109106 pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
109107 if( pTerm->eOperator & WO_IN ){
109108 Expr *pExpr = pTerm->pExpr;
109109 pNew->wsFlags |= WHERE_COLUMN_IN;
109110 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
109111 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
109112 nIn = 46; assert( 46==whereCost(25) );
109113 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
109114 /* "x IN (value, value, ...)" */
109115 nIn = whereCost(pExpr->x.pList->nExpr);
109117 pNew->rRun += nIn;
109118 pNew->u.btree.nEq++;
109119 pNew->nOut = nRowEst + nInMul + nIn;
109120 }else if( pTerm->eOperator & (WO_EQ) ){
109121 assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
109122 || nInMul==0 );
109123 pNew->wsFlags |= WHERE_COLUMN_EQ;
109124 if( iCol<0
109125 || (pProbe->onError!=OE_None && nInMul==0
109126 && pNew->u.btree.nEq==pProbe->nColumn-1)
109128 assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
109129 pNew->wsFlags |= WHERE_ONEROW;
109131 pNew->u.btree.nEq++;
109132 pNew->nOut = nRowEst + nInMul;
109133 }else if( pTerm->eOperator & (WO_ISNULL) ){
109134 pNew->wsFlags |= WHERE_COLUMN_NULL;
109135 pNew->u.btree.nEq++;
109136 /* TUNING: IS NULL selects 2 rows */
109137 nIn = 10; assert( 10==whereCost(2) );
109138 pNew->nOut = nRowEst + nInMul + nIn;
109139 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
109140 testcase( pTerm->eOperator & WO_GT );
109141 testcase( pTerm->eOperator & WO_GE );
109142 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
109143 pBtm = pTerm;
109144 pTop = 0;
109145 }else{
109146 assert( pTerm->eOperator & (WO_LT|WO_LE) );
109147 testcase( pTerm->eOperator & WO_LT );
109148 testcase( pTerm->eOperator & WO_LE );
109149 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
109150 pTop = pTerm;
109151 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
109152 pNew->aLTerm[pNew->nLTerm-2] : 0;
109154 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
109155 /* Adjust nOut and rRun for STAT3 range values */
109156 WhereCost rDiv;
109157 whereRangeScanEst(pParse, pProbe, pNew->u.btree.nEq,
109158 pBtm, pTop, &rDiv);
109159 pNew->nOut = saved_nOut>rDiv+10 ? saved_nOut - rDiv : 10;
109161 #ifdef SQLITE_ENABLE_STAT3
109162 if( pNew->u.btree.nEq==1 && pProbe->nSample
109163 && OptimizationEnabled(db, SQLITE_Stat3) ){
109164 tRowcnt nOut = 0;
109165 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
109166 testcase( pTerm->eOperator & WO_EQ );
109167 testcase( pTerm->eOperator & WO_ISNULL );
109168 rc = whereEqualScanEst(pParse, pProbe, pTerm->pExpr->pRight, &nOut);
109169 }else if( (pTerm->eOperator & WO_IN)
109170 && !ExprHasProperty(pTerm->pExpr, EP_xIsSelect) ){
109171 rc = whereInScanEst(pParse, pProbe, pTerm->pExpr->x.pList, &nOut);
109173 assert( nOut==0 || rc==SQLITE_OK );
109174 if( nOut ) pNew->nOut = whereCost(nOut);
109176 #endif
109177 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
109178 /* Each row involves a step of the index, then a binary search of
109179 ** the main table */
109180 pNew->rRun = whereCostAdd(pNew->rRun, rLogSize>27 ? rLogSize-17 : 10);
109182 /* Step cost for each output row */
109183 pNew->rRun = whereCostAdd(pNew->rRun, pNew->nOut);
109184 /* TBD: Adjust nOut for additional constraints */
109185 rc = whereLoopInsert(pBuilder, pNew);
109186 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
109187 && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
109189 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
109192 pNew->prereq = saved_prereq;
109193 pNew->u.btree.nEq = saved_nEq;
109194 pNew->wsFlags = saved_wsFlags;
109195 pNew->nOut = saved_nOut;
109196 pNew->nLTerm = saved_nLTerm;
109197 return rc;
109201 ** Return True if it is possible that pIndex might be useful in
109202 ** implementing the ORDER BY clause in pBuilder.
109204 ** Return False if pBuilder does not contain an ORDER BY clause or
109205 ** if there is no way for pIndex to be useful in implementing that
109206 ** ORDER BY clause.
109208 static int indexMightHelpWithOrderBy(
109209 WhereLoopBuilder *pBuilder,
109210 Index *pIndex,
109211 int iCursor
109213 ExprList *pOB;
109214 int ii, jj;
109216 if( pIndex->bUnordered ) return 0;
109217 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
109218 for(ii=0; ii<pOB->nExpr; ii++){
109219 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
109220 if( pExpr->op!=TK_COLUMN ) return 0;
109221 if( pExpr->iTable==iCursor ){
109222 for(jj=0; jj<pIndex->nColumn; jj++){
109223 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
109227 return 0;
109231 ** Return a bitmask where 1s indicate that the corresponding column of
109232 ** the table is used by an index. Only the first 63 columns are considered.
109234 static Bitmask columnsInIndex(Index *pIdx){
109235 Bitmask m = 0;
109236 int j;
109237 for(j=pIdx->nColumn-1; j>=0; j--){
109238 int x = pIdx->aiColumn[j];
109239 assert( x>=0 );
109240 testcase( x==BMS-1 );
109241 testcase( x==BMS-2 );
109242 if( x<BMS-1 ) m |= MASKBIT(x);
109244 return m;
109247 /* Check to see if a partial index with pPartIndexWhere can be used
109248 ** in the current query. Return true if it can be and false if not.
109250 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
109251 int i;
109252 WhereTerm *pTerm;
109253 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
109254 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
109256 return 0;
109260 ** Add all WhereLoop objects for a single table of the join where the table
109261 ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
109262 ** a b-tree table, not a virtual table.
109264 static int whereLoopAddBtree(
109265 WhereLoopBuilder *pBuilder, /* WHERE clause information */
109266 Bitmask mExtra /* Extra prerequesites for using this table */
109268 WhereInfo *pWInfo; /* WHERE analysis context */
109269 Index *pProbe; /* An index we are evaluating */
109270 Index sPk; /* A fake index object for the primary key */
109271 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
109272 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
109273 SrcList *pTabList; /* The FROM clause */
109274 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
109275 WhereLoop *pNew; /* Template WhereLoop object */
109276 int rc = SQLITE_OK; /* Return code */
109277 int iSortIdx = 1; /* Index number */
109278 int b; /* A boolean value */
109279 WhereCost rSize; /* number of rows in the table */
109280 WhereCost rLogSize; /* Logarithm of the number of rows in the table */
109281 WhereClause *pWC; /* The parsed WHERE clause */
109283 pNew = pBuilder->pNew;
109284 pWInfo = pBuilder->pWInfo;
109285 pTabList = pWInfo->pTabList;
109286 pSrc = pTabList->a + pNew->iTab;
109287 pWC = pBuilder->pWC;
109288 assert( !IsVirtual(pSrc->pTab) );
109290 if( pSrc->pIndex ){
109291 /* An INDEXED BY clause specifies a particular index to use */
109292 pProbe = pSrc->pIndex;
109293 }else{
109294 /* There is no INDEXED BY clause. Create a fake Index object in local
109295 ** variable sPk to represent the rowid primary key index. Make this
109296 ** fake index the first in a chain of Index objects with all of the real
109297 ** indices to follow */
109298 Index *pFirst; /* First of real indices on the table */
109299 memset(&sPk, 0, sizeof(Index));
109300 sPk.nColumn = 1;
109301 sPk.aiColumn = &aiColumnPk;
109302 sPk.aiRowEst = aiRowEstPk;
109303 sPk.onError = OE_Replace;
109304 sPk.pTable = pSrc->pTab;
109305 aiRowEstPk[0] = pSrc->pTab->nRowEst;
109306 aiRowEstPk[1] = 1;
109307 pFirst = pSrc->pTab->pIndex;
109308 if( pSrc->notIndexed==0 ){
109309 /* The real indices of the table are only considered if the
109310 ** NOT INDEXED qualifier is omitted from the FROM clause */
109311 sPk.pNext = pFirst;
109313 pProbe = &sPk;
109315 rSize = whereCost(pSrc->pTab->nRowEst);
109316 rLogSize = estLog(rSize);
109318 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
109319 /* Automatic indexes */
109320 if( !pBuilder->pOrSet
109321 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
109322 && pSrc->pIndex==0
109323 && !pSrc->viaCoroutine
109324 && !pSrc->notIndexed
109325 && !pSrc->isCorrelated
109327 /* Generate auto-index WhereLoops */
109328 WhereTerm *pTerm;
109329 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
109330 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
109331 if( pTerm->prereqRight & pNew->maskSelf ) continue;
109332 if( termCanDriveIndex(pTerm, pSrc, 0) ){
109333 pNew->u.btree.nEq = 1;
109334 pNew->u.btree.pIndex = 0;
109335 pNew->nLTerm = 1;
109336 pNew->aLTerm[0] = pTerm;
109337 /* TUNING: One-time cost for computing the automatic index is
109338 ** approximately 7*N*log2(N) where N is the number of rows in
109339 ** the table being indexed. */
109340 pNew->rSetup = rLogSize + rSize + 28; assert( 28==whereCost(7) );
109341 /* TUNING: Each index lookup yields 20 rows in the table. This
109342 ** is more than the usual guess of 10 rows, since we have no way
109343 ** of knowning how selective the index will ultimately be. It would
109344 ** not be unreasonable to make this value much larger. */
109345 pNew->nOut = 43; assert( 43==whereCost(20) );
109346 pNew->rRun = whereCostAdd(rLogSize,pNew->nOut);
109347 pNew->wsFlags = WHERE_AUTO_INDEX;
109348 pNew->prereq = mExtra | pTerm->prereqRight;
109349 rc = whereLoopInsert(pBuilder, pNew);
109353 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
109355 /* Loop over all indices
109357 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
109358 if( pProbe->pPartIdxWhere!=0
109359 && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
109360 continue; /* Partial index inappropriate for this query */
109362 pNew->u.btree.nEq = 0;
109363 pNew->nLTerm = 0;
109364 pNew->iSortIdx = 0;
109365 pNew->rSetup = 0;
109366 pNew->prereq = mExtra;
109367 pNew->nOut = rSize;
109368 pNew->u.btree.pIndex = pProbe;
109369 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
109370 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
109371 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
109372 if( pProbe->tnum<=0 ){
109373 /* Integer primary key index */
109374 pNew->wsFlags = WHERE_IPK;
109376 /* Full table scan */
109377 pNew->iSortIdx = b ? iSortIdx : 0;
109378 /* TUNING: Cost of full table scan is 3*(N + log2(N)).
109379 ** + The extra 3 factor is to encourage the use of indexed lookups
109380 ** over full scans. A smaller constant 2 is used for covering
109381 ** index scans so that a covering index scan will be favored over
109382 ** a table scan. */
109383 pNew->rRun = whereCostAdd(rSize,rLogSize) + 16;
109384 rc = whereLoopInsert(pBuilder, pNew);
109385 if( rc ) break;
109386 }else{
109387 Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
109388 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
109390 /* Full scan via index */
109391 if( b
109392 || ( m==0
109393 && pProbe->bUnordered==0
109394 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
109395 && sqlite3GlobalConfig.bUseCis
109396 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
109399 pNew->iSortIdx = b ? iSortIdx : 0;
109400 if( m==0 ){
109401 /* TUNING: Cost of a covering index scan is 2*(N + log2(N)).
109402 ** + The extra 2 factor is to encourage the use of indexed lookups
109403 ** over index scans. A table scan uses a factor of 3 so that
109404 ** index scans are favored over table scans.
109405 ** + If this covering index might also help satisfy the ORDER BY
109406 ** clause, then the cost is fudged down slightly so that this
109407 ** index is favored above other indices that have no hope of
109408 ** helping with the ORDER BY. */
109409 pNew->rRun = 10 + whereCostAdd(rSize,rLogSize) - b;
109410 }else{
109411 assert( b!=0 );
109412 /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
109413 ** which we will simplify to just N*log2(N) */
109414 pNew->rRun = rSize + rLogSize;
109416 rc = whereLoopInsert(pBuilder, pNew);
109417 if( rc ) break;
109420 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
109422 /* If there was an INDEXED BY clause, then only that one index is
109423 ** considered. */
109424 if( pSrc->pIndex ) break;
109426 return rc;
109429 #ifndef SQLITE_OMIT_VIRTUALTABLE
109431 ** Add all WhereLoop objects for a table of the join identified by
109432 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
109434 static int whereLoopAddVirtual(
109435 WhereLoopBuilder *pBuilder /* WHERE clause information */
109437 WhereInfo *pWInfo; /* WHERE analysis context */
109438 Parse *pParse; /* The parsing context */
109439 WhereClause *pWC; /* The WHERE clause */
109440 struct SrcList_item *pSrc; /* The FROM clause term to search */
109441 Table *pTab;
109442 sqlite3 *db;
109443 sqlite3_index_info *pIdxInfo;
109444 struct sqlite3_index_constraint *pIdxCons;
109445 struct sqlite3_index_constraint_usage *pUsage;
109446 WhereTerm *pTerm;
109447 int i, j;
109448 int iTerm, mxTerm;
109449 int nConstraint;
109450 int seenIn = 0; /* True if an IN operator is seen */
109451 int seenVar = 0; /* True if a non-constant constraint is seen */
109452 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
109453 WhereLoop *pNew;
109454 int rc = SQLITE_OK;
109456 pWInfo = pBuilder->pWInfo;
109457 pParse = pWInfo->pParse;
109458 db = pParse->db;
109459 pWC = pBuilder->pWC;
109460 pNew = pBuilder->pNew;
109461 pSrc = &pWInfo->pTabList->a[pNew->iTab];
109462 pTab = pSrc->pTab;
109463 assert( IsVirtual(pTab) );
109464 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
109465 if( pIdxInfo==0 ) return SQLITE_NOMEM;
109466 pNew->prereq = 0;
109467 pNew->rSetup = 0;
109468 pNew->wsFlags = WHERE_VIRTUALTABLE;
109469 pNew->nLTerm = 0;
109470 pNew->u.vtab.needFree = 0;
109471 pUsage = pIdxInfo->aConstraintUsage;
109472 nConstraint = pIdxInfo->nConstraint;
109473 if( whereLoopResize(db, pNew, nConstraint) ){
109474 sqlite3DbFree(db, pIdxInfo);
109475 return SQLITE_NOMEM;
109478 for(iPhase=0; iPhase<=3; iPhase++){
109479 if( !seenIn && (iPhase&1)!=0 ){
109480 iPhase++;
109481 if( iPhase>3 ) break;
109483 if( !seenVar && iPhase>1 ) break;
109484 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
109485 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
109486 j = pIdxCons->iTermOffset;
109487 pTerm = &pWC->a[j];
109488 switch( iPhase ){
109489 case 0: /* Constants without IN operator */
109490 pIdxCons->usable = 0;
109491 if( (pTerm->eOperator & WO_IN)!=0 ){
109492 seenIn = 1;
109494 if( pTerm->prereqRight!=0 ){
109495 seenVar = 1;
109496 }else if( (pTerm->eOperator & WO_IN)==0 ){
109497 pIdxCons->usable = 1;
109499 break;
109500 case 1: /* Constants with IN operators */
109501 assert( seenIn );
109502 pIdxCons->usable = (pTerm->prereqRight==0);
109503 break;
109504 case 2: /* Variables without IN */
109505 assert( seenVar );
109506 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
109507 break;
109508 default: /* Variables with IN */
109509 assert( seenVar && seenIn );
109510 pIdxCons->usable = 1;
109511 break;
109514 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
109515 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
109516 pIdxInfo->idxStr = 0;
109517 pIdxInfo->idxNum = 0;
109518 pIdxInfo->needToFreeIdxStr = 0;
109519 pIdxInfo->orderByConsumed = 0;
109520 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
109521 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
109522 if( rc ) goto whereLoopAddVtab_exit;
109523 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
109524 pNew->prereq = 0;
109525 mxTerm = -1;
109526 assert( pNew->nLSlot>=nConstraint );
109527 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
109528 pNew->u.vtab.omitMask = 0;
109529 for(i=0; i<nConstraint; i++, pIdxCons++){
109530 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
109531 j = pIdxCons->iTermOffset;
109532 if( iTerm>=nConstraint
109533 || j<0
109534 || j>=pWC->nTerm
109535 || pNew->aLTerm[iTerm]!=0
109537 rc = SQLITE_ERROR;
109538 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
109539 goto whereLoopAddVtab_exit;
109541 testcase( iTerm==nConstraint-1 );
109542 testcase( j==0 );
109543 testcase( j==pWC->nTerm-1 );
109544 pTerm = &pWC->a[j];
109545 pNew->prereq |= pTerm->prereqRight;
109546 assert( iTerm<pNew->nLSlot );
109547 pNew->aLTerm[iTerm] = pTerm;
109548 if( iTerm>mxTerm ) mxTerm = iTerm;
109549 testcase( iTerm==15 );
109550 testcase( iTerm==16 );
109551 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
109552 if( (pTerm->eOperator & WO_IN)!=0 ){
109553 if( pUsage[i].omit==0 ){
109554 /* Do not attempt to use an IN constraint if the virtual table
109555 ** says that the equivalent EQ constraint cannot be safely omitted.
109556 ** If we do attempt to use such a constraint, some rows might be
109557 ** repeated in the output. */
109558 break;
109560 /* A virtual table that is constrained by an IN clause may not
109561 ** consume the ORDER BY clause because (1) the order of IN terms
109562 ** is not necessarily related to the order of output terms and
109563 ** (2) Multiple outputs from a single IN value will not merge
109564 ** together. */
109565 pIdxInfo->orderByConsumed = 0;
109569 if( i>=nConstraint ){
109570 pNew->nLTerm = mxTerm+1;
109571 assert( pNew->nLTerm<=pNew->nLSlot );
109572 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
109573 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
109574 pIdxInfo->needToFreeIdxStr = 0;
109575 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
109576 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
109577 && pIdxInfo->orderByConsumed);
109578 pNew->rSetup = 0;
109579 pNew->rRun = whereCostFromDouble(pIdxInfo->estimatedCost);
109580 /* TUNING: Every virtual table query returns 25 rows */
109581 pNew->nOut = 46; assert( 46==whereCost(25) );
109582 whereLoopInsert(pBuilder, pNew);
109583 if( pNew->u.vtab.needFree ){
109584 sqlite3_free(pNew->u.vtab.idxStr);
109585 pNew->u.vtab.needFree = 0;
109590 whereLoopAddVtab_exit:
109591 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
109592 sqlite3DbFree(db, pIdxInfo);
109593 return rc;
109595 #endif /* SQLITE_OMIT_VIRTUALTABLE */
109598 ** Add WhereLoop entries to handle OR terms. This works for either
109599 ** btrees or virtual tables.
109601 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
109602 WhereInfo *pWInfo = pBuilder->pWInfo;
109603 WhereClause *pWC;
109604 WhereLoop *pNew;
109605 WhereTerm *pTerm, *pWCEnd;
109606 int rc = SQLITE_OK;
109607 int iCur;
109608 WhereClause tempWC;
109609 WhereLoopBuilder sSubBuild;
109610 WhereOrSet sSum, sCur, sPrev;
109611 struct SrcList_item *pItem;
109613 pWC = pBuilder->pWC;
109614 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
109615 pWCEnd = pWC->a + pWC->nTerm;
109616 pNew = pBuilder->pNew;
109617 memset(&sSum, 0, sizeof(sSum));
109619 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
109620 if( (pTerm->eOperator & WO_OR)!=0
109621 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
109623 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
109624 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
109625 WhereTerm *pOrTerm;
109626 int once = 1;
109627 int i, j;
109629 pItem = pWInfo->pTabList->a + pNew->iTab;
109630 iCur = pItem->iCursor;
109631 sSubBuild = *pBuilder;
109632 sSubBuild.pOrderBy = 0;
109633 sSubBuild.pOrSet = &sCur;
109635 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
109636 if( (pOrTerm->eOperator & WO_AND)!=0 ){
109637 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
109638 }else if( pOrTerm->leftCursor==iCur ){
109639 tempWC.pWInfo = pWC->pWInfo;
109640 tempWC.pOuter = pWC;
109641 tempWC.op = TK_AND;
109642 tempWC.nTerm = 1;
109643 tempWC.a = pOrTerm;
109644 sSubBuild.pWC = &tempWC;
109645 }else{
109646 continue;
109648 sCur.n = 0;
109649 #ifndef SQLITE_OMIT_VIRTUALTABLE
109650 if( IsVirtual(pItem->pTab) ){
109651 rc = whereLoopAddVirtual(&sSubBuild);
109652 for(i=0; i<sCur.n; i++) sCur.a[i].prereq |= mExtra;
109653 }else
109654 #endif
109656 rc = whereLoopAddBtree(&sSubBuild, mExtra);
109658 assert( rc==SQLITE_OK || sCur.n==0 );
109659 if( sCur.n==0 ){
109660 sSum.n = 0;
109661 break;
109662 }else if( once ){
109663 whereOrMove(&sSum, &sCur);
109664 once = 0;
109665 }else{
109666 whereOrMove(&sPrev, &sSum);
109667 sSum.n = 0;
109668 for(i=0; i<sPrev.n; i++){
109669 for(j=0; j<sCur.n; j++){
109670 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
109671 whereCostAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
109672 whereCostAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
109677 pNew->nLTerm = 1;
109678 pNew->aLTerm[0] = pTerm;
109679 pNew->wsFlags = WHERE_MULTI_OR;
109680 pNew->rSetup = 0;
109681 pNew->iSortIdx = 0;
109682 memset(&pNew->u, 0, sizeof(pNew->u));
109683 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
109684 /* TUNING: Multiple by 3.5 for the secondary table lookup */
109685 pNew->rRun = sSum.a[i].rRun + 18;
109686 pNew->nOut = sSum.a[i].nOut;
109687 pNew->prereq = sSum.a[i].prereq;
109688 rc = whereLoopInsert(pBuilder, pNew);
109692 return rc;
109696 ** Add all WhereLoop objects for all tables
109698 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
109699 WhereInfo *pWInfo = pBuilder->pWInfo;
109700 Bitmask mExtra = 0;
109701 Bitmask mPrior = 0;
109702 int iTab;
109703 SrcList *pTabList = pWInfo->pTabList;
109704 struct SrcList_item *pItem;
109705 sqlite3 *db = pWInfo->pParse->db;
109706 int nTabList = pWInfo->nLevel;
109707 int rc = SQLITE_OK;
109708 u8 priorJoinType = 0;
109709 WhereLoop *pNew;
109711 /* Loop over the tables in the join, from left to right */
109712 pNew = pBuilder->pNew;
109713 whereLoopInit(pNew);
109714 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
109715 pNew->iTab = iTab;
109716 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
109717 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
109718 mExtra = mPrior;
109720 priorJoinType = pItem->jointype;
109721 if( IsVirtual(pItem->pTab) ){
109722 rc = whereLoopAddVirtual(pBuilder);
109723 }else{
109724 rc = whereLoopAddBtree(pBuilder, mExtra);
109726 if( rc==SQLITE_OK ){
109727 rc = whereLoopAddOr(pBuilder, mExtra);
109729 mPrior |= pNew->maskSelf;
109730 if( rc || db->mallocFailed ) break;
109732 whereLoopClear(db, pNew);
109733 return rc;
109737 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
109738 ** parameters) to see if it outputs rows in the requested ORDER BY
109739 ** (or GROUP BY) without requiring a separate sort operation. Return:
109741 ** 0: ORDER BY is not satisfied. Sorting required
109742 ** 1: ORDER BY is satisfied. Omit sorting
109743 ** -1: Unknown at this time
109745 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
109746 ** strict. With GROUP BY and DISTINCT the only requirement is that
109747 ** equivalent rows appear immediately adjacent to one another. GROUP BY
109748 ** and DISTINT do not require rows to appear in any particular order as long
109749 ** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
109750 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
109751 ** pOrderBy terms must be matched in strict left-to-right order.
109753 static int wherePathSatisfiesOrderBy(
109754 WhereInfo *pWInfo, /* The WHERE clause */
109755 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
109756 WherePath *pPath, /* The WherePath to check */
109757 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
109758 u16 nLoop, /* Number of entries in pPath->aLoop[] */
109759 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
109760 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
109762 u8 revSet; /* True if rev is known */
109763 u8 rev; /* Composite sort order */
109764 u8 revIdx; /* Index sort order */
109765 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
109766 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
109767 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
109768 u16 nColumn; /* Number of columns in pIndex */
109769 u16 nOrderBy; /* Number terms in the ORDER BY clause */
109770 int iLoop; /* Index of WhereLoop in pPath being processed */
109771 int i, j; /* Loop counters */
109772 int iCur; /* Cursor number for current WhereLoop */
109773 int iColumn; /* A column number within table iCur */
109774 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
109775 WhereTerm *pTerm; /* A single term of the WHERE clause */
109776 Expr *pOBExpr; /* An expression from the ORDER BY clause */
109777 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
109778 Index *pIndex; /* The index associated with pLoop */
109779 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
109780 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
109781 Bitmask obDone; /* Mask of all ORDER BY terms */
109782 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
109783 Bitmask ready; /* Mask of inner loops */
109786 ** We say the WhereLoop is "one-row" if it generates no more than one
109787 ** row of output. A WhereLoop is one-row if all of the following are true:
109788 ** (a) All index columns match with WHERE_COLUMN_EQ.
109789 ** (b) The index is unique
109790 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
109791 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
109793 ** We say the WhereLoop is "order-distinct" if the set of columns from
109794 ** that WhereLoop that are in the ORDER BY clause are different for every
109795 ** row of the WhereLoop. Every one-row WhereLoop is automatically
109796 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
109797 ** is not order-distinct. To be order-distinct is not quite the same as being
109798 ** UNIQUE since a UNIQUE column or index can have multiple rows that
109799 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
109800 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
109802 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
109803 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
109804 ** automatically order-distinct.
109807 assert( pOrderBy!=0 );
109809 /* Sortability of virtual tables is determined by the xBestIndex method
109810 ** of the virtual table itself */
109811 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
109812 testcase( nLoop>0 ); /* True when outer loops are one-row and match
109813 ** no ORDER BY terms */
109814 return pLast->u.vtab.isOrdered;
109816 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
109818 nOrderBy = pOrderBy->nExpr;
109819 testcase( nOrderBy==BMS-1 );
109820 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
109821 isOrderDistinct = 1;
109822 obDone = MASKBIT(nOrderBy)-1;
109823 orderDistinctMask = 0;
109824 ready = 0;
109825 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
109826 if( iLoop>0 ) ready |= pLoop->maskSelf;
109827 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
109828 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
109829 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
109831 /* Mark off any ORDER BY term X that is a column in the table of
109832 ** the current loop for which there is term in the WHERE
109833 ** clause of the form X IS NULL or X=? that reference only outer
109834 ** loops.
109836 for(i=0; i<nOrderBy; i++){
109837 if( MASKBIT(i) & obSat ) continue;
109838 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
109839 if( pOBExpr->op!=TK_COLUMN ) continue;
109840 if( pOBExpr->iTable!=iCur ) continue;
109841 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
109842 ~ready, WO_EQ|WO_ISNULL, 0);
109843 if( pTerm==0 ) continue;
109844 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
109845 const char *z1, *z2;
109846 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
109847 if( !pColl ) pColl = db->pDfltColl;
109848 z1 = pColl->zName;
109849 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
109850 if( !pColl ) pColl = db->pDfltColl;
109851 z2 = pColl->zName;
109852 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
109854 obSat |= MASKBIT(i);
109857 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
109858 if( pLoop->wsFlags & WHERE_IPK ){
109859 pIndex = 0;
109860 nColumn = 0;
109861 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
109862 return 0;
109863 }else{
109864 nColumn = pIndex->nColumn;
109865 isOrderDistinct = pIndex->onError!=OE_None;
109868 /* Loop through all columns of the index and deal with the ones
109869 ** that are not constrained by == or IN.
109871 rev = revSet = 0;
109872 distinctColumns = 0;
109873 for(j=0; j<=nColumn; j++){
109874 u8 bOnce; /* True to run the ORDER BY search loop */
109876 /* Skip over == and IS NULL terms */
109877 if( j<pLoop->u.btree.nEq
109878 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
109880 if( i & WO_ISNULL ){
109881 testcase( isOrderDistinct );
109882 isOrderDistinct = 0;
109884 continue;
109887 /* Get the column number in the table (iColumn) and sort order
109888 ** (revIdx) for the j-th column of the index.
109890 if( j<nColumn ){
109891 /* Normal index columns */
109892 iColumn = pIndex->aiColumn[j];
109893 revIdx = pIndex->aSortOrder[j];
109894 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
109895 }else{
109896 /* The ROWID column at the end */
109897 assert( j==nColumn );
109898 iColumn = -1;
109899 revIdx = 0;
109902 /* An unconstrained column that might be NULL means that this
109903 ** WhereLoop is not well-ordered
109905 if( isOrderDistinct
109906 && iColumn>=0
109907 && j>=pLoop->u.btree.nEq
109908 && pIndex->pTable->aCol[iColumn].notNull==0
109910 isOrderDistinct = 0;
109913 /* Find the ORDER BY term that corresponds to the j-th column
109914 ** of the index and and mark that ORDER BY term off
109916 bOnce = 1;
109917 isMatch = 0;
109918 for(i=0; bOnce && i<nOrderBy; i++){
109919 if( MASKBIT(i) & obSat ) continue;
109920 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
109921 testcase( wctrlFlags & WHERE_GROUPBY );
109922 testcase( wctrlFlags & WHERE_DISTINCTBY );
109923 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
109924 if( pOBExpr->op!=TK_COLUMN ) continue;
109925 if( pOBExpr->iTable!=iCur ) continue;
109926 if( pOBExpr->iColumn!=iColumn ) continue;
109927 if( iColumn>=0 ){
109928 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
109929 if( !pColl ) pColl = db->pDfltColl;
109930 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
109932 isMatch = 1;
109933 break;
109935 if( isMatch ){
109936 if( iColumn<0 ){
109937 testcase( distinctColumns==0 );
109938 distinctColumns = 1;
109940 obSat |= MASKBIT(i);
109941 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
109942 /* Make sure the sort order is compatible in an ORDER BY clause.
109943 ** Sort order is irrelevant for a GROUP BY clause. */
109944 if( revSet ){
109945 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
109946 }else{
109947 rev = revIdx ^ pOrderBy->a[i].sortOrder;
109948 if( rev ) *pRevMask |= MASKBIT(iLoop);
109949 revSet = 1;
109952 }else{
109953 /* No match found */
109954 if( j==0 || j<nColumn ){
109955 testcase( isOrderDistinct!=0 );
109956 isOrderDistinct = 0;
109958 break;
109960 } /* end Loop over all index columns */
109961 if( distinctColumns ){
109962 testcase( isOrderDistinct==0 );
109963 isOrderDistinct = 1;
109965 } /* end-if not one-row */
109967 /* Mark off any other ORDER BY terms that reference pLoop */
109968 if( isOrderDistinct ){
109969 orderDistinctMask |= pLoop->maskSelf;
109970 for(i=0; i<nOrderBy; i++){
109971 Expr *p;
109972 if( MASKBIT(i) & obSat ) continue;
109973 p = pOrderBy->a[i].pExpr;
109974 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
109975 obSat |= MASKBIT(i);
109979 } /* End the loop over all WhereLoops from outer-most down to inner-most */
109980 if( obSat==obDone ) return 1;
109981 if( !isOrderDistinct ) return 0;
109982 return -1;
109985 #ifdef WHERETRACE_ENABLED
109986 /* For debugging use only: */
109987 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
109988 static char zName[65];
109989 int i;
109990 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
109991 if( pLast ) zName[i++] = pLast->cId;
109992 zName[i] = 0;
109993 return zName;
109995 #endif
109999 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
110000 ** attempts to find the lowest cost path that visits each WhereLoop
110001 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
110003 ** Assume that the total number of output rows that will need to be sorted
110004 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
110005 ** costs if nRowEst==0.
110007 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
110008 ** error occurs.
110010 static int wherePathSolver(WhereInfo *pWInfo, WhereCost nRowEst){
110011 int mxChoice; /* Maximum number of simultaneous paths tracked */
110012 int nLoop; /* Number of terms in the join */
110013 Parse *pParse; /* Parsing context */
110014 sqlite3 *db; /* The database connection */
110015 int iLoop; /* Loop counter over the terms of the join */
110016 int ii, jj; /* Loop counters */
110017 WhereCost rCost; /* Cost of a path */
110018 WhereCost mxCost = 0; /* Maximum cost of a set of paths */
110019 WhereCost rSortCost; /* Cost to do a sort */
110020 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
110021 WherePath *aFrom; /* All nFrom paths at the previous level */
110022 WherePath *aTo; /* The nTo best paths at the current level */
110023 WherePath *pFrom; /* An element of aFrom[] that we are working on */
110024 WherePath *pTo; /* An element of aTo[] that we are working on */
110025 WhereLoop *pWLoop; /* One of the WhereLoop objects */
110026 WhereLoop **pX; /* Used to divy up the pSpace memory */
110027 char *pSpace; /* Temporary memory used by this routine */
110029 pParse = pWInfo->pParse;
110030 db = pParse->db;
110031 nLoop = pWInfo->nLevel;
110032 /* TUNING: For simple queries, only the best path is tracked.
110033 ** For 2-way joins, the 5 best paths are followed.
110034 ** For joins of 3 or more tables, track the 10 best paths */
110035 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
110036 assert( nLoop<=pWInfo->pTabList->nSrc );
110037 WHERETRACE(0x002, ("---- begin solver\n"));
110039 /* Allocate and initialize space for aTo and aFrom */
110040 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
110041 pSpace = sqlite3DbMallocRaw(db, ii);
110042 if( pSpace==0 ) return SQLITE_NOMEM;
110043 aTo = (WherePath*)pSpace;
110044 aFrom = aTo+mxChoice;
110045 memset(aFrom, 0, sizeof(aFrom[0]));
110046 pX = (WhereLoop**)(aFrom+mxChoice);
110047 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
110048 pFrom->aLoop = pX;
110051 /* Seed the search with a single WherePath containing zero WhereLoops.
110053 ** TUNING: Do not let the number of iterations go above 25. If the cost
110054 ** of computing an automatic index is not paid back within the first 25
110055 ** rows, then do not use the automatic index. */
110056 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==whereCost(25) );
110057 nFrom = 1;
110059 /* Precompute the cost of sorting the final result set, if the caller
110060 ** to sqlite3WhereBegin() was concerned about sorting */
110061 rSortCost = 0;
110062 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
110063 aFrom[0].isOrderedValid = 1;
110064 }else{
110065 /* TUNING: Estimated cost of sorting is N*log2(N) where N is the
110066 ** number of output rows. */
110067 rSortCost = nRowEst + estLog(nRowEst);
110068 WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
110071 /* Compute successively longer WherePaths using the previous generation
110072 ** of WherePaths as the basis for the next. Keep track of the mxChoice
110073 ** best paths at each generation */
110074 for(iLoop=0; iLoop<nLoop; iLoop++){
110075 nTo = 0;
110076 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
110077 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
110078 Bitmask maskNew;
110079 Bitmask revMask = 0;
110080 u8 isOrderedValid = pFrom->isOrderedValid;
110081 u8 isOrdered = pFrom->isOrdered;
110082 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
110083 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
110084 /* At this point, pWLoop is a candidate to be the next loop.
110085 ** Compute its cost */
110086 rCost = whereCostAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
110087 rCost = whereCostAdd(rCost, pFrom->rCost);
110088 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
110089 if( !isOrderedValid ){
110090 switch( wherePathSatisfiesOrderBy(pWInfo,
110091 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
110092 iLoop, pWLoop, &revMask) ){
110093 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
110094 isOrdered = 1;
110095 isOrderedValid = 1;
110096 break;
110097 case 0: /* No. pFrom+pWLoop will require a separate sort */
110098 isOrdered = 0;
110099 isOrderedValid = 1;
110100 rCost = whereCostAdd(rCost, rSortCost);
110101 break;
110102 default: /* Cannot tell yet. Try again on the next iteration */
110103 break;
110105 }else{
110106 revMask = pFrom->revLoop;
110108 /* Check to see if pWLoop should be added to the mxChoice best so far */
110109 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
110110 if( pTo->maskLoop==maskNew && pTo->isOrderedValid==isOrderedValid ){
110111 testcase( jj==nTo-1 );
110112 break;
110115 if( jj>=nTo ){
110116 if( nTo>=mxChoice && rCost>=mxCost ){
110117 #ifdef WHERETRACE_ENABLED
110118 if( sqlite3WhereTrace&0x4 ){
110119 sqlite3DebugPrintf("Skip %s cost=%3d order=%c\n",
110120 wherePathName(pFrom, iLoop, pWLoop), rCost,
110121 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
110123 #endif
110124 continue;
110126 /* Add a new Path to the aTo[] set */
110127 if( nTo<mxChoice ){
110128 /* Increase the size of the aTo set by one */
110129 jj = nTo++;
110130 }else{
110131 /* New path replaces the prior worst to keep count below mxChoice */
110132 for(jj=nTo-1; aTo[jj].rCost<mxCost; jj--){ assert(jj>0); }
110134 pTo = &aTo[jj];
110135 #ifdef WHERETRACE_ENABLED
110136 if( sqlite3WhereTrace&0x4 ){
110137 sqlite3DebugPrintf("New %s cost=%-3d order=%c\n",
110138 wherePathName(pFrom, iLoop, pWLoop), rCost,
110139 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
110141 #endif
110142 }else{
110143 if( pTo->rCost<=rCost ){
110144 #ifdef WHERETRACE_ENABLED
110145 if( sqlite3WhereTrace&0x4 ){
110146 sqlite3DebugPrintf(
110147 "Skip %s cost=%-3d order=%c",
110148 wherePathName(pFrom, iLoop, pWLoop), rCost,
110149 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
110150 sqlite3DebugPrintf(" vs %s cost=%-3d order=%c\n",
110151 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
110152 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
110154 #endif
110155 testcase( pTo->rCost==rCost );
110156 continue;
110158 testcase( pTo->rCost==rCost+1 );
110159 /* A new and better score for a previously created equivalent path */
110160 #ifdef WHERETRACE_ENABLED
110161 if( sqlite3WhereTrace&0x4 ){
110162 sqlite3DebugPrintf(
110163 "Update %s cost=%-3d order=%c",
110164 wherePathName(pFrom, iLoop, pWLoop), rCost,
110165 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
110166 sqlite3DebugPrintf(" was %s cost=%-3d order=%c\n",
110167 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
110168 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
110170 #endif
110172 /* pWLoop is a winner. Add it to the set of best so far */
110173 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
110174 pTo->revLoop = revMask;
110175 pTo->nRow = pFrom->nRow + pWLoop->nOut;
110176 pTo->rCost = rCost;
110177 pTo->isOrderedValid = isOrderedValid;
110178 pTo->isOrdered = isOrdered;
110179 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
110180 pTo->aLoop[iLoop] = pWLoop;
110181 if( nTo>=mxChoice ){
110182 mxCost = aTo[0].rCost;
110183 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
110184 if( pTo->rCost>mxCost ) mxCost = pTo->rCost;
110190 #ifdef WHERETRACE_ENABLED
110191 if( sqlite3WhereTrace>=2 ){
110192 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
110193 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
110194 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
110195 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
110196 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
110197 if( pTo->isOrderedValid && pTo->isOrdered ){
110198 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
110199 }else{
110200 sqlite3DebugPrintf("\n");
110204 #endif
110206 /* Swap the roles of aFrom and aTo for the next generation */
110207 pFrom = aTo;
110208 aTo = aFrom;
110209 aFrom = pFrom;
110210 nFrom = nTo;
110213 if( nFrom==0 ){
110214 sqlite3ErrorMsg(pParse, "no query solution");
110215 sqlite3DbFree(db, pSpace);
110216 return SQLITE_ERROR;
110219 /* Find the lowest cost path. pFrom will be left pointing to that path */
110220 pFrom = aFrom;
110221 assert( nFrom==1 );
110222 #if 0 /* The following is needed if nFrom is ever more than 1 */
110223 for(ii=1; ii<nFrom; ii++){
110224 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
110226 #endif
110227 assert( pWInfo->nLevel==nLoop );
110228 /* Load the lowest cost path into pWInfo */
110229 for(iLoop=0; iLoop<nLoop; iLoop++){
110230 WhereLevel *pLevel = pWInfo->a + iLoop;
110231 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
110232 pLevel->iFrom = pWLoop->iTab;
110233 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
110235 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
110236 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
110237 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
110238 && nRowEst
110240 Bitmask notUsed;
110241 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
110242 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
110243 if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
110245 if( pFrom->isOrdered ){
110246 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
110247 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
110248 }else{
110249 pWInfo->bOBSat = 1;
110250 pWInfo->revMask = pFrom->revLoop;
110253 pWInfo->nRowOut = pFrom->nRow;
110255 /* Free temporary memory and return success */
110256 sqlite3DbFree(db, pSpace);
110257 return SQLITE_OK;
110261 ** Most queries use only a single table (they are not joins) and have
110262 ** simple == constraints against indexed fields. This routine attempts
110263 ** to plan those simple cases using much less ceremony than the
110264 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
110265 ** times for the common case.
110267 ** Return non-zero on success, if this query can be handled by this
110268 ** no-frills query planner. Return zero if this query needs the
110269 ** general-purpose query planner.
110271 static int whereShortCut(WhereLoopBuilder *pBuilder){
110272 WhereInfo *pWInfo;
110273 struct SrcList_item *pItem;
110274 WhereClause *pWC;
110275 WhereTerm *pTerm;
110276 WhereLoop *pLoop;
110277 int iCur;
110278 int j;
110279 Table *pTab;
110280 Index *pIdx;
110282 pWInfo = pBuilder->pWInfo;
110283 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
110284 assert( pWInfo->pTabList->nSrc>=1 );
110285 pItem = pWInfo->pTabList->a;
110286 pTab = pItem->pTab;
110287 if( IsVirtual(pTab) ) return 0;
110288 if( pItem->zIndex ) return 0;
110289 iCur = pItem->iCursor;
110290 pWC = &pWInfo->sWC;
110291 pLoop = pBuilder->pNew;
110292 pLoop->wsFlags = 0;
110293 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
110294 if( pTerm ){
110295 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
110296 pLoop->aLTerm[0] = pTerm;
110297 pLoop->nLTerm = 1;
110298 pLoop->u.btree.nEq = 1;
110299 /* TUNING: Cost of a rowid lookup is 10 */
110300 pLoop->rRun = 33; /* 33==whereCost(10) */
110301 }else{
110302 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
110303 if( pIdx->onError==OE_None || pIdx->pPartIdxWhere!=0 ) continue;
110304 for(j=0; j<pIdx->nColumn; j++){
110305 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
110306 if( pTerm==0 ) break;
110307 whereLoopResize(pWInfo->pParse->db, pLoop, j);
110308 pLoop->aLTerm[j] = pTerm;
110310 if( j!=pIdx->nColumn ) continue;
110311 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
110312 if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
110313 pLoop->wsFlags |= WHERE_IDX_ONLY;
110315 pLoop->nLTerm = j;
110316 pLoop->u.btree.nEq = j;
110317 pLoop->u.btree.pIndex = pIdx;
110318 /* TUNING: Cost of a unique index lookup is 15 */
110319 pLoop->rRun = 39; /* 39==whereCost(15) */
110320 break;
110323 if( pLoop->wsFlags ){
110324 pLoop->nOut = (WhereCost)1;
110325 pWInfo->a[0].pWLoop = pLoop;
110326 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
110327 pWInfo->a[0].iTabCur = iCur;
110328 pWInfo->nRowOut = 1;
110329 if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
110330 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
110331 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
110333 #ifdef SQLITE_DEBUG
110334 pLoop->cId = '0';
110335 #endif
110336 return 1;
110338 return 0;
110342 ** Generate the beginning of the loop used for WHERE clause processing.
110343 ** The return value is a pointer to an opaque structure that contains
110344 ** information needed to terminate the loop. Later, the calling routine
110345 ** should invoke sqlite3WhereEnd() with the return value of this function
110346 ** in order to complete the WHERE clause processing.
110348 ** If an error occurs, this routine returns NULL.
110350 ** The basic idea is to do a nested loop, one loop for each table in
110351 ** the FROM clause of a select. (INSERT and UPDATE statements are the
110352 ** same as a SELECT with only a single table in the FROM clause.) For
110353 ** example, if the SQL is this:
110355 ** SELECT * FROM t1, t2, t3 WHERE ...;
110357 ** Then the code generated is conceptually like the following:
110359 ** foreach row1 in t1 do \ Code generated
110360 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
110361 ** foreach row3 in t3 do /
110362 ** ...
110363 ** end \ Code generated
110364 ** end |-- by sqlite3WhereEnd()
110365 ** end /
110367 ** Note that the loops might not be nested in the order in which they
110368 ** appear in the FROM clause if a different order is better able to make
110369 ** use of indices. Note also that when the IN operator appears in
110370 ** the WHERE clause, it might result in additional nested loops for
110371 ** scanning through all values on the right-hand side of the IN.
110373 ** There are Btree cursors associated with each table. t1 uses cursor
110374 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
110375 ** And so forth. This routine generates code to open those VDBE cursors
110376 ** and sqlite3WhereEnd() generates the code to close them.
110378 ** The code that sqlite3WhereBegin() generates leaves the cursors named
110379 ** in pTabList pointing at their appropriate entries. The [...] code
110380 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
110381 ** data from the various tables of the loop.
110383 ** If the WHERE clause is empty, the foreach loops must each scan their
110384 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
110385 ** the tables have indices and there are terms in the WHERE clause that
110386 ** refer to those indices, a complete table scan can be avoided and the
110387 ** code will run much faster. Most of the work of this routine is checking
110388 ** to see if there are indices that can be used to speed up the loop.
110390 ** Terms of the WHERE clause are also used to limit which rows actually
110391 ** make it to the "..." in the middle of the loop. After each "foreach",
110392 ** terms of the WHERE clause that use only terms in that loop and outer
110393 ** loops are evaluated and if false a jump is made around all subsequent
110394 ** inner loops (or around the "..." if the test occurs within the inner-
110395 ** most loop)
110397 ** OUTER JOINS
110399 ** An outer join of tables t1 and t2 is conceptally coded as follows:
110401 ** foreach row1 in t1 do
110402 ** flag = 0
110403 ** foreach row2 in t2 do
110404 ** start:
110405 ** ...
110406 ** flag = 1
110407 ** end
110408 ** if flag==0 then
110409 ** move the row2 cursor to a null row
110410 ** goto start
110411 ** fi
110412 ** end
110414 ** ORDER BY CLAUSE PROCESSING
110416 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
110417 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
110418 ** if there is one. If there is no ORDER BY clause or if this routine
110419 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
110421 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
110422 Parse *pParse, /* The parser context */
110423 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
110424 Expr *pWhere, /* The WHERE clause */
110425 ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
110426 ExprList *pResultSet, /* Result set of the query */
110427 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
110428 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
110430 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
110431 int nTabList; /* Number of elements in pTabList */
110432 WhereInfo *pWInfo; /* Will become the return value of this function */
110433 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
110434 Bitmask notReady; /* Cursors that are not yet positioned */
110435 WhereLoopBuilder sWLB; /* The WhereLoop builder */
110436 WhereMaskSet *pMaskSet; /* The expression mask set */
110437 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
110438 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
110439 int ii; /* Loop counter */
110440 sqlite3 *db; /* Database connection */
110441 int rc; /* Return code */
110444 /* Variable initialization */
110445 db = pParse->db;
110446 memset(&sWLB, 0, sizeof(sWLB));
110447 sWLB.pOrderBy = pOrderBy;
110449 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
110450 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
110451 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
110452 wctrlFlags &= ~WHERE_WANT_DISTINCT;
110455 /* The number of tables in the FROM clause is limited by the number of
110456 ** bits in a Bitmask
110458 testcase( pTabList->nSrc==BMS );
110459 if( pTabList->nSrc>BMS ){
110460 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
110461 return 0;
110464 /* This function normally generates a nested loop for all tables in
110465 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
110466 ** only generate code for the first table in pTabList and assume that
110467 ** any cursors associated with subsequent tables are uninitialized.
110469 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
110471 /* Allocate and initialize the WhereInfo structure that will become the
110472 ** return value. A single allocation is used to store the WhereInfo
110473 ** struct, the contents of WhereInfo.a[], the WhereClause structure
110474 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
110475 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
110476 ** some architectures. Hence the ROUND8() below.
110478 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
110479 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
110480 if( db->mallocFailed ){
110481 sqlite3DbFree(db, pWInfo);
110482 pWInfo = 0;
110483 goto whereBeginError;
110485 pWInfo->nLevel = nTabList;
110486 pWInfo->pParse = pParse;
110487 pWInfo->pTabList = pTabList;
110488 pWInfo->pOrderBy = pOrderBy;
110489 pWInfo->pResultSet = pResultSet;
110490 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
110491 pWInfo->wctrlFlags = wctrlFlags;
110492 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
110493 pMaskSet = &pWInfo->sMaskSet;
110494 sWLB.pWInfo = pWInfo;
110495 sWLB.pWC = &pWInfo->sWC;
110496 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
110497 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
110498 whereLoopInit(sWLB.pNew);
110499 #ifdef SQLITE_DEBUG
110500 sWLB.pNew->cId = '*';
110501 #endif
110503 /* Split the WHERE clause into separate subexpressions where each
110504 ** subexpression is separated by an AND operator.
110506 initMaskSet(pMaskSet);
110507 whereClauseInit(&pWInfo->sWC, pWInfo);
110508 sqlite3ExprCodeConstants(pParse, pWhere);
110509 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
110510 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
110512 /* Special case: a WHERE clause that is constant. Evaluate the
110513 ** expression and either jump over all of the code or fall thru.
110515 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
110516 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
110517 pWhere = 0;
110520 /* Special case: No FROM clause
110522 if( nTabList==0 ){
110523 if( pOrderBy ) pWInfo->bOBSat = 1;
110524 if( wctrlFlags & WHERE_WANT_DISTINCT ){
110525 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
110529 /* Assign a bit from the bitmask to every term in the FROM clause.
110531 ** When assigning bitmask values to FROM clause cursors, it must be
110532 ** the case that if X is the bitmask for the N-th FROM clause term then
110533 ** the bitmask for all FROM clause terms to the left of the N-th term
110534 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
110535 ** its Expr.iRightJoinTable value to find the bitmask of the right table
110536 ** of the join. Subtracting one from the right table bitmask gives a
110537 ** bitmask for all tables to the left of the join. Knowing the bitmask
110538 ** for all tables to the left of a left join is important. Ticket #3015.
110540 ** Note that bitmasks are created for all pTabList->nSrc tables in
110541 ** pTabList, not just the first nTabList tables. nTabList is normally
110542 ** equal to pTabList->nSrc but might be shortened to 1 if the
110543 ** WHERE_ONETABLE_ONLY flag is set.
110545 for(ii=0; ii<pTabList->nSrc; ii++){
110546 createMask(pMaskSet, pTabList->a[ii].iCursor);
110548 #ifndef NDEBUG
110550 Bitmask toTheLeft = 0;
110551 for(ii=0; ii<pTabList->nSrc; ii++){
110552 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
110553 assert( (m-1)==toTheLeft );
110554 toTheLeft |= m;
110557 #endif
110559 /* Analyze all of the subexpressions. Note that exprAnalyze() might
110560 ** add new virtual terms onto the end of the WHERE clause. We do not
110561 ** want to analyze these virtual terms, so start analyzing at the end
110562 ** and work forward so that the added virtual terms are never processed.
110564 exprAnalyzeAll(pTabList, &pWInfo->sWC);
110565 if( db->mallocFailed ){
110566 goto whereBeginError;
110569 /* If the ORDER BY (or GROUP BY) clause contains references to general
110570 ** expressions, then we won't be able to satisfy it using indices, so
110571 ** go ahead and disable it now.
110573 if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
110574 for(ii=0; ii<pOrderBy->nExpr; ii++){
110575 Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
110576 if( pExpr->op!=TK_COLUMN ){
110577 pWInfo->pOrderBy = pOrderBy = 0;
110578 break;
110579 }else if( pExpr->iColumn<0 ){
110580 break;
110585 if( wctrlFlags & WHERE_WANT_DISTINCT ){
110586 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
110587 /* The DISTINCT marking is pointless. Ignore it. */
110588 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
110589 }else if( pOrderBy==0 ){
110590 /* Try to ORDER BY the result set to make distinct processing easier */
110591 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
110592 pWInfo->pOrderBy = pResultSet;
110596 /* Construct the WhereLoop objects */
110597 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
110598 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
110599 rc = whereLoopAddAll(&sWLB);
110600 if( rc ) goto whereBeginError;
110602 /* Display all of the WhereLoop objects if wheretrace is enabled */
110603 #ifdef WHERETRACE_ENABLED
110604 if( sqlite3WhereTrace ){
110605 WhereLoop *p;
110606 int i;
110607 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
110608 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
110609 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
110610 p->cId = zLabel[i%sizeof(zLabel)];
110611 whereLoopPrint(p, pTabList);
110614 #endif
110616 wherePathSolver(pWInfo, 0);
110617 if( db->mallocFailed ) goto whereBeginError;
110618 if( pWInfo->pOrderBy ){
110619 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
110620 if( db->mallocFailed ) goto whereBeginError;
110623 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
110624 pWInfo->revMask = (Bitmask)(-1);
110626 if( pParse->nErr || NEVER(db->mallocFailed) ){
110627 goto whereBeginError;
110629 #ifdef WHERETRACE_ENABLED
110630 if( sqlite3WhereTrace ){
110631 int ii;
110632 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
110633 if( pWInfo->bOBSat ){
110634 sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
110636 switch( pWInfo->eDistinct ){
110637 case WHERE_DISTINCT_UNIQUE: {
110638 sqlite3DebugPrintf(" DISTINCT=unique");
110639 break;
110641 case WHERE_DISTINCT_ORDERED: {
110642 sqlite3DebugPrintf(" DISTINCT=ordered");
110643 break;
110645 case WHERE_DISTINCT_UNORDERED: {
110646 sqlite3DebugPrintf(" DISTINCT=unordered");
110647 break;
110650 sqlite3DebugPrintf("\n");
110651 for(ii=0; ii<pWInfo->nLevel; ii++){
110652 whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
110655 #endif
110656 /* Attempt to omit tables from the join that do not effect the result */
110657 if( pWInfo->nLevel>=2
110658 && pResultSet!=0
110659 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
110661 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
110662 if( pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, pOrderBy);
110663 while( pWInfo->nLevel>=2 ){
110664 WhereTerm *pTerm, *pEnd;
110665 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
110666 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
110667 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
110668 && (pLoop->wsFlags & WHERE_ONEROW)==0
110670 break;
110672 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
110673 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
110674 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
110675 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
110676 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
110678 break;
110681 if( pTerm<pEnd ) break;
110682 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
110683 pWInfo->nLevel--;
110684 nTabList--;
110687 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
110688 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
110690 /* If the caller is an UPDATE or DELETE statement that is requesting
110691 ** to use a one-pass algorithm, determine if this is appropriate.
110692 ** The one-pass algorithm only works if the WHERE clause constraints
110693 ** the statement to update a single row.
110695 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
110696 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
110697 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
110698 pWInfo->okOnePass = 1;
110699 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
110702 /* Open all tables in the pTabList and any indices selected for
110703 ** searching those tables.
110705 notReady = ~(Bitmask)0;
110706 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
110707 Table *pTab; /* Table to open */
110708 int iDb; /* Index of database containing table/index */
110709 struct SrcList_item *pTabItem;
110711 pTabItem = &pTabList->a[pLevel->iFrom];
110712 pTab = pTabItem->pTab;
110713 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110714 pLoop = pLevel->pWLoop;
110715 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
110716 /* Do nothing */
110717 }else
110718 #ifndef SQLITE_OMIT_VIRTUALTABLE
110719 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
110720 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
110721 int iCur = pTabItem->iCursor;
110722 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
110723 }else if( IsVirtual(pTab) ){
110724 /* noop */
110725 }else
110726 #endif
110727 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
110728 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
110729 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
110730 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
110731 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
110732 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
110733 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
110734 Bitmask b = pTabItem->colUsed;
110735 int n = 0;
110736 for(; b; b=b>>1, n++){}
110737 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
110738 SQLITE_INT_TO_PTR(n), P4_INT32);
110739 assert( n<=pTab->nCol );
110741 }else{
110742 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
110744 if( pLoop->wsFlags & WHERE_INDEXED ){
110745 Index *pIx = pLoop->u.btree.pIndex;
110746 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
110747 /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
110748 int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
110749 assert( pIx->pSchema==pTab->pSchema );
110750 assert( iIndexCur>=0 );
110751 sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
110752 (char*)pKey, P4_KEYINFO_HANDOFF);
110753 VdbeComment((v, "%s", pIx->zName));
110755 sqlite3CodeVerifySchema(pParse, iDb);
110756 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
110758 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
110759 if( db->mallocFailed ) goto whereBeginError;
110761 /* Generate the code to do the search. Each iteration of the for
110762 ** loop below generates code for a single nested loop of the VM
110763 ** program.
110765 notReady = ~(Bitmask)0;
110766 for(ii=0; ii<nTabList; ii++){
110767 pLevel = &pWInfo->a[ii];
110768 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
110769 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
110770 constructAutomaticIndex(pParse, &pWInfo->sWC,
110771 &pTabList->a[pLevel->iFrom], notReady, pLevel);
110772 if( db->mallocFailed ) goto whereBeginError;
110774 #endif
110775 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
110776 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
110777 notReady = codeOneLoopStart(pWInfo, ii, notReady);
110778 pWInfo->iContinue = pLevel->addrCont;
110781 /* Done. */
110782 return pWInfo;
110784 /* Jump here if malloc fails */
110785 whereBeginError:
110786 if( pWInfo ){
110787 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
110788 whereInfoFree(db, pWInfo);
110790 return 0;
110794 ** Generate the end of the WHERE loop. See comments on
110795 ** sqlite3WhereBegin() for additional information.
110797 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
110798 Parse *pParse = pWInfo->pParse;
110799 Vdbe *v = pParse->pVdbe;
110800 int i;
110801 WhereLevel *pLevel;
110802 WhereLoop *pLoop;
110803 SrcList *pTabList = pWInfo->pTabList;
110804 sqlite3 *db = pParse->db;
110806 /* Generate loop termination code.
110808 sqlite3ExprCacheClear(pParse);
110809 for(i=pWInfo->nLevel-1; i>=0; i--){
110810 pLevel = &pWInfo->a[i];
110811 pLoop = pLevel->pWLoop;
110812 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
110813 if( pLevel->op!=OP_Noop ){
110814 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
110815 sqlite3VdbeChangeP5(v, pLevel->p5);
110817 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
110818 struct InLoop *pIn;
110819 int j;
110820 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
110821 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
110822 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
110823 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
110824 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
110826 sqlite3DbFree(db, pLevel->u.in.aInLoop);
110828 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
110829 if( pLevel->iLeftJoin ){
110830 int addr;
110831 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
110832 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
110833 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
110834 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
110835 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
110837 if( pLoop->wsFlags & WHERE_INDEXED ){
110838 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
110840 if( pLevel->op==OP_Return ){
110841 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
110842 }else{
110843 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
110845 sqlite3VdbeJumpHere(v, addr);
110849 /* The "break" point is here, just past the end of the outer loop.
110850 ** Set it.
110852 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
110854 /* Close all of the cursors that were opened by sqlite3WhereBegin.
110856 assert( pWInfo->nLevel<=pTabList->nSrc );
110857 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
110858 Index *pIdx = 0;
110859 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
110860 Table *pTab = pTabItem->pTab;
110861 assert( pTab!=0 );
110862 pLoop = pLevel->pWLoop;
110863 if( (pTab->tabFlags & TF_Ephemeral)==0
110864 && pTab->pSelect==0
110865 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
110867 int ws = pLoop->wsFlags;
110868 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
110869 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
110871 if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){
110872 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
110876 /* If this scan uses an index, make VDBE code substitutions to read data
110877 ** from the index instead of from the table where possible. In some cases
110878 ** this optimization prevents the table from ever being read, which can
110879 ** yield a significant performance boost.
110881 ** Calls to the code generator in between sqlite3WhereBegin and
110882 ** sqlite3WhereEnd will have created code that references the table
110883 ** directly. This loop scans all that code looking for opcodes
110884 ** that reference the table and converts them into opcodes that
110885 ** reference the index.
110887 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
110888 pIdx = pLoop->u.btree.pIndex;
110889 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
110890 pIdx = pLevel->u.pCovidx;
110892 if( pIdx && !db->mallocFailed ){
110893 int k, j, last;
110894 VdbeOp *pOp;
110896 last = sqlite3VdbeCurrentAddr(v);
110897 k = pLevel->addrBody;
110898 pOp = sqlite3VdbeGetOp(v, k);
110899 for(; k<last; k++, pOp++){
110900 if( pOp->p1!=pLevel->iTabCur ) continue;
110901 if( pOp->opcode==OP_Column ){
110902 for(j=0; j<pIdx->nColumn; j++){
110903 if( pOp->p2==pIdx->aiColumn[j] ){
110904 pOp->p2 = j;
110905 pOp->p1 = pLevel->iIdxCur;
110906 break;
110909 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
110910 }else if( pOp->opcode==OP_Rowid ){
110911 pOp->p1 = pLevel->iIdxCur;
110912 pOp->opcode = OP_IdxRowid;
110918 /* Final cleanup
110920 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
110921 whereInfoFree(db, pWInfo);
110922 return;
110925 /************** End of where.c ***********************************************/
110926 /************** Begin file parse.c *******************************************/
110927 /* Driver template for the LEMON parser generator.
110928 ** The author disclaims copyright to this source code.
110930 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
110931 ** The only modifications are the addition of a couple of NEVER()
110932 ** macros to disable tests that are needed in the case of a general
110933 ** LALR(1) grammar but which are always false in the
110934 ** specific grammar used by SQLite.
110936 /* First off, code is included that follows the "include" declaration
110937 ** in the input grammar file. */
110938 /* #include <stdio.h> */
110942 ** Disable all error recovery processing in the parser push-down
110943 ** automaton.
110945 #define YYNOERRORRECOVERY 1
110948 ** Make yytestcase() the same as testcase()
110950 #define yytestcase(X) testcase(X)
110953 ** An instance of this structure holds information about the
110954 ** LIMIT clause of a SELECT statement.
110956 struct LimitVal {
110957 Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
110958 Expr *pOffset; /* The OFFSET expression. NULL if there is none */
110962 ** An instance of this structure is used to store the LIKE,
110963 ** GLOB, NOT LIKE, and NOT GLOB operators.
110965 struct LikeOp {
110966 Token eOperator; /* "like" or "glob" or "regexp" */
110967 int bNot; /* True if the NOT keyword is present */
110971 ** An instance of the following structure describes the event of a
110972 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
110973 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
110975 ** UPDATE ON (a,b,c)
110977 ** Then the "b" IdList records the list "a,b,c".
110979 struct TrigEvent { int a; IdList * b; };
110982 ** An instance of this structure holds the ATTACH key and the key type.
110984 struct AttachKey { int type; Token key; };
110987 ** One or more VALUES claues
110989 struct ValueList {
110990 ExprList *pList;
110991 Select *pSelect;
110995 /* This is a utility routine used to set the ExprSpan.zStart and
110996 ** ExprSpan.zEnd values of pOut so that the span covers the complete
110997 ** range of text beginning with pStart and going to the end of pEnd.
110999 static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
111000 pOut->zStart = pStart->z;
111001 pOut->zEnd = &pEnd->z[pEnd->n];
111004 /* Construct a new Expr object from a single identifier. Use the
111005 ** new Expr to populate pOut. Set the span of pOut to be the identifier
111006 ** that created the expression.
111008 static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
111009 pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
111010 pOut->zStart = pValue->z;
111011 pOut->zEnd = &pValue->z[pValue->n];
111014 /* This routine constructs a binary expression node out of two ExprSpan
111015 ** objects and uses the result to populate a new ExprSpan object.
111017 static void spanBinaryExpr(
111018 ExprSpan *pOut, /* Write the result here */
111019 Parse *pParse, /* The parsing context. Errors accumulate here */
111020 int op, /* The binary operation */
111021 ExprSpan *pLeft, /* The left operand */
111022 ExprSpan *pRight /* The right operand */
111024 pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
111025 pOut->zStart = pLeft->zStart;
111026 pOut->zEnd = pRight->zEnd;
111029 /* Construct an expression node for a unary postfix operator
111031 static void spanUnaryPostfix(
111032 ExprSpan *pOut, /* Write the new expression node here */
111033 Parse *pParse, /* Parsing context to record errors */
111034 int op, /* The operator */
111035 ExprSpan *pOperand, /* The operand */
111036 Token *pPostOp /* The operand token for setting the span */
111038 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
111039 pOut->zStart = pOperand->zStart;
111040 pOut->zEnd = &pPostOp->z[pPostOp->n];
111043 /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
111044 ** unary TK_ISNULL or TK_NOTNULL expression. */
111045 static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
111046 sqlite3 *db = pParse->db;
111047 if( db->mallocFailed==0 && pY->op==TK_NULL ){
111048 pA->op = (u8)op;
111049 sqlite3ExprDelete(db, pA->pRight);
111050 pA->pRight = 0;
111054 /* Construct an expression node for a unary prefix operator
111056 static void spanUnaryPrefix(
111057 ExprSpan *pOut, /* Write the new expression node here */
111058 Parse *pParse, /* Parsing context to record errors */
111059 int op, /* The operator */
111060 ExprSpan *pOperand, /* The operand */
111061 Token *pPreOp /* The operand token for setting the span */
111063 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
111064 pOut->zStart = pPreOp->z;
111065 pOut->zEnd = pOperand->zEnd;
111067 /* Next is all token values, in a form suitable for use by makeheaders.
111068 ** This section will be null unless lemon is run with the -m switch.
111071 ** These constants (all generated automatically by the parser generator)
111072 ** specify the various kinds of tokens (terminals) that the parser
111073 ** understands.
111075 ** Each symbol here is a terminal symbol in the grammar.
111077 /* Make sure the INTERFACE macro is defined.
111079 #ifndef INTERFACE
111080 # define INTERFACE 1
111081 #endif
111082 /* The next thing included is series of defines which control
111083 ** various aspects of the generated parser.
111084 ** YYCODETYPE is the data type used for storing terminal
111085 ** and nonterminal numbers. "unsigned char" is
111086 ** used if there are fewer than 250 terminals
111087 ** and nonterminals. "int" is used otherwise.
111088 ** YYNOCODE is a number of type YYCODETYPE which corresponds
111089 ** to no legal terminal or nonterminal number. This
111090 ** number is used to fill in empty slots of the hash
111091 ** table.
111092 ** YYFALLBACK If defined, this indicates that one or more tokens
111093 ** have fall-back values which should be used if the
111094 ** original value of the token will not parse.
111095 ** YYACTIONTYPE is the data type used for storing terminal
111096 ** and nonterminal numbers. "unsigned char" is
111097 ** used if there are fewer than 250 rules and
111098 ** states combined. "int" is used otherwise.
111099 ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
111100 ** directly to the parser from the tokenizer.
111101 ** YYMINORTYPE is the data type used for all minor tokens.
111102 ** This is typically a union of many types, one of
111103 ** which is sqlite3ParserTOKENTYPE. The entry in the union
111104 ** for base tokens is called "yy0".
111105 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
111106 ** zero the stack is dynamically sized using realloc()
111107 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
111108 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
111109 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
111110 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
111111 ** YYNSTATE the combined number of states.
111112 ** YYNRULE the number of rules in the grammar
111113 ** YYERRORSYMBOL is the code number of the error symbol. If not
111114 ** defined, then do no error processing.
111116 #define YYCODETYPE unsigned char
111117 #define YYNOCODE 251
111118 #define YYACTIONTYPE unsigned short int
111119 #define YYWILDCARD 67
111120 #define sqlite3ParserTOKENTYPE Token
111121 typedef union {
111122 int yyinit;
111123 sqlite3ParserTOKENTYPE yy0;
111124 struct LimitVal yy64;
111125 Expr* yy122;
111126 Select* yy159;
111127 IdList* yy180;
111128 struct {int value; int mask;} yy207;
111129 u8 yy258;
111130 u16 yy305;
111131 struct LikeOp yy318;
111132 TriggerStep* yy327;
111133 ExprSpan yy342;
111134 SrcList* yy347;
111135 int yy392;
111136 struct TrigEvent yy410;
111137 ExprList* yy442;
111138 struct ValueList yy487;
111139 } YYMINORTYPE;
111140 #ifndef YYSTACKDEPTH
111141 #define YYSTACKDEPTH 100
111142 #endif
111143 #define sqlite3ParserARG_SDECL Parse *pParse;
111144 #define sqlite3ParserARG_PDECL ,Parse *pParse
111145 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
111146 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
111147 #define YYNSTATE 628
111148 #define YYNRULE 327
111149 #define YYFALLBACK 1
111150 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
111151 #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
111152 #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
111154 /* The yyzerominor constant is used to initialize instances of
111155 ** YYMINORTYPE objects to zero. */
111156 static const YYMINORTYPE yyzerominor = { 0 };
111158 /* Define the yytestcase() macro to be a no-op if is not already defined
111159 ** otherwise.
111161 ** Applications can choose to define yytestcase() in the %include section
111162 ** to a macro that can assist in verifying code coverage. For production
111163 ** code the yytestcase() macro should be turned off. But it is useful
111164 ** for testing.
111166 #ifndef yytestcase
111167 # define yytestcase(X)
111168 #endif
111171 /* Next are the tables used to determine what action to take based on the
111172 ** current state and lookahead token. These tables are used to implement
111173 ** functions that take a state number and lookahead value and return an
111174 ** action integer.
111176 ** Suppose the action integer is N. Then the action is determined as
111177 ** follows
111179 ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
111180 ** token onto the stack and goto state N.
111182 ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
111184 ** N == YYNSTATE+YYNRULE A syntax error has occurred.
111186 ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
111188 ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
111189 ** slots in the yy_action[] table.
111191 ** The action table is constructed as a single large table named yy_action[].
111192 ** Given state S and lookahead X, the action is computed as
111194 ** yy_action[ yy_shift_ofst[S] + X ]
111196 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
111197 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
111198 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
111199 ** and that yy_default[S] should be used instead.
111201 ** The formula above is for computing the action when the lookahead is
111202 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
111203 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
111204 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
111205 ** YY_SHIFT_USE_DFLT.
111207 ** The following are the tables generated in this section:
111209 ** yy_action[] A single table containing all actions.
111210 ** yy_lookahead[] A table containing the lookahead for each entry in
111211 ** yy_action. Used to detect hash collisions.
111212 ** yy_shift_ofst[] For each state, the offset into yy_action for
111213 ** shifting terminals.
111214 ** yy_reduce_ofst[] For each state, the offset into yy_action for
111215 ** shifting non-terminals after a reduce.
111216 ** yy_default[] Default action for each state.
111218 #define YY_ACTTAB_COUNT (1564)
111219 static const YYACTIONTYPE yy_action[] = {
111220 /* 0 */ 310, 956, 184, 418, 2, 171, 625, 595, 56, 56,
111221 /* 10 */ 56, 56, 49, 54, 54, 54, 54, 53, 53, 52,
111222 /* 20 */ 52, 52, 51, 233, 621, 620, 299, 621, 620, 234,
111223 /* 30 */ 588, 582, 56, 56, 56, 56, 19, 54, 54, 54,
111224 /* 40 */ 54, 53, 53, 52, 52, 52, 51, 233, 606, 57,
111225 /* 50 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
111226 /* 60 */ 56, 56, 542, 54, 54, 54, 54, 53, 53, 52,
111227 /* 70 */ 52, 52, 51, 233, 310, 595, 326, 196, 195, 194,
111228 /* 80 */ 33, 54, 54, 54, 54, 53, 53, 52, 52, 52,
111229 /* 90 */ 51, 233, 618, 617, 165, 618, 617, 381, 378, 377,
111230 /* 100 */ 408, 533, 577, 577, 588, 582, 304, 423, 376, 59,
111231 /* 110 */ 53, 53, 52, 52, 52, 51, 233, 50, 47, 146,
111232 /* 120 */ 575, 546, 65, 57, 58, 48, 580, 579, 581, 581,
111233 /* 130 */ 55, 55, 56, 56, 56, 56, 213, 54, 54, 54,
111234 /* 140 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 223,
111235 /* 150 */ 540, 421, 170, 176, 138, 281, 384, 276, 383, 168,
111236 /* 160 */ 490, 552, 410, 669, 621, 620, 272, 439, 410, 439,
111237 /* 170 */ 551, 605, 67, 483, 508, 619, 600, 413, 588, 582,
111238 /* 180 */ 601, 484, 619, 413, 619, 599, 91, 440, 441, 440,
111239 /* 190 */ 336, 599, 73, 670, 222, 267, 481, 57, 58, 48,
111240 /* 200 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
111241 /* 210 */ 671, 54, 54, 54, 54, 53, 53, 52, 52, 52,
111242 /* 220 */ 51, 233, 310, 280, 232, 231, 1, 132, 200, 386,
111243 /* 230 */ 621, 620, 618, 617, 279, 436, 290, 564, 175, 263,
111244 /* 240 */ 410, 265, 438, 498, 437, 166, 442, 569, 337, 569,
111245 /* 250 */ 201, 538, 588, 582, 600, 413, 165, 595, 601, 381,
111246 /* 260 */ 378, 377, 598, 599, 92, 524, 619, 570, 570, 593,
111247 /* 270 */ 376, 57, 58, 48, 580, 579, 581, 581, 55, 55,
111248 /* 280 */ 56, 56, 56, 56, 598, 54, 54, 54, 54, 53,
111249 /* 290 */ 53, 52, 52, 52, 51, 233, 310, 464, 618, 617,
111250 /* 300 */ 591, 591, 591, 174, 273, 397, 410, 273, 410, 549,
111251 /* 310 */ 398, 621, 620, 68, 327, 621, 620, 621, 620, 619,
111252 /* 320 */ 547, 413, 619, 413, 472, 595, 588, 582, 473, 599,
111253 /* 330 */ 92, 599, 92, 52, 52, 52, 51, 233, 514, 513,
111254 /* 340 */ 206, 323, 364, 465, 221, 57, 58, 48, 580, 579,
111255 /* 350 */ 581, 581, 55, 55, 56, 56, 56, 56, 530, 54,
111256 /* 360 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
111257 /* 370 */ 310, 397, 410, 397, 598, 373, 387, 531, 348, 618,
111258 /* 380 */ 617, 576, 202, 618, 617, 618, 617, 413, 621, 620,
111259 /* 390 */ 145, 255, 347, 254, 578, 599, 74, 352, 45, 490,
111260 /* 400 */ 588, 582, 235, 189, 465, 545, 167, 297, 187, 470,
111261 /* 410 */ 480, 67, 62, 39, 619, 547, 598, 346, 574, 57,
111262 /* 420 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
111263 /* 430 */ 56, 56, 6, 54, 54, 54, 54, 53, 53, 52,
111264 /* 440 */ 52, 52, 51, 233, 310, 563, 559, 408, 529, 577,
111265 /* 450 */ 577, 345, 255, 347, 254, 182, 618, 617, 504, 505,
111266 /* 460 */ 315, 410, 558, 235, 166, 272, 410, 353, 565, 181,
111267 /* 470 */ 408, 547, 577, 577, 588, 582, 413, 538, 557, 562,
111268 /* 480 */ 518, 413, 619, 249, 599, 16, 7, 36, 468, 599,
111269 /* 490 */ 92, 517, 619, 57, 58, 48, 580, 579, 581, 581,
111270 /* 500 */ 55, 55, 56, 56, 56, 56, 542, 54, 54, 54,
111271 /* 510 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 328,
111272 /* 520 */ 573, 572, 526, 559, 561, 395, 872, 246, 410, 248,
111273 /* 530 */ 171, 393, 595, 219, 408, 410, 577, 577, 503, 558,
111274 /* 540 */ 365, 145, 511, 413, 408, 229, 577, 577, 588, 582,
111275 /* 550 */ 413, 599, 92, 382, 270, 557, 166, 401, 599, 69,
111276 /* 560 */ 502, 420, 946, 199, 946, 198, 547, 57, 58, 48,
111277 /* 570 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
111278 /* 580 */ 569, 54, 54, 54, 54, 53, 53, 52, 52, 52,
111279 /* 590 */ 51, 233, 310, 318, 420, 945, 509, 945, 309, 598,
111280 /* 600 */ 595, 566, 491, 212, 173, 247, 424, 616, 615, 614,
111281 /* 610 */ 324, 197, 143, 406, 573, 572, 490, 66, 50, 47,
111282 /* 620 */ 146, 595, 588, 582, 232, 231, 560, 428, 67, 556,
111283 /* 630 */ 15, 619, 186, 544, 304, 422, 35, 206, 433, 424,
111284 /* 640 */ 553, 57, 58, 48, 580, 579, 581, 581, 55, 55,
111285 /* 650 */ 56, 56, 56, 56, 205, 54, 54, 54, 54, 53,
111286 /* 660 */ 53, 52, 52, 52, 51, 233, 310, 570, 570, 261,
111287 /* 670 */ 269, 598, 12, 374, 569, 166, 410, 314, 410, 421,
111288 /* 680 */ 410, 474, 474, 366, 619, 50, 47, 146, 598, 595,
111289 /* 690 */ 256, 413, 166, 413, 352, 413, 588, 582, 32, 599,
111290 /* 700 */ 94, 599, 97, 599, 95, 628, 626, 330, 142, 50,
111291 /* 710 */ 47, 146, 334, 350, 359, 57, 58, 48, 580, 579,
111292 /* 720 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
111293 /* 730 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
111294 /* 740 */ 310, 410, 389, 413, 410, 22, 566, 405, 212, 363,
111295 /* 750 */ 390, 599, 104, 360, 410, 156, 413, 410, 604, 413,
111296 /* 760 */ 538, 332, 570, 570, 599, 103, 494, 599, 105, 413,
111297 /* 770 */ 588, 582, 413, 261, 550, 619, 11, 599, 106, 522,
111298 /* 780 */ 599, 133, 169, 458, 457, 170, 35, 602, 619, 57,
111299 /* 790 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
111300 /* 800 */ 56, 56, 410, 54, 54, 54, 54, 53, 53, 52,
111301 /* 810 */ 52, 52, 51, 233, 310, 410, 260, 413, 410, 50,
111302 /* 820 */ 47, 146, 358, 319, 356, 599, 134, 528, 353, 338,
111303 /* 830 */ 413, 410, 357, 413, 358, 410, 358, 619, 599, 98,
111304 /* 840 */ 129, 599, 102, 619, 588, 582, 413, 21, 235, 619,
111305 /* 850 */ 413, 619, 211, 143, 599, 101, 30, 167, 599, 93,
111306 /* 860 */ 351, 536, 203, 57, 58, 48, 580, 579, 581, 581,
111307 /* 870 */ 55, 55, 56, 56, 56, 56, 410, 54, 54, 54,
111308 /* 880 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 410,
111309 /* 890 */ 527, 413, 410, 426, 215, 306, 598, 552, 141, 599,
111310 /* 900 */ 100, 40, 410, 38, 413, 410, 551, 413, 410, 228,
111311 /* 910 */ 220, 315, 599, 77, 501, 599, 96, 413, 588, 582,
111312 /* 920 */ 413, 339, 253, 413, 218, 599, 137, 380, 599, 136,
111313 /* 930 */ 28, 599, 135, 271, 716, 210, 482, 57, 58, 48,
111314 /* 940 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
111315 /* 950 */ 410, 54, 54, 54, 54, 53, 53, 52, 52, 52,
111316 /* 960 */ 51, 233, 310, 410, 273, 413, 410, 316, 147, 598,
111317 /* 970 */ 273, 627, 2, 599, 76, 209, 410, 127, 413, 619,
111318 /* 980 */ 126, 413, 410, 622, 235, 619, 599, 90, 375, 599,
111319 /* 990 */ 89, 413, 588, 582, 27, 261, 351, 413, 619, 599,
111320 /* 1000 */ 75, 322, 542, 542, 125, 599, 88, 321, 279, 598,
111321 /* 1010 */ 619, 57, 46, 48, 580, 579, 581, 581, 55, 55,
111322 /* 1020 */ 56, 56, 56, 56, 410, 54, 54, 54, 54, 53,
111323 /* 1030 */ 53, 52, 52, 52, 51, 233, 310, 410, 451, 413,
111324 /* 1040 */ 164, 285, 283, 273, 610, 425, 305, 599, 87, 371,
111325 /* 1050 */ 410, 478, 413, 410, 609, 410, 608, 603, 619, 619,
111326 /* 1060 */ 599, 99, 587, 586, 122, 413, 588, 582, 413, 619,
111327 /* 1070 */ 413, 619, 619, 599, 86, 367, 599, 17, 599, 85,
111328 /* 1080 */ 320, 185, 520, 519, 584, 583, 58, 48, 580, 579,
111329 /* 1090 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
111330 /* 1100 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
111331 /* 1110 */ 310, 585, 410, 413, 410, 261, 261, 261, 409, 592,
111332 /* 1120 */ 475, 599, 84, 170, 410, 467, 519, 413, 121, 413,
111333 /* 1130 */ 619, 619, 619, 619, 619, 599, 83, 599, 72, 413,
111334 /* 1140 */ 588, 582, 51, 233, 626, 330, 471, 599, 71, 258,
111335 /* 1150 */ 159, 120, 14, 463, 157, 158, 117, 261, 449, 448,
111336 /* 1160 */ 447, 48, 580, 579, 581, 581, 55, 55, 56, 56,
111337 /* 1170 */ 56, 56, 619, 54, 54, 54, 54, 53, 53, 52,
111338 /* 1180 */ 52, 52, 51, 233, 44, 404, 261, 3, 410, 460,
111339 /* 1190 */ 261, 414, 620, 118, 399, 10, 25, 24, 555, 349,
111340 /* 1200 */ 217, 619, 407, 413, 410, 619, 4, 44, 404, 619,
111341 /* 1210 */ 3, 599, 82, 619, 414, 620, 456, 543, 115, 413,
111342 /* 1220 */ 539, 402, 537, 275, 507, 407, 251, 599, 81, 216,
111343 /* 1230 */ 274, 564, 619, 243, 454, 619, 154, 619, 619, 619,
111344 /* 1240 */ 450, 417, 624, 110, 402, 619, 410, 236, 64, 123,
111345 /* 1250 */ 488, 41, 42, 532, 564, 204, 410, 268, 43, 412,
111346 /* 1260 */ 411, 413, 266, 593, 108, 619, 107, 435, 333, 599,
111347 /* 1270 */ 80, 413, 619, 264, 41, 42, 444, 619, 410, 599,
111348 /* 1280 */ 70, 43, 412, 411, 434, 262, 593, 149, 619, 598,
111349 /* 1290 */ 257, 237, 188, 413, 591, 591, 591, 590, 589, 13,
111350 /* 1300 */ 619, 599, 18, 329, 235, 619, 44, 404, 361, 3,
111351 /* 1310 */ 419, 462, 340, 414, 620, 227, 124, 591, 591, 591,
111352 /* 1320 */ 590, 589, 13, 619, 407, 410, 619, 410, 139, 34,
111353 /* 1330 */ 404, 388, 3, 148, 623, 313, 414, 620, 312, 331,
111354 /* 1340 */ 413, 461, 413, 402, 180, 354, 413, 407, 599, 79,
111355 /* 1350 */ 599, 78, 250, 564, 599, 9, 619, 613, 612, 611,
111356 /* 1360 */ 619, 8, 453, 443, 242, 416, 402, 619, 239, 235,
111357 /* 1370 */ 179, 238, 429, 41, 42, 289, 564, 619, 619, 619,
111358 /* 1380 */ 43, 412, 411, 619, 144, 593, 619, 619, 177, 61,
111359 /* 1390 */ 619, 597, 392, 621, 620, 288, 41, 42, 415, 619,
111360 /* 1400 */ 294, 30, 394, 43, 412, 411, 293, 619, 593, 31,
111361 /* 1410 */ 619, 396, 292, 60, 230, 37, 591, 591, 591, 590,
111362 /* 1420 */ 589, 13, 214, 554, 183, 291, 172, 302, 301, 300,
111363 /* 1430 */ 178, 298, 596, 564, 452, 29, 286, 391, 541, 591,
111364 /* 1440 */ 591, 591, 590, 589, 13, 284, 521, 535, 150, 534,
111365 /* 1450 */ 241, 282, 385, 192, 191, 325, 516, 515, 277, 240,
111366 /* 1460 */ 511, 524, 308, 512, 128, 593, 510, 225, 226, 487,
111367 /* 1470 */ 486, 224, 152, 492, 465, 307, 485, 163, 153, 372,
111368 /* 1480 */ 479, 151, 162, 259, 370, 161, 368, 208, 476, 477,
111369 /* 1490 */ 26, 160, 469, 466, 362, 140, 591, 591, 591, 116,
111370 /* 1500 */ 119, 455, 344, 155, 114, 343, 113, 112, 446, 111,
111371 /* 1510 */ 131, 109, 432, 317, 130, 431, 23, 20, 430, 427,
111372 /* 1520 */ 190, 63, 255, 342, 244, 607, 295, 287, 311, 594,
111373 /* 1530 */ 278, 508, 496, 235, 493, 571, 497, 568, 495, 403,
111374 /* 1540 */ 459, 379, 355, 245, 193, 303, 567, 296, 341, 5,
111375 /* 1550 */ 445, 548, 506, 207, 525, 500, 335, 489, 252, 369,
111376 /* 1560 */ 400, 499, 523, 233,
111378 static const YYCODETYPE yy_lookahead[] = {
111379 /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
111380 /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
111381 /* 20 */ 89, 90, 91, 92, 26, 27, 15, 26, 27, 197,
111382 /* 30 */ 49, 50, 77, 78, 79, 80, 204, 82, 83, 84,
111383 /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 23, 68,
111384 /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
111385 /* 60 */ 79, 80, 166, 82, 83, 84, 85, 86, 87, 88,
111386 /* 70 */ 89, 90, 91, 92, 19, 94, 19, 105, 106, 107,
111387 /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
111388 /* 90 */ 91, 92, 94, 95, 96, 94, 95, 99, 100, 101,
111389 /* 100 */ 112, 205, 114, 115, 49, 50, 22, 23, 110, 54,
111390 /* 110 */ 86, 87, 88, 89, 90, 91, 92, 221, 222, 223,
111391 /* 120 */ 23, 120, 25, 68, 69, 70, 71, 72, 73, 74,
111392 /* 130 */ 75, 76, 77, 78, 79, 80, 22, 82, 83, 84,
111393 /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 92,
111394 /* 150 */ 23, 67, 25, 96, 97, 98, 99, 100, 101, 102,
111395 /* 160 */ 150, 32, 150, 118, 26, 27, 109, 150, 150, 150,
111396 /* 170 */ 41, 161, 162, 180, 181, 165, 113, 165, 49, 50,
111397 /* 180 */ 117, 188, 165, 165, 165, 173, 174, 170, 171, 170,
111398 /* 190 */ 171, 173, 174, 118, 184, 16, 186, 68, 69, 70,
111399 /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
111400 /* 210 */ 118, 82, 83, 84, 85, 86, 87, 88, 89, 90,
111401 /* 220 */ 91, 92, 19, 98, 86, 87, 22, 24, 160, 88,
111402 /* 230 */ 26, 27, 94, 95, 109, 97, 224, 66, 118, 60,
111403 /* 240 */ 150, 62, 104, 23, 106, 25, 229, 230, 229, 230,
111404 /* 250 */ 160, 150, 49, 50, 113, 165, 96, 26, 117, 99,
111405 /* 260 */ 100, 101, 194, 173, 174, 94, 165, 129, 130, 98,
111406 /* 270 */ 110, 68, 69, 70, 71, 72, 73, 74, 75, 76,
111407 /* 280 */ 77, 78, 79, 80, 194, 82, 83, 84, 85, 86,
111408 /* 290 */ 87, 88, 89, 90, 91, 92, 19, 11, 94, 95,
111409 /* 300 */ 129, 130, 131, 118, 150, 215, 150, 150, 150, 25,
111410 /* 310 */ 220, 26, 27, 22, 213, 26, 27, 26, 27, 165,
111411 /* 320 */ 25, 165, 165, 165, 30, 94, 49, 50, 34, 173,
111412 /* 330 */ 174, 173, 174, 88, 89, 90, 91, 92, 7, 8,
111413 /* 340 */ 160, 187, 48, 57, 187, 68, 69, 70, 71, 72,
111414 /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 23, 82,
111415 /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
111416 /* 370 */ 19, 215, 150, 215, 194, 19, 220, 88, 220, 94,
111417 /* 380 */ 95, 23, 160, 94, 95, 94, 95, 165, 26, 27,
111418 /* 390 */ 95, 105, 106, 107, 113, 173, 174, 217, 22, 150,
111419 /* 400 */ 49, 50, 116, 119, 57, 120, 50, 158, 22, 21,
111420 /* 410 */ 161, 162, 232, 136, 165, 120, 194, 237, 23, 68,
111421 /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
111422 /* 430 */ 79, 80, 22, 82, 83, 84, 85, 86, 87, 88,
111423 /* 440 */ 89, 90, 91, 92, 19, 23, 12, 112, 23, 114,
111424 /* 450 */ 115, 63, 105, 106, 107, 23, 94, 95, 97, 98,
111425 /* 460 */ 104, 150, 28, 116, 25, 109, 150, 150, 23, 23,
111426 /* 470 */ 112, 25, 114, 115, 49, 50, 165, 150, 44, 11,
111427 /* 480 */ 46, 165, 165, 16, 173, 174, 76, 136, 100, 173,
111428 /* 490 */ 174, 57, 165, 68, 69, 70, 71, 72, 73, 74,
111429 /* 500 */ 75, 76, 77, 78, 79, 80, 166, 82, 83, 84,
111430 /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 169,
111431 /* 520 */ 170, 171, 23, 12, 23, 214, 138, 60, 150, 62,
111432 /* 530 */ 24, 215, 26, 216, 112, 150, 114, 115, 36, 28,
111433 /* 540 */ 213, 95, 103, 165, 112, 205, 114, 115, 49, 50,
111434 /* 550 */ 165, 173, 174, 51, 23, 44, 25, 46, 173, 174,
111435 /* 560 */ 58, 22, 23, 22, 25, 160, 120, 68, 69, 70,
111436 /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
111437 /* 580 */ 230, 82, 83, 84, 85, 86, 87, 88, 89, 90,
111438 /* 590 */ 91, 92, 19, 215, 22, 23, 23, 25, 163, 194,
111439 /* 600 */ 94, 166, 167, 168, 25, 138, 67, 7, 8, 9,
111440 /* 610 */ 108, 206, 207, 169, 170, 171, 150, 22, 221, 222,
111441 /* 620 */ 223, 26, 49, 50, 86, 87, 23, 161, 162, 23,
111442 /* 630 */ 22, 165, 24, 120, 22, 23, 25, 160, 241, 67,
111443 /* 640 */ 176, 68, 69, 70, 71, 72, 73, 74, 75, 76,
111444 /* 650 */ 77, 78, 79, 80, 160, 82, 83, 84, 85, 86,
111445 /* 660 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 150,
111446 /* 670 */ 23, 194, 35, 23, 230, 25, 150, 155, 150, 67,
111447 /* 680 */ 150, 105, 106, 107, 165, 221, 222, 223, 194, 94,
111448 /* 690 */ 23, 165, 25, 165, 217, 165, 49, 50, 25, 173,
111449 /* 700 */ 174, 173, 174, 173, 174, 0, 1, 2, 118, 221,
111450 /* 710 */ 222, 223, 193, 219, 237, 68, 69, 70, 71, 72,
111451 /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
111452 /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
111453 /* 740 */ 19, 150, 19, 165, 150, 24, 166, 167, 168, 227,
111454 /* 750 */ 27, 173, 174, 231, 150, 25, 165, 150, 172, 165,
111455 /* 760 */ 150, 242, 129, 130, 173, 174, 180, 173, 174, 165,
111456 /* 770 */ 49, 50, 165, 150, 176, 165, 35, 173, 174, 165,
111457 /* 780 */ 173, 174, 35, 23, 23, 25, 25, 173, 165, 68,
111458 /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
111459 /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
111460 /* 810 */ 89, 90, 91, 92, 19, 150, 193, 165, 150, 221,
111461 /* 820 */ 222, 223, 150, 213, 19, 173, 174, 23, 150, 97,
111462 /* 830 */ 165, 150, 27, 165, 150, 150, 150, 165, 173, 174,
111463 /* 840 */ 22, 173, 174, 165, 49, 50, 165, 52, 116, 165,
111464 /* 850 */ 165, 165, 206, 207, 173, 174, 126, 50, 173, 174,
111465 /* 860 */ 128, 27, 160, 68, 69, 70, 71, 72, 73, 74,
111466 /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
111467 /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
111468 /* 890 */ 23, 165, 150, 23, 216, 25, 194, 32, 39, 173,
111469 /* 900 */ 174, 135, 150, 137, 165, 150, 41, 165, 150, 52,
111470 /* 910 */ 238, 104, 173, 174, 29, 173, 174, 165, 49, 50,
111471 /* 920 */ 165, 219, 238, 165, 238, 173, 174, 52, 173, 174,
111472 /* 930 */ 22, 173, 174, 23, 23, 160, 25, 68, 69, 70,
111473 /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
111474 /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
111475 /* 960 */ 91, 92, 19, 150, 150, 165, 150, 245, 246, 194,
111476 /* 970 */ 150, 144, 145, 173, 174, 160, 150, 22, 165, 165,
111477 /* 980 */ 22, 165, 150, 150, 116, 165, 173, 174, 52, 173,
111478 /* 990 */ 174, 165, 49, 50, 22, 150, 128, 165, 165, 173,
111479 /* 1000 */ 174, 187, 166, 166, 22, 173, 174, 187, 109, 194,
111480 /* 1010 */ 165, 68, 69, 70, 71, 72, 73, 74, 75, 76,
111481 /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
111482 /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 150, 193, 165,
111483 /* 1040 */ 102, 205, 205, 150, 150, 247, 248, 173, 174, 19,
111484 /* 1050 */ 150, 20, 165, 150, 150, 150, 150, 150, 165, 165,
111485 /* 1060 */ 173, 174, 49, 50, 104, 165, 49, 50, 165, 165,
111486 /* 1070 */ 165, 165, 165, 173, 174, 43, 173, 174, 173, 174,
111487 /* 1080 */ 187, 24, 190, 191, 71, 72, 69, 70, 71, 72,
111488 /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
111489 /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
111490 /* 1110 */ 19, 98, 150, 165, 150, 150, 150, 150, 150, 150,
111491 /* 1120 */ 59, 173, 174, 25, 150, 190, 191, 165, 53, 165,
111492 /* 1130 */ 165, 165, 165, 165, 165, 173, 174, 173, 174, 165,
111493 /* 1140 */ 49, 50, 91, 92, 1, 2, 53, 173, 174, 138,
111494 /* 1150 */ 104, 22, 5, 1, 35, 118, 127, 150, 193, 193,
111495 /* 1160 */ 193, 70, 71, 72, 73, 74, 75, 76, 77, 78,
111496 /* 1170 */ 79, 80, 165, 82, 83, 84, 85, 86, 87, 88,
111497 /* 1180 */ 89, 90, 91, 92, 19, 20, 150, 22, 150, 27,
111498 /* 1190 */ 150, 26, 27, 108, 150, 22, 76, 76, 150, 25,
111499 /* 1200 */ 193, 165, 37, 165, 150, 165, 22, 19, 20, 165,
111500 /* 1210 */ 22, 173, 174, 165, 26, 27, 23, 150, 119, 165,
111501 /* 1220 */ 150, 56, 150, 150, 150, 37, 16, 173, 174, 193,
111502 /* 1230 */ 150, 66, 165, 193, 1, 165, 121, 165, 165, 165,
111503 /* 1240 */ 20, 146, 147, 119, 56, 165, 150, 152, 16, 154,
111504 /* 1250 */ 150, 86, 87, 88, 66, 160, 150, 150, 93, 94,
111505 /* 1260 */ 95, 165, 150, 98, 108, 165, 127, 23, 65, 173,
111506 /* 1270 */ 174, 165, 165, 150, 86, 87, 128, 165, 150, 173,
111507 /* 1280 */ 174, 93, 94, 95, 23, 150, 98, 15, 165, 194,
111508 /* 1290 */ 150, 140, 22, 165, 129, 130, 131, 132, 133, 134,
111509 /* 1300 */ 165, 173, 174, 3, 116, 165, 19, 20, 150, 22,
111510 /* 1310 */ 4, 150, 217, 26, 27, 179, 179, 129, 130, 131,
111511 /* 1320 */ 132, 133, 134, 165, 37, 150, 165, 150, 164, 19,
111512 /* 1330 */ 20, 150, 22, 246, 149, 249, 26, 27, 249, 244,
111513 /* 1340 */ 165, 150, 165, 56, 6, 150, 165, 37, 173, 174,
111514 /* 1350 */ 173, 174, 150, 66, 173, 174, 165, 149, 149, 13,
111515 /* 1360 */ 165, 25, 150, 150, 150, 149, 56, 165, 150, 116,
111516 /* 1370 */ 151, 150, 150, 86, 87, 150, 66, 165, 165, 165,
111517 /* 1380 */ 93, 94, 95, 165, 150, 98, 165, 165, 151, 22,
111518 /* 1390 */ 165, 194, 150, 26, 27, 150, 86, 87, 159, 165,
111519 /* 1400 */ 199, 126, 123, 93, 94, 95, 200, 165, 98, 124,
111520 /* 1410 */ 165, 122, 201, 125, 225, 135, 129, 130, 131, 132,
111521 /* 1420 */ 133, 134, 5, 157, 157, 202, 118, 10, 11, 12,
111522 /* 1430 */ 13, 14, 203, 66, 17, 104, 210, 121, 211, 129,
111523 /* 1440 */ 130, 131, 132, 133, 134, 210, 175, 211, 31, 211,
111524 /* 1450 */ 33, 210, 104, 86, 87, 47, 175, 183, 175, 42,
111525 /* 1460 */ 103, 94, 178, 177, 22, 98, 175, 92, 228, 175,
111526 /* 1470 */ 175, 228, 55, 183, 57, 178, 175, 156, 61, 18,
111527 /* 1480 */ 157, 64, 156, 235, 157, 156, 45, 157, 236, 157,
111528 /* 1490 */ 135, 156, 199, 189, 157, 68, 129, 130, 131, 22,
111529 /* 1500 */ 189, 199, 157, 156, 192, 18, 192, 192, 199, 192,
111530 /* 1510 */ 218, 189, 40, 157, 218, 157, 240, 240, 157, 38,
111531 /* 1520 */ 196, 243, 105, 106, 107, 153, 198, 209, 111, 166,
111532 /* 1530 */ 176, 181, 166, 116, 166, 230, 176, 230, 176, 226,
111533 /* 1540 */ 199, 177, 239, 209, 185, 148, 166, 195, 209, 196,
111534 /* 1550 */ 199, 208, 182, 233, 173, 182, 139, 186, 239, 234,
111535 /* 1560 */ 191, 182, 173, 92,
111537 #define YY_SHIFT_USE_DFLT (-70)
111538 #define YY_SHIFT_COUNT (417)
111539 #define YY_SHIFT_MIN (-69)
111540 #define YY_SHIFT_MAX (1487)
111541 static const short yy_shift_ofst[] = {
111542 /* 0 */ 1143, 1188, 1417, 1188, 1287, 1287, 138, 138, -2, -19,
111543 /* 10 */ 1287, 1287, 1287, 1287, 347, 362, 129, 129, 795, 1165,
111544 /* 20 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
111545 /* 30 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
111546 /* 40 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
111547 /* 50 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
111548 /* 60 */ 1287, 1287, 286, 362, 362, 538, 538, 231, 1253, 55,
111549 /* 70 */ 721, 647, 573, 499, 425, 351, 277, 203, 869, 869,
111550 /* 80 */ 869, 869, 869, 869, 869, 869, 869, 869, 869, 869,
111551 /* 90 */ 869, 869, 869, 943, 869, 1017, 1091, 1091, -69, -45,
111552 /* 100 */ -45, -45, -45, -45, -1, 24, 245, 362, 362, 362,
111553 /* 110 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
111554 /* 120 */ 362, 362, 362, 388, 356, 362, 362, 362, 362, 362,
111555 /* 130 */ 732, 868, 231, 1051, 1471, -70, -70, -70, 1367, 57,
111556 /* 140 */ 434, 434, 289, 291, 285, 1, 204, 572, 539, 362,
111557 /* 150 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
111558 /* 160 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
111559 /* 170 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
111560 /* 180 */ 362, 506, 506, 506, 705, 1253, 1253, 1253, -70, -70,
111561 /* 190 */ -70, 171, 171, 160, 502, 502, 502, 446, 432, 511,
111562 /* 200 */ 422, 358, 335, -12, -12, -12, -12, 576, 294, -12,
111563 /* 210 */ -12, 295, 595, 141, 600, 730, 723, 723, 805, 730,
111564 /* 220 */ 805, 439, 911, 231, 865, 231, 865, 807, 865, 723,
111565 /* 230 */ 766, 633, 633, 231, 284, 63, 608, 1481, 1308, 1308,
111566 /* 240 */ 1472, 1472, 1308, 1477, 1427, 1275, 1487, 1487, 1487, 1487,
111567 /* 250 */ 1308, 1461, 1275, 1477, 1427, 1427, 1275, 1308, 1461, 1355,
111568 /* 260 */ 1441, 1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348,
111569 /* 270 */ 1348, 1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408,
111570 /* 280 */ 1348, 1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308,
111571 /* 290 */ 1280, 1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346,
111572 /* 300 */ 1338, 1338, 1338, 1338, -70, -70, -70, -70, -70, -70,
111573 /* 310 */ 1013, 467, 612, 84, 179, -28, 870, 410, 761, 760,
111574 /* 320 */ 667, 650, 531, 220, 361, 331, 125, 127, 97, 1306,
111575 /* 330 */ 1300, 1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174,
111576 /* 340 */ 1139, 1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184,
111577 /* 350 */ 1174, 1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152,
111578 /* 360 */ 1147, 1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032, 960,
111579 /* 370 */ 1057, 1031, 1030, 899, 938, 982, 936, 972, 958, 910,
111580 /* 380 */ 955, 875, 885, 908, 857, 859, 867, 804, 590, 834,
111581 /* 390 */ 747, 818, 513, 611, 741, 673, 637, 611, 606, 603,
111582 /* 400 */ 579, 501, 541, 468, 386, 445, 395, 376, 281, 185,
111583 /* 410 */ 120, 92, 75, 45, 114, 25, 11, 5,
111585 #define YY_REDUCE_USE_DFLT (-169)
111586 #define YY_REDUCE_COUNT (309)
111587 #define YY_REDUCE_MIN (-168)
111588 #define YY_REDUCE_MAX (1397)
111589 static const short yy_reduce_ofst[] = {
111590 /* 0 */ -141, 90, 1095, 222, 158, 156, 19, 17, 10, -104,
111591 /* 10 */ 378, 316, 311, 12, 180, 249, 598, 464, 397, 1181,
111592 /* 20 */ 1177, 1175, 1128, 1106, 1096, 1054, 1038, 974, 964, 962,
111593 /* 30 */ 948, 905, 903, 900, 887, 874, 832, 826, 816, 813,
111594 /* 40 */ 800, 758, 755, 752, 742, 739, 726, 685, 681, 668,
111595 /* 50 */ 665, 652, 607, 604, 594, 591, 578, 530, 528, 526,
111596 /* 60 */ 385, 18, 477, 466, 519, 444, 350, 435, 405, 488,
111597 /* 70 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
111598 /* 80 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
111599 /* 90 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
111600 /* 100 */ 488, 488, 488, 488, 488, 488, 488, 1040, 678, 1036,
111601 /* 110 */ 1007, 967, 966, 965, 845, 686, 610, 684, 317, 672,
111602 /* 120 */ 893, 327, 623, 522, -7, 820, 814, 157, 154, 101,
111603 /* 130 */ 702, 494, 580, 488, 488, 488, 488, 488, 614, 586,
111604 /* 140 */ 935, 892, 968, 1245, 1242, 1234, 1225, 798, 798, 1222,
111605 /* 150 */ 1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
111606 /* 160 */ 1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
111607 /* 170 */ 1070, 1067, 1048, 1044, 969, 968, 907, 906, 904, 894,
111608 /* 180 */ 833, 837, 836, 340, 827, 815, 775, 68, 722, 646,
111609 /* 190 */ -168, 1389, 1381, 1371, 1379, 1373, 1370, 1343, 1352, 1369,
111610 /* 200 */ 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1325, 1320, 1352,
111611 /* 210 */ 1352, 1343, 1380, 1353, 1397, 1351, 1339, 1334, 1319, 1341,
111612 /* 220 */ 1303, 1364, 1359, 1368, 1362, 1366, 1360, 1350, 1354, 1318,
111613 /* 230 */ 1313, 1307, 1305, 1363, 1328, 1324, 1372, 1278, 1361, 1358,
111614 /* 240 */ 1277, 1276, 1356, 1296, 1322, 1309, 1317, 1315, 1314, 1312,
111615 /* 250 */ 1345, 1347, 1302, 1292, 1311, 1304, 1293, 1337, 1335, 1252,
111616 /* 260 */ 1248, 1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301,
111617 /* 270 */ 1295, 1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274,
111618 /* 280 */ 1281, 1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266,
111619 /* 290 */ 1189, 1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219,
111620 /* 300 */ 1216, 1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
111622 static const YYACTIONTYPE yy_default[] = {
111623 /* 0 */ 633, 867, 955, 955, 867, 867, 955, 955, 955, 757,
111624 /* 10 */ 955, 955, 955, 865, 955, 955, 785, 785, 929, 955,
111625 /* 20 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111626 /* 30 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111627 /* 40 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111628 /* 50 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111629 /* 60 */ 955, 955, 955, 955, 955, 955, 955, 672, 761, 791,
111630 /* 70 */ 955, 955, 955, 955, 955, 955, 955, 955, 928, 930,
111631 /* 80 */ 799, 798, 908, 772, 796, 789, 793, 868, 861, 862,
111632 /* 90 */ 860, 864, 869, 955, 792, 828, 845, 827, 839, 844,
111633 /* 100 */ 851, 843, 840, 830, 829, 831, 832, 955, 955, 955,
111634 /* 110 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111635 /* 120 */ 955, 955, 955, 659, 726, 955, 955, 955, 955, 955,
111636 /* 130 */ 955, 955, 955, 833, 834, 848, 847, 846, 955, 664,
111637 /* 140 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111638 /* 150 */ 935, 933, 955, 880, 955, 955, 955, 955, 955, 955,
111639 /* 160 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111640 /* 170 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111641 /* 180 */ 639, 757, 757, 757, 633, 955, 955, 955, 947, 761,
111642 /* 190 */ 751, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111643 /* 200 */ 955, 955, 955, 801, 740, 918, 920, 955, 901, 738,
111644 /* 210 */ 661, 759, 674, 749, 641, 795, 774, 774, 913, 795,
111645 /* 220 */ 913, 697, 720, 955, 785, 955, 785, 694, 785, 774,
111646 /* 230 */ 863, 955, 955, 955, 758, 749, 955, 940, 765, 765,
111647 /* 240 */ 932, 932, 765, 807, 730, 795, 737, 737, 737, 737,
111648 /* 250 */ 765, 656, 795, 807, 730, 730, 795, 765, 656, 907,
111649 /* 260 */ 905, 765, 765, 656, 765, 656, 765, 656, 873, 728,
111650 /* 270 */ 728, 728, 712, 877, 877, 873, 728, 697, 728, 712,
111651 /* 280 */ 728, 728, 778, 773, 778, 773, 778, 773, 765, 765,
111652 /* 290 */ 955, 790, 779, 788, 786, 795, 955, 715, 649, 649,
111653 /* 300 */ 638, 638, 638, 638, 952, 952, 947, 699, 699, 682,
111654 /* 310 */ 955, 955, 955, 955, 955, 955, 955, 882, 955, 955,
111655 /* 320 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111656 /* 330 */ 634, 942, 955, 955, 939, 955, 955, 955, 955, 800,
111657 /* 340 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111658 /* 350 */ 917, 955, 955, 955, 955, 955, 955, 955, 911, 955,
111659 /* 360 */ 955, 955, 955, 955, 955, 904, 903, 955, 955, 955,
111660 /* 370 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111661 /* 380 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
111662 /* 390 */ 955, 955, 955, 787, 955, 780, 955, 866, 955, 955,
111663 /* 400 */ 955, 955, 955, 955, 955, 955, 955, 955, 743, 816,
111664 /* 410 */ 955, 815, 819, 814, 666, 955, 647, 955, 630, 635,
111665 /* 420 */ 951, 954, 953, 950, 949, 948, 943, 941, 938, 937,
111666 /* 430 */ 936, 934, 931, 927, 886, 884, 891, 890, 889, 888,
111667 /* 440 */ 887, 885, 883, 881, 802, 797, 794, 926, 879, 739,
111668 /* 450 */ 736, 735, 655, 944, 910, 919, 806, 805, 808, 916,
111669 /* 460 */ 915, 914, 912, 909, 896, 804, 803, 731, 871, 870,
111670 /* 470 */ 658, 900, 899, 898, 902, 906, 897, 767, 657, 654,
111671 /* 480 */ 663, 718, 719, 727, 725, 724, 723, 722, 721, 717,
111672 /* 490 */ 665, 673, 711, 696, 695, 876, 878, 875, 874, 704,
111673 /* 500 */ 703, 709, 708, 707, 706, 705, 702, 701, 700, 693,
111674 /* 510 */ 692, 698, 691, 714, 713, 710, 690, 734, 733, 732,
111675 /* 520 */ 729, 689, 688, 687, 819, 686, 685, 825, 824, 812,
111676 /* 530 */ 855, 754, 753, 752, 764, 763, 776, 775, 810, 809,
111677 /* 540 */ 777, 762, 756, 755, 771, 770, 769, 768, 760, 750,
111678 /* 550 */ 782, 784, 783, 781, 857, 766, 854, 925, 924, 923,
111679 /* 560 */ 922, 921, 859, 858, 826, 823, 677, 678, 894, 893,
111680 /* 570 */ 895, 892, 680, 679, 676, 675, 856, 745, 744, 852,
111681 /* 580 */ 849, 841, 837, 853, 850, 842, 838, 836, 835, 821,
111682 /* 590 */ 820, 818, 817, 813, 822, 668, 746, 742, 741, 811,
111683 /* 600 */ 748, 747, 684, 683, 681, 662, 660, 653, 651, 650,
111684 /* 610 */ 652, 648, 646, 645, 644, 643, 642, 671, 670, 669,
111685 /* 620 */ 667, 666, 640, 637, 636, 632, 631, 629,
111688 /* The next table maps tokens into fallback tokens. If a construct
111689 ** like the following:
111691 ** %fallback ID X Y Z.
111693 ** appears in the grammar, then ID becomes a fallback token for X, Y,
111694 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
111695 ** but it does not parse, the type of the token is changed to ID and
111696 ** the parse is retried before an error is thrown.
111698 #ifdef YYFALLBACK
111699 static const YYCODETYPE yyFallback[] = {
111700 0, /* $ => nothing */
111701 0, /* SEMI => nothing */
111702 26, /* EXPLAIN => ID */
111703 26, /* QUERY => ID */
111704 26, /* PLAN => ID */
111705 26, /* BEGIN => ID */
111706 0, /* TRANSACTION => nothing */
111707 26, /* DEFERRED => ID */
111708 26, /* IMMEDIATE => ID */
111709 26, /* EXCLUSIVE => ID */
111710 0, /* COMMIT => nothing */
111711 26, /* END => ID */
111712 26, /* ROLLBACK => ID */
111713 26, /* SAVEPOINT => ID */
111714 26, /* RELEASE => ID */
111715 0, /* TO => nothing */
111716 0, /* TABLE => nothing */
111717 0, /* CREATE => nothing */
111718 26, /* IF => ID */
111719 0, /* NOT => nothing */
111720 0, /* EXISTS => nothing */
111721 26, /* TEMP => ID */
111722 0, /* LP => nothing */
111723 0, /* RP => nothing */
111724 0, /* AS => nothing */
111725 0, /* COMMA => nothing */
111726 0, /* ID => nothing */
111727 0, /* INDEXED => nothing */
111728 26, /* ABORT => ID */
111729 26, /* ACTION => ID */
111730 26, /* AFTER => ID */
111731 26, /* ANALYZE => ID */
111732 26, /* ASC => ID */
111733 26, /* ATTACH => ID */
111734 26, /* BEFORE => ID */
111735 26, /* BY => ID */
111736 26, /* CASCADE => ID */
111737 26, /* CAST => ID */
111738 26, /* COLUMNKW => ID */
111739 26, /* CONFLICT => ID */
111740 26, /* DATABASE => ID */
111741 26, /* DESC => ID */
111742 26, /* DETACH => ID */
111743 26, /* EACH => ID */
111744 26, /* FAIL => ID */
111745 26, /* FOR => ID */
111746 26, /* IGNORE => ID */
111747 26, /* INITIALLY => ID */
111748 26, /* INSTEAD => ID */
111749 26, /* LIKE_KW => ID */
111750 26, /* MATCH => ID */
111751 26, /* NO => ID */
111752 26, /* KEY => ID */
111753 26, /* OF => ID */
111754 26, /* OFFSET => ID */
111755 26, /* PRAGMA => ID */
111756 26, /* RAISE => ID */
111757 26, /* REPLACE => ID */
111758 26, /* RESTRICT => ID */
111759 26, /* ROW => ID */
111760 26, /* TRIGGER => ID */
111761 26, /* VACUUM => ID */
111762 26, /* VIEW => ID */
111763 26, /* VIRTUAL => ID */
111764 26, /* REINDEX => ID */
111765 26, /* RENAME => ID */
111766 26, /* CTIME_KW => ID */
111768 #endif /* YYFALLBACK */
111770 /* The following structure represents a single element of the
111771 ** parser's stack. Information stored includes:
111773 ** + The state number for the parser at this level of the stack.
111775 ** + The value of the token stored at this level of the stack.
111776 ** (In other words, the "major" token.)
111778 ** + The semantic value stored at this level of the stack. This is
111779 ** the information used by the action routines in the grammar.
111780 ** It is sometimes called the "minor" token.
111782 struct yyStackEntry {
111783 YYACTIONTYPE stateno; /* The state-number */
111784 YYCODETYPE major; /* The major token value. This is the code
111785 ** number for the token at this stack level */
111786 YYMINORTYPE minor; /* The user-supplied minor token value. This
111787 ** is the value of the token */
111789 typedef struct yyStackEntry yyStackEntry;
111791 /* The state of the parser is completely contained in an instance of
111792 ** the following structure */
111793 struct yyParser {
111794 int yyidx; /* Index of top element in stack */
111795 #ifdef YYTRACKMAXSTACKDEPTH
111796 int yyidxMax; /* Maximum value of yyidx */
111797 #endif
111798 int yyerrcnt; /* Shifts left before out of the error */
111799 sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
111800 #if YYSTACKDEPTH<=0
111801 int yystksz; /* Current side of the stack */
111802 yyStackEntry *yystack; /* The parser's stack */
111803 #else
111804 yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
111805 #endif
111807 typedef struct yyParser yyParser;
111809 #ifndef NDEBUG
111810 /* #include <stdio.h> */
111811 static FILE *yyTraceFILE = 0;
111812 static char *yyTracePrompt = 0;
111813 #endif /* NDEBUG */
111815 #ifndef NDEBUG
111817 ** Turn parser tracing on by giving a stream to which to write the trace
111818 ** and a prompt to preface each trace message. Tracing is turned off
111819 ** by making either argument NULL
111821 ** Inputs:
111822 ** <ul>
111823 ** <li> A FILE* to which trace output should be written.
111824 ** If NULL, then tracing is turned off.
111825 ** <li> A prefix string written at the beginning of every
111826 ** line of trace output. If NULL, then tracing is
111827 ** turned off.
111828 ** </ul>
111830 ** Outputs:
111831 ** None.
111833 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
111834 yyTraceFILE = TraceFILE;
111835 yyTracePrompt = zTracePrompt;
111836 if( yyTraceFILE==0 ) yyTracePrompt = 0;
111837 else if( yyTracePrompt==0 ) yyTraceFILE = 0;
111839 #endif /* NDEBUG */
111841 #ifndef NDEBUG
111842 /* For tracing shifts, the names of all terminals and nonterminals
111843 ** are required. The following table supplies these names */
111844 static const char *const yyTokenName[] = {
111845 "$", "SEMI", "EXPLAIN", "QUERY",
111846 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
111847 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
111848 "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
111849 "TABLE", "CREATE", "IF", "NOT",
111850 "EXISTS", "TEMP", "LP", "RP",
111851 "AS", "COMMA", "ID", "INDEXED",
111852 "ABORT", "ACTION", "AFTER", "ANALYZE",
111853 "ASC", "ATTACH", "BEFORE", "BY",
111854 "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
111855 "DATABASE", "DESC", "DETACH", "EACH",
111856 "FAIL", "FOR", "IGNORE", "INITIALLY",
111857 "INSTEAD", "LIKE_KW", "MATCH", "NO",
111858 "KEY", "OF", "OFFSET", "PRAGMA",
111859 "RAISE", "REPLACE", "RESTRICT", "ROW",
111860 "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
111861 "REINDEX", "RENAME", "CTIME_KW", "ANY",
111862 "OR", "AND", "IS", "BETWEEN",
111863 "IN", "ISNULL", "NOTNULL", "NE",
111864 "EQ", "GT", "LE", "LT",
111865 "GE", "ESCAPE", "BITAND", "BITOR",
111866 "LSHIFT", "RSHIFT", "PLUS", "MINUS",
111867 "STAR", "SLASH", "REM", "CONCAT",
111868 "COLLATE", "BITNOT", "STRING", "JOIN_KW",
111869 "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
111870 "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
111871 "ON", "INSERT", "DELETE", "UPDATE",
111872 "SET", "DEFERRABLE", "FOREIGN", "DROP",
111873 "UNION", "ALL", "EXCEPT", "INTERSECT",
111874 "SELECT", "DISTINCT", "DOT", "FROM",
111875 "JOIN", "USING", "ORDER", "GROUP",
111876 "HAVING", "LIMIT", "WHERE", "INTO",
111877 "VALUES", "INTEGER", "FLOAT", "BLOB",
111878 "REGISTER", "VARIABLE", "CASE", "WHEN",
111879 "THEN", "ELSE", "INDEX", "ALTER",
111880 "ADD", "error", "input", "cmdlist",
111881 "ecmd", "explain", "cmdx", "cmd",
111882 "transtype", "trans_opt", "nm", "savepoint_opt",
111883 "create_table", "create_table_args", "createkw", "temp",
111884 "ifnotexists", "dbnm", "columnlist", "conslist_opt",
111885 "select", "column", "columnid", "type",
111886 "carglist", "id", "ids", "typetoken",
111887 "typename", "signed", "plus_num", "minus_num",
111888 "ccons", "term", "expr", "onconf",
111889 "sortorder", "autoinc", "idxlist_opt", "refargs",
111890 "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
111891 "conslist", "tconscomma", "tcons", "idxlist",
111892 "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
111893 "ifexists", "fullname", "oneselect", "multiselect_op",
111894 "distinct", "selcollist", "from", "where_opt",
111895 "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
111896 "sclp", "as", "seltablist", "stl_prefix",
111897 "joinop", "indexed_opt", "on_opt", "using_opt",
111898 "joinop2", "inscollist", "sortlist", "nexprlist",
111899 "setlist", "insert_cmd", "inscollist_opt", "valuelist",
111900 "exprlist", "likeop", "between_op", "in_op",
111901 "case_operand", "case_exprlist", "case_else", "uniqueflag",
111902 "collate", "nmnum", "number", "trigger_decl",
111903 "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
111904 "when_clause", "trigger_cmd", "trnm", "tridxby",
111905 "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
111906 "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
111907 "lp", "anylist",
111909 #endif /* NDEBUG */
111911 #ifndef NDEBUG
111912 /* For tracing reduce actions, the names of all rules are required.
111914 static const char *const yyRuleName[] = {
111915 /* 0 */ "input ::= cmdlist",
111916 /* 1 */ "cmdlist ::= cmdlist ecmd",
111917 /* 2 */ "cmdlist ::= ecmd",
111918 /* 3 */ "ecmd ::= SEMI",
111919 /* 4 */ "ecmd ::= explain cmdx SEMI",
111920 /* 5 */ "explain ::=",
111921 /* 6 */ "explain ::= EXPLAIN",
111922 /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
111923 /* 8 */ "cmdx ::= cmd",
111924 /* 9 */ "cmd ::= BEGIN transtype trans_opt",
111925 /* 10 */ "trans_opt ::=",
111926 /* 11 */ "trans_opt ::= TRANSACTION",
111927 /* 12 */ "trans_opt ::= TRANSACTION nm",
111928 /* 13 */ "transtype ::=",
111929 /* 14 */ "transtype ::= DEFERRED",
111930 /* 15 */ "transtype ::= IMMEDIATE",
111931 /* 16 */ "transtype ::= EXCLUSIVE",
111932 /* 17 */ "cmd ::= COMMIT trans_opt",
111933 /* 18 */ "cmd ::= END trans_opt",
111934 /* 19 */ "cmd ::= ROLLBACK trans_opt",
111935 /* 20 */ "savepoint_opt ::= SAVEPOINT",
111936 /* 21 */ "savepoint_opt ::=",
111937 /* 22 */ "cmd ::= SAVEPOINT nm",
111938 /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
111939 /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
111940 /* 25 */ "cmd ::= create_table create_table_args",
111941 /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
111942 /* 27 */ "createkw ::= CREATE",
111943 /* 28 */ "ifnotexists ::=",
111944 /* 29 */ "ifnotexists ::= IF NOT EXISTS",
111945 /* 30 */ "temp ::= TEMP",
111946 /* 31 */ "temp ::=",
111947 /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
111948 /* 33 */ "create_table_args ::= AS select",
111949 /* 34 */ "columnlist ::= columnlist COMMA column",
111950 /* 35 */ "columnlist ::= column",
111951 /* 36 */ "column ::= columnid type carglist",
111952 /* 37 */ "columnid ::= nm",
111953 /* 38 */ "id ::= ID",
111954 /* 39 */ "id ::= INDEXED",
111955 /* 40 */ "ids ::= ID|STRING",
111956 /* 41 */ "nm ::= id",
111957 /* 42 */ "nm ::= STRING",
111958 /* 43 */ "nm ::= JOIN_KW",
111959 /* 44 */ "type ::=",
111960 /* 45 */ "type ::= typetoken",
111961 /* 46 */ "typetoken ::= typename",
111962 /* 47 */ "typetoken ::= typename LP signed RP",
111963 /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
111964 /* 49 */ "typename ::= ids",
111965 /* 50 */ "typename ::= typename ids",
111966 /* 51 */ "signed ::= plus_num",
111967 /* 52 */ "signed ::= minus_num",
111968 /* 53 */ "carglist ::= carglist ccons",
111969 /* 54 */ "carglist ::=",
111970 /* 55 */ "ccons ::= CONSTRAINT nm",
111971 /* 56 */ "ccons ::= DEFAULT term",
111972 /* 57 */ "ccons ::= DEFAULT LP expr RP",
111973 /* 58 */ "ccons ::= DEFAULT PLUS term",
111974 /* 59 */ "ccons ::= DEFAULT MINUS term",
111975 /* 60 */ "ccons ::= DEFAULT id",
111976 /* 61 */ "ccons ::= NULL onconf",
111977 /* 62 */ "ccons ::= NOT NULL onconf",
111978 /* 63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
111979 /* 64 */ "ccons ::= UNIQUE onconf",
111980 /* 65 */ "ccons ::= CHECK LP expr RP",
111981 /* 66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
111982 /* 67 */ "ccons ::= defer_subclause",
111983 /* 68 */ "ccons ::= COLLATE ids",
111984 /* 69 */ "autoinc ::=",
111985 /* 70 */ "autoinc ::= AUTOINCR",
111986 /* 71 */ "refargs ::=",
111987 /* 72 */ "refargs ::= refargs refarg",
111988 /* 73 */ "refarg ::= MATCH nm",
111989 /* 74 */ "refarg ::= ON INSERT refact",
111990 /* 75 */ "refarg ::= ON DELETE refact",
111991 /* 76 */ "refarg ::= ON UPDATE refact",
111992 /* 77 */ "refact ::= SET NULL",
111993 /* 78 */ "refact ::= SET DEFAULT",
111994 /* 79 */ "refact ::= CASCADE",
111995 /* 80 */ "refact ::= RESTRICT",
111996 /* 81 */ "refact ::= NO ACTION",
111997 /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
111998 /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
111999 /* 84 */ "init_deferred_pred_opt ::=",
112000 /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
112001 /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
112002 /* 87 */ "conslist_opt ::=",
112003 /* 88 */ "conslist_opt ::= COMMA conslist",
112004 /* 89 */ "conslist ::= conslist tconscomma tcons",
112005 /* 90 */ "conslist ::= tcons",
112006 /* 91 */ "tconscomma ::= COMMA",
112007 /* 92 */ "tconscomma ::=",
112008 /* 93 */ "tcons ::= CONSTRAINT nm",
112009 /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
112010 /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
112011 /* 96 */ "tcons ::= CHECK LP expr RP onconf",
112012 /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
112013 /* 98 */ "defer_subclause_opt ::=",
112014 /* 99 */ "defer_subclause_opt ::= defer_subclause",
112015 /* 100 */ "onconf ::=",
112016 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
112017 /* 102 */ "orconf ::=",
112018 /* 103 */ "orconf ::= OR resolvetype",
112019 /* 104 */ "resolvetype ::= raisetype",
112020 /* 105 */ "resolvetype ::= IGNORE",
112021 /* 106 */ "resolvetype ::= REPLACE",
112022 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
112023 /* 108 */ "ifexists ::= IF EXISTS",
112024 /* 109 */ "ifexists ::=",
112025 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
112026 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
112027 /* 112 */ "cmd ::= select",
112028 /* 113 */ "select ::= oneselect",
112029 /* 114 */ "select ::= select multiselect_op oneselect",
112030 /* 115 */ "multiselect_op ::= UNION",
112031 /* 116 */ "multiselect_op ::= UNION ALL",
112032 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
112033 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
112034 /* 119 */ "distinct ::= DISTINCT",
112035 /* 120 */ "distinct ::= ALL",
112036 /* 121 */ "distinct ::=",
112037 /* 122 */ "sclp ::= selcollist COMMA",
112038 /* 123 */ "sclp ::=",
112039 /* 124 */ "selcollist ::= sclp expr as",
112040 /* 125 */ "selcollist ::= sclp STAR",
112041 /* 126 */ "selcollist ::= sclp nm DOT STAR",
112042 /* 127 */ "as ::= AS nm",
112043 /* 128 */ "as ::= ids",
112044 /* 129 */ "as ::=",
112045 /* 130 */ "from ::=",
112046 /* 131 */ "from ::= FROM seltablist",
112047 /* 132 */ "stl_prefix ::= seltablist joinop",
112048 /* 133 */ "stl_prefix ::=",
112049 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
112050 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
112051 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
112052 /* 137 */ "dbnm ::=",
112053 /* 138 */ "dbnm ::= DOT nm",
112054 /* 139 */ "fullname ::= nm dbnm",
112055 /* 140 */ "joinop ::= COMMA|JOIN",
112056 /* 141 */ "joinop ::= JOIN_KW JOIN",
112057 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
112058 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
112059 /* 144 */ "on_opt ::= ON expr",
112060 /* 145 */ "on_opt ::=",
112061 /* 146 */ "indexed_opt ::=",
112062 /* 147 */ "indexed_opt ::= INDEXED BY nm",
112063 /* 148 */ "indexed_opt ::= NOT INDEXED",
112064 /* 149 */ "using_opt ::= USING LP inscollist RP",
112065 /* 150 */ "using_opt ::=",
112066 /* 151 */ "orderby_opt ::=",
112067 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
112068 /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
112069 /* 154 */ "sortlist ::= expr sortorder",
112070 /* 155 */ "sortorder ::= ASC",
112071 /* 156 */ "sortorder ::= DESC",
112072 /* 157 */ "sortorder ::=",
112073 /* 158 */ "groupby_opt ::=",
112074 /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
112075 /* 160 */ "having_opt ::=",
112076 /* 161 */ "having_opt ::= HAVING expr",
112077 /* 162 */ "limit_opt ::=",
112078 /* 163 */ "limit_opt ::= LIMIT expr",
112079 /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
112080 /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
112081 /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
112082 /* 167 */ "where_opt ::=",
112083 /* 168 */ "where_opt ::= WHERE expr",
112084 /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
112085 /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
112086 /* 171 */ "setlist ::= nm EQ expr",
112087 /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
112088 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
112089 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
112090 /* 175 */ "insert_cmd ::= INSERT orconf",
112091 /* 176 */ "insert_cmd ::= REPLACE",
112092 /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
112093 /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
112094 /* 179 */ "inscollist_opt ::=",
112095 /* 180 */ "inscollist_opt ::= LP inscollist RP",
112096 /* 181 */ "inscollist ::= inscollist COMMA nm",
112097 /* 182 */ "inscollist ::= nm",
112098 /* 183 */ "expr ::= term",
112099 /* 184 */ "expr ::= LP expr RP",
112100 /* 185 */ "term ::= NULL",
112101 /* 186 */ "expr ::= id",
112102 /* 187 */ "expr ::= JOIN_KW",
112103 /* 188 */ "expr ::= nm DOT nm",
112104 /* 189 */ "expr ::= nm DOT nm DOT nm",
112105 /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
112106 /* 191 */ "term ::= STRING",
112107 /* 192 */ "expr ::= REGISTER",
112108 /* 193 */ "expr ::= VARIABLE",
112109 /* 194 */ "expr ::= expr COLLATE ids",
112110 /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
112111 /* 196 */ "expr ::= ID LP distinct exprlist RP",
112112 /* 197 */ "expr ::= ID LP STAR RP",
112113 /* 198 */ "term ::= CTIME_KW",
112114 /* 199 */ "expr ::= expr AND expr",
112115 /* 200 */ "expr ::= expr OR expr",
112116 /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
112117 /* 202 */ "expr ::= expr EQ|NE expr",
112118 /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
112119 /* 204 */ "expr ::= expr PLUS|MINUS expr",
112120 /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
112121 /* 206 */ "expr ::= expr CONCAT expr",
112122 /* 207 */ "likeop ::= LIKE_KW",
112123 /* 208 */ "likeop ::= NOT LIKE_KW",
112124 /* 209 */ "likeop ::= MATCH",
112125 /* 210 */ "likeop ::= NOT MATCH",
112126 /* 211 */ "expr ::= expr likeop expr",
112127 /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
112128 /* 213 */ "expr ::= expr ISNULL|NOTNULL",
112129 /* 214 */ "expr ::= expr NOT NULL",
112130 /* 215 */ "expr ::= expr IS expr",
112131 /* 216 */ "expr ::= expr IS NOT expr",
112132 /* 217 */ "expr ::= NOT expr",
112133 /* 218 */ "expr ::= BITNOT expr",
112134 /* 219 */ "expr ::= MINUS expr",
112135 /* 220 */ "expr ::= PLUS expr",
112136 /* 221 */ "between_op ::= BETWEEN",
112137 /* 222 */ "between_op ::= NOT BETWEEN",
112138 /* 223 */ "expr ::= expr between_op expr AND expr",
112139 /* 224 */ "in_op ::= IN",
112140 /* 225 */ "in_op ::= NOT IN",
112141 /* 226 */ "expr ::= expr in_op LP exprlist RP",
112142 /* 227 */ "expr ::= LP select RP",
112143 /* 228 */ "expr ::= expr in_op LP select RP",
112144 /* 229 */ "expr ::= expr in_op nm dbnm",
112145 /* 230 */ "expr ::= EXISTS LP select RP",
112146 /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
112147 /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
112148 /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
112149 /* 234 */ "case_else ::= ELSE expr",
112150 /* 235 */ "case_else ::=",
112151 /* 236 */ "case_operand ::= expr",
112152 /* 237 */ "case_operand ::=",
112153 /* 238 */ "exprlist ::= nexprlist",
112154 /* 239 */ "exprlist ::=",
112155 /* 240 */ "nexprlist ::= nexprlist COMMA expr",
112156 /* 241 */ "nexprlist ::= expr",
112157 /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
112158 /* 243 */ "uniqueflag ::= UNIQUE",
112159 /* 244 */ "uniqueflag ::=",
112160 /* 245 */ "idxlist_opt ::=",
112161 /* 246 */ "idxlist_opt ::= LP idxlist RP",
112162 /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
112163 /* 248 */ "idxlist ::= nm collate sortorder",
112164 /* 249 */ "collate ::=",
112165 /* 250 */ "collate ::= COLLATE ids",
112166 /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
112167 /* 252 */ "cmd ::= VACUUM",
112168 /* 253 */ "cmd ::= VACUUM nm",
112169 /* 254 */ "cmd ::= PRAGMA nm dbnm",
112170 /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
112171 /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
112172 /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
112173 /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
112174 /* 259 */ "nmnum ::= plus_num",
112175 /* 260 */ "nmnum ::= nm",
112176 /* 261 */ "nmnum ::= ON",
112177 /* 262 */ "nmnum ::= DELETE",
112178 /* 263 */ "nmnum ::= DEFAULT",
112179 /* 264 */ "plus_num ::= PLUS number",
112180 /* 265 */ "plus_num ::= number",
112181 /* 266 */ "minus_num ::= MINUS number",
112182 /* 267 */ "number ::= INTEGER|FLOAT",
112183 /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
112184 /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
112185 /* 270 */ "trigger_time ::= BEFORE",
112186 /* 271 */ "trigger_time ::= AFTER",
112187 /* 272 */ "trigger_time ::= INSTEAD OF",
112188 /* 273 */ "trigger_time ::=",
112189 /* 274 */ "trigger_event ::= DELETE|INSERT",
112190 /* 275 */ "trigger_event ::= UPDATE",
112191 /* 276 */ "trigger_event ::= UPDATE OF inscollist",
112192 /* 277 */ "foreach_clause ::=",
112193 /* 278 */ "foreach_clause ::= FOR EACH ROW",
112194 /* 279 */ "when_clause ::=",
112195 /* 280 */ "when_clause ::= WHEN expr",
112196 /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
112197 /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
112198 /* 283 */ "trnm ::= nm",
112199 /* 284 */ "trnm ::= nm DOT nm",
112200 /* 285 */ "tridxby ::=",
112201 /* 286 */ "tridxby ::= INDEXED BY nm",
112202 /* 287 */ "tridxby ::= NOT INDEXED",
112203 /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
112204 /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
112205 /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
112206 /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
112207 /* 292 */ "trigger_cmd ::= select",
112208 /* 293 */ "expr ::= RAISE LP IGNORE RP",
112209 /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
112210 /* 295 */ "raisetype ::= ROLLBACK",
112211 /* 296 */ "raisetype ::= ABORT",
112212 /* 297 */ "raisetype ::= FAIL",
112213 /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
112214 /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
112215 /* 300 */ "cmd ::= DETACH database_kw_opt expr",
112216 /* 301 */ "key_opt ::=",
112217 /* 302 */ "key_opt ::= KEY expr",
112218 /* 303 */ "database_kw_opt ::= DATABASE",
112219 /* 304 */ "database_kw_opt ::=",
112220 /* 305 */ "cmd ::= REINDEX",
112221 /* 306 */ "cmd ::= REINDEX nm dbnm",
112222 /* 307 */ "cmd ::= ANALYZE",
112223 /* 308 */ "cmd ::= ANALYZE nm dbnm",
112224 /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
112225 /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
112226 /* 311 */ "add_column_fullname ::= fullname",
112227 /* 312 */ "kwcolumn_opt ::=",
112228 /* 313 */ "kwcolumn_opt ::= COLUMNKW",
112229 /* 314 */ "cmd ::= create_vtab",
112230 /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
112231 /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
112232 /* 317 */ "vtabarglist ::= vtabarg",
112233 /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
112234 /* 319 */ "vtabarg ::=",
112235 /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
112236 /* 321 */ "vtabargtoken ::= ANY",
112237 /* 322 */ "vtabargtoken ::= lp anylist RP",
112238 /* 323 */ "lp ::= LP",
112239 /* 324 */ "anylist ::=",
112240 /* 325 */ "anylist ::= anylist LP anylist RP",
112241 /* 326 */ "anylist ::= anylist ANY",
112243 #endif /* NDEBUG */
112246 #if YYSTACKDEPTH<=0
112248 ** Try to increase the size of the parser stack.
112250 static void yyGrowStack(yyParser *p){
112251 int newSize;
112252 yyStackEntry *pNew;
112254 newSize = p->yystksz*2 + 100;
112255 pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
112256 if( pNew ){
112257 p->yystack = pNew;
112258 p->yystksz = newSize;
112259 #ifndef NDEBUG
112260 if( yyTraceFILE ){
112261 fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
112262 yyTracePrompt, p->yystksz);
112264 #endif
112267 #endif
112270 ** This function allocates a new parser.
112271 ** The only argument is a pointer to a function which works like
112272 ** malloc.
112274 ** Inputs:
112275 ** A pointer to the function used to allocate memory.
112277 ** Outputs:
112278 ** A pointer to a parser. This pointer is used in subsequent calls
112279 ** to sqlite3Parser and sqlite3ParserFree.
112281 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
112282 yyParser *pParser;
112283 pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
112284 if( pParser ){
112285 pParser->yyidx = -1;
112286 #ifdef YYTRACKMAXSTACKDEPTH
112287 pParser->yyidxMax = 0;
112288 #endif
112289 #if YYSTACKDEPTH<=0
112290 pParser->yystack = NULL;
112291 pParser->yystksz = 0;
112292 yyGrowStack(pParser);
112293 #endif
112295 return pParser;
112298 /* The following function deletes the value associated with a
112299 ** symbol. The symbol can be either a terminal or nonterminal.
112300 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
112301 ** the value.
112303 static void yy_destructor(
112304 yyParser *yypParser, /* The parser */
112305 YYCODETYPE yymajor, /* Type code for object to destroy */
112306 YYMINORTYPE *yypminor /* The object to be destroyed */
112308 sqlite3ParserARG_FETCH;
112309 switch( yymajor ){
112310 /* Here is inserted the actions which take place when a
112311 ** terminal or non-terminal is destroyed. This can happen
112312 ** when the symbol is popped from the stack during a
112313 ** reduce or during error processing or when a parser is
112314 ** being destroyed before it is finished parsing.
112316 ** Note: during a reduce, the only symbols destroyed are those
112317 ** which appear on the RHS of the rule, but which are not used
112318 ** inside the C code.
112320 case 160: /* select */
112321 case 194: /* oneselect */
112323 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
112325 break;
112326 case 173: /* term */
112327 case 174: /* expr */
112329 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
112331 break;
112332 case 178: /* idxlist_opt */
112333 case 187: /* idxlist */
112334 case 197: /* selcollist */
112335 case 200: /* groupby_opt */
112336 case 202: /* orderby_opt */
112337 case 204: /* sclp */
112338 case 214: /* sortlist */
112339 case 215: /* nexprlist */
112340 case 216: /* setlist */
112341 case 220: /* exprlist */
112342 case 225: /* case_exprlist */
112344 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
112346 break;
112347 case 193: /* fullname */
112348 case 198: /* from */
112349 case 206: /* seltablist */
112350 case 207: /* stl_prefix */
112352 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
112354 break;
112355 case 199: /* where_opt */
112356 case 201: /* having_opt */
112357 case 210: /* on_opt */
112358 case 224: /* case_operand */
112359 case 226: /* case_else */
112360 case 236: /* when_clause */
112361 case 241: /* key_opt */
112363 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
112365 break;
112366 case 211: /* using_opt */
112367 case 213: /* inscollist */
112368 case 218: /* inscollist_opt */
112370 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
112372 break;
112373 case 219: /* valuelist */
112376 sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
112377 sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
112380 break;
112381 case 232: /* trigger_cmd_list */
112382 case 237: /* trigger_cmd */
112384 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
112386 break;
112387 case 234: /* trigger_event */
112389 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
112391 break;
112392 default: break; /* If no destructor action specified: do nothing */
112397 ** Pop the parser's stack once.
112399 ** If there is a destructor routine associated with the token which
112400 ** is popped from the stack, then call it.
112402 ** Return the major token number for the symbol popped.
112404 static int yy_pop_parser_stack(yyParser *pParser){
112405 YYCODETYPE yymajor;
112406 yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
112408 /* There is no mechanism by which the parser stack can be popped below
112409 ** empty in SQLite. */
112410 if( NEVER(pParser->yyidx<0) ) return 0;
112411 #ifndef NDEBUG
112412 if( yyTraceFILE && pParser->yyidx>=0 ){
112413 fprintf(yyTraceFILE,"%sPopping %s\n",
112414 yyTracePrompt,
112415 yyTokenName[yytos->major]);
112417 #endif
112418 yymajor = yytos->major;
112419 yy_destructor(pParser, yymajor, &yytos->minor);
112420 pParser->yyidx--;
112421 return yymajor;
112425 ** Deallocate and destroy a parser. Destructors are all called for
112426 ** all stack elements before shutting the parser down.
112428 ** Inputs:
112429 ** <ul>
112430 ** <li> A pointer to the parser. This should be a pointer
112431 ** obtained from sqlite3ParserAlloc.
112432 ** <li> A pointer to a function used to reclaim memory obtained
112433 ** from malloc.
112434 ** </ul>
112436 SQLITE_PRIVATE void sqlite3ParserFree(
112437 void *p, /* The parser to be deleted */
112438 void (*freeProc)(void*) /* Function used to reclaim memory */
112440 yyParser *pParser = (yyParser*)p;
112441 /* In SQLite, we never try to destroy a parser that was not successfully
112442 ** created in the first place. */
112443 if( NEVER(pParser==0) ) return;
112444 while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
112445 #if YYSTACKDEPTH<=0
112446 free(pParser->yystack);
112447 #endif
112448 (*freeProc)((void*)pParser);
112452 ** Return the peak depth of the stack for a parser.
112454 #ifdef YYTRACKMAXSTACKDEPTH
112455 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
112456 yyParser *pParser = (yyParser*)p;
112457 return pParser->yyidxMax;
112459 #endif
112462 ** Find the appropriate action for a parser given the terminal
112463 ** look-ahead token iLookAhead.
112465 ** If the look-ahead token is YYNOCODE, then check to see if the action is
112466 ** independent of the look-ahead. If it is, return the action, otherwise
112467 ** return YY_NO_ACTION.
112469 static int yy_find_shift_action(
112470 yyParser *pParser, /* The parser */
112471 YYCODETYPE iLookAhead /* The look-ahead token */
112473 int i;
112474 int stateno = pParser->yystack[pParser->yyidx].stateno;
112476 if( stateno>YY_SHIFT_COUNT
112477 || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
112478 return yy_default[stateno];
112480 assert( iLookAhead!=YYNOCODE );
112481 i += iLookAhead;
112482 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
112483 if( iLookAhead>0 ){
112484 #ifdef YYFALLBACK
112485 YYCODETYPE iFallback; /* Fallback token */
112486 if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
112487 && (iFallback = yyFallback[iLookAhead])!=0 ){
112488 #ifndef NDEBUG
112489 if( yyTraceFILE ){
112490 fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
112491 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
112493 #endif
112494 return yy_find_shift_action(pParser, iFallback);
112496 #endif
112497 #ifdef YYWILDCARD
112499 int j = i - iLookAhead + YYWILDCARD;
112501 #if YY_SHIFT_MIN+YYWILDCARD<0
112502 j>=0 &&
112503 #endif
112504 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
112505 j<YY_ACTTAB_COUNT &&
112506 #endif
112507 yy_lookahead[j]==YYWILDCARD
112509 #ifndef NDEBUG
112510 if( yyTraceFILE ){
112511 fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
112512 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
112514 #endif /* NDEBUG */
112515 return yy_action[j];
112518 #endif /* YYWILDCARD */
112520 return yy_default[stateno];
112521 }else{
112522 return yy_action[i];
112527 ** Find the appropriate action for a parser given the non-terminal
112528 ** look-ahead token iLookAhead.
112530 ** If the look-ahead token is YYNOCODE, then check to see if the action is
112531 ** independent of the look-ahead. If it is, return the action, otherwise
112532 ** return YY_NO_ACTION.
112534 static int yy_find_reduce_action(
112535 int stateno, /* Current state number */
112536 YYCODETYPE iLookAhead /* The look-ahead token */
112538 int i;
112539 #ifdef YYERRORSYMBOL
112540 if( stateno>YY_REDUCE_COUNT ){
112541 return yy_default[stateno];
112543 #else
112544 assert( stateno<=YY_REDUCE_COUNT );
112545 #endif
112546 i = yy_reduce_ofst[stateno];
112547 assert( i!=YY_REDUCE_USE_DFLT );
112548 assert( iLookAhead!=YYNOCODE );
112549 i += iLookAhead;
112550 #ifdef YYERRORSYMBOL
112551 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
112552 return yy_default[stateno];
112554 #else
112555 assert( i>=0 && i<YY_ACTTAB_COUNT );
112556 assert( yy_lookahead[i]==iLookAhead );
112557 #endif
112558 return yy_action[i];
112562 ** The following routine is called if the stack overflows.
112564 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
112565 sqlite3ParserARG_FETCH;
112566 yypParser->yyidx--;
112567 #ifndef NDEBUG
112568 if( yyTraceFILE ){
112569 fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
112571 #endif
112572 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
112573 /* Here code is inserted which will execute if the parser
112574 ** stack every overflows */
112576 UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
112577 sqlite3ErrorMsg(pParse, "parser stack overflow");
112578 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
112582 ** Perform a shift action.
112584 static void yy_shift(
112585 yyParser *yypParser, /* The parser to be shifted */
112586 int yyNewState, /* The new state to shift in */
112587 int yyMajor, /* The major token to shift in */
112588 YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
112590 yyStackEntry *yytos;
112591 yypParser->yyidx++;
112592 #ifdef YYTRACKMAXSTACKDEPTH
112593 if( yypParser->yyidx>yypParser->yyidxMax ){
112594 yypParser->yyidxMax = yypParser->yyidx;
112596 #endif
112597 #if YYSTACKDEPTH>0
112598 if( yypParser->yyidx>=YYSTACKDEPTH ){
112599 yyStackOverflow(yypParser, yypMinor);
112600 return;
112602 #else
112603 if( yypParser->yyidx>=yypParser->yystksz ){
112604 yyGrowStack(yypParser);
112605 if( yypParser->yyidx>=yypParser->yystksz ){
112606 yyStackOverflow(yypParser, yypMinor);
112607 return;
112610 #endif
112611 yytos = &yypParser->yystack[yypParser->yyidx];
112612 yytos->stateno = (YYACTIONTYPE)yyNewState;
112613 yytos->major = (YYCODETYPE)yyMajor;
112614 yytos->minor = *yypMinor;
112615 #ifndef NDEBUG
112616 if( yyTraceFILE && yypParser->yyidx>0 ){
112617 int i;
112618 fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
112619 fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
112620 for(i=1; i<=yypParser->yyidx; i++)
112621 fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
112622 fprintf(yyTraceFILE,"\n");
112624 #endif
112627 /* The following table contains information about every rule that
112628 ** is used during the reduce.
112630 static const struct {
112631 YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
112632 unsigned char nrhs; /* Number of right-hand side symbols in the rule */
112633 } yyRuleInfo[] = {
112634 { 142, 1 },
112635 { 143, 2 },
112636 { 143, 1 },
112637 { 144, 1 },
112638 { 144, 3 },
112639 { 145, 0 },
112640 { 145, 1 },
112641 { 145, 3 },
112642 { 146, 1 },
112643 { 147, 3 },
112644 { 149, 0 },
112645 { 149, 1 },
112646 { 149, 2 },
112647 { 148, 0 },
112648 { 148, 1 },
112649 { 148, 1 },
112650 { 148, 1 },
112651 { 147, 2 },
112652 { 147, 2 },
112653 { 147, 2 },
112654 { 151, 1 },
112655 { 151, 0 },
112656 { 147, 2 },
112657 { 147, 3 },
112658 { 147, 5 },
112659 { 147, 2 },
112660 { 152, 6 },
112661 { 154, 1 },
112662 { 156, 0 },
112663 { 156, 3 },
112664 { 155, 1 },
112665 { 155, 0 },
112666 { 153, 4 },
112667 { 153, 2 },
112668 { 158, 3 },
112669 { 158, 1 },
112670 { 161, 3 },
112671 { 162, 1 },
112672 { 165, 1 },
112673 { 165, 1 },
112674 { 166, 1 },
112675 { 150, 1 },
112676 { 150, 1 },
112677 { 150, 1 },
112678 { 163, 0 },
112679 { 163, 1 },
112680 { 167, 1 },
112681 { 167, 4 },
112682 { 167, 6 },
112683 { 168, 1 },
112684 { 168, 2 },
112685 { 169, 1 },
112686 { 169, 1 },
112687 { 164, 2 },
112688 { 164, 0 },
112689 { 172, 2 },
112690 { 172, 2 },
112691 { 172, 4 },
112692 { 172, 3 },
112693 { 172, 3 },
112694 { 172, 2 },
112695 { 172, 2 },
112696 { 172, 3 },
112697 { 172, 5 },
112698 { 172, 2 },
112699 { 172, 4 },
112700 { 172, 4 },
112701 { 172, 1 },
112702 { 172, 2 },
112703 { 177, 0 },
112704 { 177, 1 },
112705 { 179, 0 },
112706 { 179, 2 },
112707 { 181, 2 },
112708 { 181, 3 },
112709 { 181, 3 },
112710 { 181, 3 },
112711 { 182, 2 },
112712 { 182, 2 },
112713 { 182, 1 },
112714 { 182, 1 },
112715 { 182, 2 },
112716 { 180, 3 },
112717 { 180, 2 },
112718 { 183, 0 },
112719 { 183, 2 },
112720 { 183, 2 },
112721 { 159, 0 },
112722 { 159, 2 },
112723 { 184, 3 },
112724 { 184, 1 },
112725 { 185, 1 },
112726 { 185, 0 },
112727 { 186, 2 },
112728 { 186, 7 },
112729 { 186, 5 },
112730 { 186, 5 },
112731 { 186, 10 },
112732 { 188, 0 },
112733 { 188, 1 },
112734 { 175, 0 },
112735 { 175, 3 },
112736 { 189, 0 },
112737 { 189, 2 },
112738 { 190, 1 },
112739 { 190, 1 },
112740 { 190, 1 },
112741 { 147, 4 },
112742 { 192, 2 },
112743 { 192, 0 },
112744 { 147, 8 },
112745 { 147, 4 },
112746 { 147, 1 },
112747 { 160, 1 },
112748 { 160, 3 },
112749 { 195, 1 },
112750 { 195, 2 },
112751 { 195, 1 },
112752 { 194, 9 },
112753 { 196, 1 },
112754 { 196, 1 },
112755 { 196, 0 },
112756 { 204, 2 },
112757 { 204, 0 },
112758 { 197, 3 },
112759 { 197, 2 },
112760 { 197, 4 },
112761 { 205, 2 },
112762 { 205, 1 },
112763 { 205, 0 },
112764 { 198, 0 },
112765 { 198, 2 },
112766 { 207, 2 },
112767 { 207, 0 },
112768 { 206, 7 },
112769 { 206, 7 },
112770 { 206, 7 },
112771 { 157, 0 },
112772 { 157, 2 },
112773 { 193, 2 },
112774 { 208, 1 },
112775 { 208, 2 },
112776 { 208, 3 },
112777 { 208, 4 },
112778 { 210, 2 },
112779 { 210, 0 },
112780 { 209, 0 },
112781 { 209, 3 },
112782 { 209, 2 },
112783 { 211, 4 },
112784 { 211, 0 },
112785 { 202, 0 },
112786 { 202, 3 },
112787 { 214, 4 },
112788 { 214, 2 },
112789 { 176, 1 },
112790 { 176, 1 },
112791 { 176, 0 },
112792 { 200, 0 },
112793 { 200, 3 },
112794 { 201, 0 },
112795 { 201, 2 },
112796 { 203, 0 },
112797 { 203, 2 },
112798 { 203, 4 },
112799 { 203, 4 },
112800 { 147, 5 },
112801 { 199, 0 },
112802 { 199, 2 },
112803 { 147, 7 },
112804 { 216, 5 },
112805 { 216, 3 },
112806 { 147, 5 },
112807 { 147, 5 },
112808 { 147, 6 },
112809 { 217, 2 },
112810 { 217, 1 },
112811 { 219, 4 },
112812 { 219, 5 },
112813 { 218, 0 },
112814 { 218, 3 },
112815 { 213, 3 },
112816 { 213, 1 },
112817 { 174, 1 },
112818 { 174, 3 },
112819 { 173, 1 },
112820 { 174, 1 },
112821 { 174, 1 },
112822 { 174, 3 },
112823 { 174, 5 },
112824 { 173, 1 },
112825 { 173, 1 },
112826 { 174, 1 },
112827 { 174, 1 },
112828 { 174, 3 },
112829 { 174, 6 },
112830 { 174, 5 },
112831 { 174, 4 },
112832 { 173, 1 },
112833 { 174, 3 },
112834 { 174, 3 },
112835 { 174, 3 },
112836 { 174, 3 },
112837 { 174, 3 },
112838 { 174, 3 },
112839 { 174, 3 },
112840 { 174, 3 },
112841 { 221, 1 },
112842 { 221, 2 },
112843 { 221, 1 },
112844 { 221, 2 },
112845 { 174, 3 },
112846 { 174, 5 },
112847 { 174, 2 },
112848 { 174, 3 },
112849 { 174, 3 },
112850 { 174, 4 },
112851 { 174, 2 },
112852 { 174, 2 },
112853 { 174, 2 },
112854 { 174, 2 },
112855 { 222, 1 },
112856 { 222, 2 },
112857 { 174, 5 },
112858 { 223, 1 },
112859 { 223, 2 },
112860 { 174, 5 },
112861 { 174, 3 },
112862 { 174, 5 },
112863 { 174, 4 },
112864 { 174, 4 },
112865 { 174, 5 },
112866 { 225, 5 },
112867 { 225, 4 },
112868 { 226, 2 },
112869 { 226, 0 },
112870 { 224, 1 },
112871 { 224, 0 },
112872 { 220, 1 },
112873 { 220, 0 },
112874 { 215, 3 },
112875 { 215, 1 },
112876 { 147, 12 },
112877 { 227, 1 },
112878 { 227, 0 },
112879 { 178, 0 },
112880 { 178, 3 },
112881 { 187, 5 },
112882 { 187, 3 },
112883 { 228, 0 },
112884 { 228, 2 },
112885 { 147, 4 },
112886 { 147, 1 },
112887 { 147, 2 },
112888 { 147, 3 },
112889 { 147, 5 },
112890 { 147, 6 },
112891 { 147, 5 },
112892 { 147, 6 },
112893 { 229, 1 },
112894 { 229, 1 },
112895 { 229, 1 },
112896 { 229, 1 },
112897 { 229, 1 },
112898 { 170, 2 },
112899 { 170, 1 },
112900 { 171, 2 },
112901 { 230, 1 },
112902 { 147, 5 },
112903 { 231, 11 },
112904 { 233, 1 },
112905 { 233, 1 },
112906 { 233, 2 },
112907 { 233, 0 },
112908 { 234, 1 },
112909 { 234, 1 },
112910 { 234, 3 },
112911 { 235, 0 },
112912 { 235, 3 },
112913 { 236, 0 },
112914 { 236, 2 },
112915 { 232, 3 },
112916 { 232, 2 },
112917 { 238, 1 },
112918 { 238, 3 },
112919 { 239, 0 },
112920 { 239, 3 },
112921 { 239, 2 },
112922 { 237, 7 },
112923 { 237, 5 },
112924 { 237, 5 },
112925 { 237, 5 },
112926 { 237, 1 },
112927 { 174, 4 },
112928 { 174, 6 },
112929 { 191, 1 },
112930 { 191, 1 },
112931 { 191, 1 },
112932 { 147, 4 },
112933 { 147, 6 },
112934 { 147, 3 },
112935 { 241, 0 },
112936 { 241, 2 },
112937 { 240, 1 },
112938 { 240, 0 },
112939 { 147, 1 },
112940 { 147, 3 },
112941 { 147, 1 },
112942 { 147, 3 },
112943 { 147, 6 },
112944 { 147, 6 },
112945 { 242, 1 },
112946 { 243, 0 },
112947 { 243, 1 },
112948 { 147, 1 },
112949 { 147, 4 },
112950 { 244, 8 },
112951 { 245, 1 },
112952 { 245, 3 },
112953 { 246, 0 },
112954 { 246, 2 },
112955 { 247, 1 },
112956 { 247, 3 },
112957 { 248, 1 },
112958 { 249, 0 },
112959 { 249, 4 },
112960 { 249, 2 },
112963 static void yy_accept(yyParser*); /* Forward Declaration */
112966 ** Perform a reduce action and the shift that must immediately
112967 ** follow the reduce.
112969 static void yy_reduce(
112970 yyParser *yypParser, /* The parser */
112971 int yyruleno /* Number of the rule by which to reduce */
112973 int yygoto; /* The next state */
112974 int yyact; /* The next action */
112975 YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
112976 yyStackEntry *yymsp; /* The top of the parser's stack */
112977 int yysize; /* Amount to pop the stack */
112978 sqlite3ParserARG_FETCH;
112979 yymsp = &yypParser->yystack[yypParser->yyidx];
112980 #ifndef NDEBUG
112981 if( yyTraceFILE && yyruleno>=0
112982 && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
112983 fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
112984 yyRuleName[yyruleno]);
112986 #endif /* NDEBUG */
112988 /* Silence complaints from purify about yygotominor being uninitialized
112989 ** in some cases when it is copied into the stack after the following
112990 ** switch. yygotominor is uninitialized when a rule reduces that does
112991 ** not set the value of its left-hand side nonterminal. Leaving the
112992 ** value of the nonterminal uninitialized is utterly harmless as long
112993 ** as the value is never used. So really the only thing this code
112994 ** accomplishes is to quieten purify.
112996 ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
112997 ** without this code, their parser segfaults. I'm not sure what there
112998 ** parser is doing to make this happen. This is the second bug report
112999 ** from wireshark this week. Clearly they are stressing Lemon in ways
113000 ** that it has not been previously stressed... (SQLite ticket #2172)
113002 /*memset(&yygotominor, 0, sizeof(yygotominor));*/
113003 yygotominor = yyzerominor;
113006 switch( yyruleno ){
113007 /* Beginning here are the reduction cases. A typical example
113008 ** follows:
113009 ** case 0:
113010 ** #line <lineno> <grammarfile>
113011 ** { ... } // User supplied code
113012 ** #line <lineno> <thisfile>
113013 ** break;
113015 case 5: /* explain ::= */
113016 { sqlite3BeginParse(pParse, 0); }
113017 break;
113018 case 6: /* explain ::= EXPLAIN */
113019 { sqlite3BeginParse(pParse, 1); }
113020 break;
113021 case 7: /* explain ::= EXPLAIN QUERY PLAN */
113022 { sqlite3BeginParse(pParse, 2); }
113023 break;
113024 case 8: /* cmdx ::= cmd */
113025 { sqlite3FinishCoding(pParse); }
113026 break;
113027 case 9: /* cmd ::= BEGIN transtype trans_opt */
113028 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
113029 break;
113030 case 13: /* transtype ::= */
113031 {yygotominor.yy392 = TK_DEFERRED;}
113032 break;
113033 case 14: /* transtype ::= DEFERRED */
113034 case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
113035 case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
113036 case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
113037 case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
113038 {yygotominor.yy392 = yymsp[0].major;}
113039 break;
113040 case 17: /* cmd ::= COMMIT trans_opt */
113041 case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
113042 {sqlite3CommitTransaction(pParse);}
113043 break;
113044 case 19: /* cmd ::= ROLLBACK trans_opt */
113045 {sqlite3RollbackTransaction(pParse);}
113046 break;
113047 case 22: /* cmd ::= SAVEPOINT nm */
113049 sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
113051 break;
113052 case 23: /* cmd ::= RELEASE savepoint_opt nm */
113054 sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
113056 break;
113057 case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
113059 sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
113061 break;
113062 case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
113064 sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
113066 break;
113067 case 27: /* createkw ::= CREATE */
113069 pParse->db->lookaside.bEnabled = 0;
113070 yygotominor.yy0 = yymsp[0].minor.yy0;
113072 break;
113073 case 28: /* ifnotexists ::= */
113074 case 31: /* temp ::= */ yytestcase(yyruleno==31);
113075 case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
113076 case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
113077 case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
113078 case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
113079 case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
113080 case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
113081 case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
113082 case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
113083 {yygotominor.yy392 = 0;}
113084 break;
113085 case 29: /* ifnotexists ::= IF NOT EXISTS */
113086 case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
113087 case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
113088 case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
113089 case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
113090 case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
113091 case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
113092 {yygotominor.yy392 = 1;}
113093 break;
113094 case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
113096 sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
113098 break;
113099 case 33: /* create_table_args ::= AS select */
113101 sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
113102 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
113104 break;
113105 case 36: /* column ::= columnid type carglist */
113107 yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
113108 yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
113110 break;
113111 case 37: /* columnid ::= nm */
113113 sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
113114 yygotominor.yy0 = yymsp[0].minor.yy0;
113115 pParse->constraintName.n = 0;
113117 break;
113118 case 38: /* id ::= ID */
113119 case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
113120 case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
113121 case 41: /* nm ::= id */ yytestcase(yyruleno==41);
113122 case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
113123 case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
113124 case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
113125 case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
113126 case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
113127 case 128: /* as ::= ids */ yytestcase(yyruleno==128);
113128 case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
113129 case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
113130 case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
113131 case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
113132 case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
113133 case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
113134 case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
113135 case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
113136 case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
113137 case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
113138 case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
113139 case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
113140 case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
113141 {yygotominor.yy0 = yymsp[0].minor.yy0;}
113142 break;
113143 case 45: /* type ::= typetoken */
113144 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
113145 break;
113146 case 47: /* typetoken ::= typename LP signed RP */
113148 yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
113149 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
113151 break;
113152 case 48: /* typetoken ::= typename LP signed COMMA signed RP */
113154 yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
113155 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
113157 break;
113158 case 50: /* typename ::= typename ids */
113159 {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);}
113160 break;
113161 case 55: /* ccons ::= CONSTRAINT nm */
113162 case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
113163 {pParse->constraintName = yymsp[0].minor.yy0;}
113164 break;
113165 case 56: /* ccons ::= DEFAULT term */
113166 case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
113167 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
113168 break;
113169 case 57: /* ccons ::= DEFAULT LP expr RP */
113170 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
113171 break;
113172 case 59: /* ccons ::= DEFAULT MINUS term */
113174 ExprSpan v;
113175 v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
113176 v.zStart = yymsp[-1].minor.yy0.z;
113177 v.zEnd = yymsp[0].minor.yy342.zEnd;
113178 sqlite3AddDefaultValue(pParse,&v);
113180 break;
113181 case 60: /* ccons ::= DEFAULT id */
113183 ExprSpan v;
113184 spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
113185 sqlite3AddDefaultValue(pParse,&v);
113187 break;
113188 case 62: /* ccons ::= NOT NULL onconf */
113189 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
113190 break;
113191 case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
113192 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
113193 break;
113194 case 64: /* ccons ::= UNIQUE onconf */
113195 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
113196 break;
113197 case 65: /* ccons ::= CHECK LP expr RP */
113198 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
113199 break;
113200 case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
113201 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
113202 break;
113203 case 67: /* ccons ::= defer_subclause */
113204 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
113205 break;
113206 case 68: /* ccons ::= COLLATE ids */
113207 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
113208 break;
113209 case 71: /* refargs ::= */
113210 { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
113211 break;
113212 case 72: /* refargs ::= refargs refarg */
113213 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
113214 break;
113215 case 73: /* refarg ::= MATCH nm */
113216 case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
113217 { yygotominor.yy207.value = 0; yygotominor.yy207.mask = 0x000000; }
113218 break;
113219 case 75: /* refarg ::= ON DELETE refact */
113220 { yygotominor.yy207.value = yymsp[0].minor.yy392; yygotominor.yy207.mask = 0x0000ff; }
113221 break;
113222 case 76: /* refarg ::= ON UPDATE refact */
113223 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8; yygotominor.yy207.mask = 0x00ff00; }
113224 break;
113225 case 77: /* refact ::= SET NULL */
113226 { yygotominor.yy392 = OE_SetNull; /* EV: R-33326-45252 */}
113227 break;
113228 case 78: /* refact ::= SET DEFAULT */
113229 { yygotominor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */}
113230 break;
113231 case 79: /* refact ::= CASCADE */
113232 { yygotominor.yy392 = OE_Cascade; /* EV: R-33326-45252 */}
113233 break;
113234 case 80: /* refact ::= RESTRICT */
113235 { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
113236 break;
113237 case 81: /* refact ::= NO ACTION */
113238 { yygotominor.yy392 = OE_None; /* EV: R-33326-45252 */}
113239 break;
113240 case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
113241 case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
113242 case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
113243 case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
113244 {yygotominor.yy392 = yymsp[0].minor.yy392;}
113245 break;
113246 case 87: /* conslist_opt ::= */
113247 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
113248 break;
113249 case 88: /* conslist_opt ::= COMMA conslist */
113250 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
113251 break;
113252 case 91: /* tconscomma ::= COMMA */
113253 {pParse->constraintName.n = 0;}
113254 break;
113255 case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
113256 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
113257 break;
113258 case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
113259 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
113260 break;
113261 case 96: /* tcons ::= CHECK LP expr RP onconf */
113262 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
113263 break;
113264 case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
113266 sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
113267 sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
113269 break;
113270 case 100: /* onconf ::= */
113271 {yygotominor.yy392 = OE_Default;}
113272 break;
113273 case 102: /* orconf ::= */
113274 {yygotominor.yy258 = OE_Default;}
113275 break;
113276 case 103: /* orconf ::= OR resolvetype */
113277 {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
113278 break;
113279 case 105: /* resolvetype ::= IGNORE */
113280 {yygotominor.yy392 = OE_Ignore;}
113281 break;
113282 case 106: /* resolvetype ::= REPLACE */
113283 {yygotominor.yy392 = OE_Replace;}
113284 break;
113285 case 107: /* cmd ::= DROP TABLE ifexists fullname */
113287 sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
113289 break;
113290 case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
113292 sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
113294 break;
113295 case 111: /* cmd ::= DROP VIEW ifexists fullname */
113297 sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
113299 break;
113300 case 112: /* cmd ::= select */
113302 SelectDest dest = {SRT_Output, 0, 0, 0, 0};
113303 sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
113304 sqlite3ExplainBegin(pParse->pVdbe);
113305 sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
113306 sqlite3ExplainFinish(pParse->pVdbe);
113307 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
113309 break;
113310 case 113: /* select ::= oneselect */
113311 {yygotominor.yy159 = yymsp[0].minor.yy159;}
113312 break;
113313 case 114: /* select ::= select multiselect_op oneselect */
113315 if( yymsp[0].minor.yy159 ){
113316 yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
113317 yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
113318 if( yymsp[-1].minor.yy392!=TK_ALL ) pParse->hasCompound = 1;
113319 }else{
113320 sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
113322 yygotominor.yy159 = yymsp[0].minor.yy159;
113324 break;
113325 case 116: /* multiselect_op ::= UNION ALL */
113326 {yygotominor.yy392 = TK_ALL;}
113327 break;
113328 case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
113330 yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy305,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
113332 break;
113333 case 119: /* distinct ::= DISTINCT */
113334 {yygotominor.yy305 = SF_Distinct;}
113335 break;
113336 case 120: /* distinct ::= ALL */
113337 case 121: /* distinct ::= */ yytestcase(yyruleno==121);
113338 {yygotominor.yy305 = 0;}
113339 break;
113340 case 122: /* sclp ::= selcollist COMMA */
113341 case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
113342 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
113343 break;
113344 case 123: /* sclp ::= */
113345 case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
113346 case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
113347 case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
113348 case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
113349 {yygotominor.yy442 = 0;}
113350 break;
113351 case 124: /* selcollist ::= sclp expr as */
113353 yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
113354 if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
113355 sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
113357 break;
113358 case 125: /* selcollist ::= sclp STAR */
113360 Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
113361 yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
113363 break;
113364 case 126: /* selcollist ::= sclp nm DOT STAR */
113366 Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
113367 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
113368 Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
113369 yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
113371 break;
113372 case 129: /* as ::= */
113373 {yygotominor.yy0.n = 0;}
113374 break;
113375 case 130: /* from ::= */
113376 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
113377 break;
113378 case 131: /* from ::= FROM seltablist */
113380 yygotominor.yy347 = yymsp[0].minor.yy347;
113381 sqlite3SrcListShiftJoinType(yygotominor.yy347);
113383 break;
113384 case 132: /* stl_prefix ::= seltablist joinop */
113386 yygotominor.yy347 = yymsp[-1].minor.yy347;
113387 if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
113389 break;
113390 case 133: /* stl_prefix ::= */
113391 {yygotominor.yy347 = 0;}
113392 break;
113393 case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
113395 yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
113396 sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
113398 break;
113399 case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
113401 yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
113403 break;
113404 case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
113406 if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
113407 yygotominor.yy347 = yymsp[-4].minor.yy347;
113408 }else if( yymsp[-4].minor.yy347->nSrc==1 ){
113409 yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
113410 if( yygotominor.yy347 ){
113411 struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
113412 struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
113413 pNew->zName = pOld->zName;
113414 pNew->zDatabase = pOld->zDatabase;
113415 pNew->pSelect = pOld->pSelect;
113416 pOld->zName = pOld->zDatabase = 0;
113417 pOld->pSelect = 0;
113419 sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
113420 }else{
113421 Select *pSubquery;
113422 sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
113423 pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
113424 yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
113427 break;
113428 case 137: /* dbnm ::= */
113429 case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
113430 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
113431 break;
113432 case 139: /* fullname ::= nm dbnm */
113433 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
113434 break;
113435 case 140: /* joinop ::= COMMA|JOIN */
113436 { yygotominor.yy392 = JT_INNER; }
113437 break;
113438 case 141: /* joinop ::= JOIN_KW JOIN */
113439 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
113440 break;
113441 case 142: /* joinop ::= JOIN_KW nm JOIN */
113442 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
113443 break;
113444 case 143: /* joinop ::= JOIN_KW nm nm JOIN */
113445 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
113446 break;
113447 case 144: /* on_opt ::= ON expr */
113448 case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
113449 case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
113450 case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
113451 case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
113452 {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
113453 break;
113454 case 145: /* on_opt ::= */
113455 case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
113456 case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
113457 case 235: /* case_else ::= */ yytestcase(yyruleno==235);
113458 case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
113459 {yygotominor.yy122 = 0;}
113460 break;
113461 case 148: /* indexed_opt ::= NOT INDEXED */
113462 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
113463 break;
113464 case 149: /* using_opt ::= USING LP inscollist RP */
113465 case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
113466 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
113467 break;
113468 case 150: /* using_opt ::= */
113469 case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
113470 {yygotominor.yy180 = 0;}
113471 break;
113472 case 152: /* orderby_opt ::= ORDER BY sortlist */
113473 case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
113474 case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
113475 {yygotominor.yy442 = yymsp[0].minor.yy442;}
113476 break;
113477 case 153: /* sortlist ::= sortlist COMMA expr sortorder */
113479 yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
113480 if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
113482 break;
113483 case 154: /* sortlist ::= expr sortorder */
113485 yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
113486 if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
113488 break;
113489 case 155: /* sortorder ::= ASC */
113490 case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
113491 {yygotominor.yy392 = SQLITE_SO_ASC;}
113492 break;
113493 case 156: /* sortorder ::= DESC */
113494 {yygotominor.yy392 = SQLITE_SO_DESC;}
113495 break;
113496 case 162: /* limit_opt ::= */
113497 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
113498 break;
113499 case 163: /* limit_opt ::= LIMIT expr */
113500 {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
113501 break;
113502 case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
113503 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
113504 break;
113505 case 165: /* limit_opt ::= LIMIT expr COMMA expr */
113506 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
113507 break;
113508 case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
113510 sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
113511 sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
113513 break;
113514 case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
113516 sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
113517 sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
113518 sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
113520 break;
113521 case 170: /* setlist ::= setlist COMMA nm EQ expr */
113523 yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
113524 sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
113526 break;
113527 case 171: /* setlist ::= nm EQ expr */
113529 yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
113530 sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
113532 break;
113533 case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
113534 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
113535 break;
113536 case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
113537 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
113538 break;
113539 case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
113540 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
113541 break;
113542 case 175: /* insert_cmd ::= INSERT orconf */
113543 {yygotominor.yy258 = yymsp[0].minor.yy258;}
113544 break;
113545 case 176: /* insert_cmd ::= REPLACE */
113546 {yygotominor.yy258 = OE_Replace;}
113547 break;
113548 case 177: /* valuelist ::= VALUES LP nexprlist RP */
113550 yygotominor.yy487.pList = yymsp[-1].minor.yy442;
113551 yygotominor.yy487.pSelect = 0;
113553 break;
113554 case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
113556 Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
113557 if( yymsp[-4].minor.yy487.pList ){
113558 yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
113559 yymsp[-4].minor.yy487.pList = 0;
113561 yygotominor.yy487.pList = 0;
113562 if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
113563 sqlite3SelectDelete(pParse->db, pRight);
113564 sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
113565 yygotominor.yy487.pSelect = 0;
113566 }else{
113567 pRight->op = TK_ALL;
113568 pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
113569 pRight->selFlags |= SF_Values;
113570 pRight->pPrior->selFlags |= SF_Values;
113571 yygotominor.yy487.pSelect = pRight;
113574 break;
113575 case 181: /* inscollist ::= inscollist COMMA nm */
113576 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
113577 break;
113578 case 182: /* inscollist ::= nm */
113579 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
113580 break;
113581 case 183: /* expr ::= term */
113582 {yygotominor.yy342 = yymsp[0].minor.yy342;}
113583 break;
113584 case 184: /* expr ::= LP expr RP */
113585 {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
113586 break;
113587 case 185: /* term ::= NULL */
113588 case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
113589 case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
113590 {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
113591 break;
113592 case 186: /* expr ::= id */
113593 case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
113594 {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
113595 break;
113596 case 188: /* expr ::= nm DOT nm */
113598 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
113599 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
113600 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
113601 spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
113603 break;
113604 case 189: /* expr ::= nm DOT nm DOT nm */
113606 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
113607 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
113608 Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
113609 Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
113610 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
113611 spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
113613 break;
113614 case 192: /* expr ::= REGISTER */
113616 /* When doing a nested parse, one can include terms in an expression
113617 ** that look like this: #1 #2 ... These terms refer to registers
113618 ** in the virtual machine. #N is the N-th register. */
113619 if( pParse->nested==0 ){
113620 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
113621 yygotominor.yy342.pExpr = 0;
113622 }else{
113623 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
113624 if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
113626 spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
113628 break;
113629 case 193: /* expr ::= VARIABLE */
113631 spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
113632 sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
113633 spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
113635 break;
113636 case 194: /* expr ::= expr COLLATE ids */
113638 yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
113639 yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
113640 yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113642 break;
113643 case 195: /* expr ::= CAST LP expr AS typetoken RP */
113645 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
113646 spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
113648 break;
113649 case 196: /* expr ::= ID LP distinct exprlist RP */
113651 if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
113652 sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
113654 yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
113655 spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
113656 if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
113657 yygotominor.yy342.pExpr->flags |= EP_Distinct;
113660 break;
113661 case 197: /* expr ::= ID LP STAR RP */
113663 yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
113664 spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
113666 break;
113667 case 198: /* term ::= CTIME_KW */
113669 /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
113670 ** treated as functions that return constants */
113671 yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
113672 if( yygotominor.yy342.pExpr ){
113673 yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
113675 spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
113677 break;
113678 case 199: /* expr ::= expr AND expr */
113679 case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
113680 case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
113681 case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
113682 case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
113683 case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
113684 case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
113685 case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
113686 {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
113687 break;
113688 case 207: /* likeop ::= LIKE_KW */
113689 case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
113690 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
113691 break;
113692 case 208: /* likeop ::= NOT LIKE_KW */
113693 case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
113694 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
113695 break;
113696 case 211: /* expr ::= expr likeop expr */
113698 ExprList *pList;
113699 pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
113700 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
113701 yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
113702 if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
113703 yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
113704 yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
113705 if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
113707 break;
113708 case 212: /* expr ::= expr likeop expr ESCAPE expr */
113710 ExprList *pList;
113711 pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
113712 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
113713 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
113714 yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
113715 if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
113716 yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
113717 yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
113718 if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
113720 break;
113721 case 213: /* expr ::= expr ISNULL|NOTNULL */
113722 {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
113723 break;
113724 case 214: /* expr ::= expr NOT NULL */
113725 {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
113726 break;
113727 case 215: /* expr ::= expr IS expr */
113729 spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
113730 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
113732 break;
113733 case 216: /* expr ::= expr IS NOT expr */
113735 spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
113736 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
113738 break;
113739 case 217: /* expr ::= NOT expr */
113740 case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
113741 {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
113742 break;
113743 case 219: /* expr ::= MINUS expr */
113744 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
113745 break;
113746 case 220: /* expr ::= PLUS expr */
113747 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
113748 break;
113749 case 223: /* expr ::= expr between_op expr AND expr */
113751 ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
113752 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
113753 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
113754 if( yygotominor.yy342.pExpr ){
113755 yygotominor.yy342.pExpr->x.pList = pList;
113756 }else{
113757 sqlite3ExprListDelete(pParse->db, pList);
113759 if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
113760 yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
113761 yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
113763 break;
113764 case 226: /* expr ::= expr in_op LP exprlist RP */
113766 if( yymsp[-1].minor.yy442==0 ){
113767 /* Expressions of the form
113769 ** expr1 IN ()
113770 ** expr1 NOT IN ()
113772 ** simplify to constants 0 (false) and 1 (true), respectively,
113773 ** regardless of the value of expr1.
113775 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
113776 sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
113777 }else{
113778 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
113779 if( yygotominor.yy342.pExpr ){
113780 yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
113781 sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113782 }else{
113783 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
113785 if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
113787 yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
113788 yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113790 break;
113791 case 227: /* expr ::= LP select RP */
113793 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
113794 if( yygotominor.yy342.pExpr ){
113795 yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
113796 ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
113797 sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113798 }else{
113799 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
113801 yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
113802 yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113804 break;
113805 case 228: /* expr ::= expr in_op LP select RP */
113807 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
113808 if( yygotominor.yy342.pExpr ){
113809 yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
113810 ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
113811 sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113812 }else{
113813 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
113815 if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
113816 yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
113817 yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113819 break;
113820 case 229: /* expr ::= expr in_op nm dbnm */
113822 SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
113823 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
113824 if( yygotominor.yy342.pExpr ){
113825 yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
113826 ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
113827 sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113828 }else{
113829 sqlite3SrcListDelete(pParse->db, pSrc);
113831 if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
113832 yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
113833 yygotominor.yy342.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];
113835 break;
113836 case 230: /* expr ::= EXISTS LP select RP */
113838 Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
113839 if( p ){
113840 p->x.pSelect = yymsp[-1].minor.yy159;
113841 ExprSetProperty(p, EP_xIsSelect);
113842 sqlite3ExprSetHeight(pParse, p);
113843 }else{
113844 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
113846 yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
113847 yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113849 break;
113850 case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
113852 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
113853 if( yygotominor.yy342.pExpr ){
113854 yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
113855 sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113856 }else{
113857 sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
113859 yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
113860 yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113862 break;
113863 case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
113865 yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
113866 yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
113868 break;
113869 case 233: /* case_exprlist ::= WHEN expr THEN expr */
113871 yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
113872 yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
113874 break;
113875 case 240: /* nexprlist ::= nexprlist COMMA expr */
113876 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
113877 break;
113878 case 241: /* nexprlist ::= expr */
113879 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
113880 break;
113881 case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
113883 sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
113884 sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy442, yymsp[-10].minor.yy392,
113885 &yymsp[-11].minor.yy0, yymsp[0].minor.yy122, SQLITE_SO_ASC, yymsp[-8].minor.yy392);
113887 break;
113888 case 243: /* uniqueflag ::= UNIQUE */
113889 case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
113890 {yygotominor.yy392 = OE_Abort;}
113891 break;
113892 case 244: /* uniqueflag ::= */
113893 {yygotominor.yy392 = OE_None;}
113894 break;
113895 case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
113897 Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
113898 yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
113899 sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
113900 sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
113901 if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
113903 break;
113904 case 248: /* idxlist ::= nm collate sortorder */
113906 Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
113907 yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
113908 sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
113909 sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
113910 if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
113912 break;
113913 case 249: /* collate ::= */
113914 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
113915 break;
113916 case 251: /* cmd ::= DROP INDEX ifexists fullname */
113917 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
113918 break;
113919 case 252: /* cmd ::= VACUUM */
113920 case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
113921 {sqlite3Vacuum(pParse);}
113922 break;
113923 case 254: /* cmd ::= PRAGMA nm dbnm */
113924 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
113925 break;
113926 case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
113927 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
113928 break;
113929 case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
113930 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
113931 break;
113932 case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
113933 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
113934 break;
113935 case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
113936 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
113937 break;
113938 case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
113940 Token all;
113941 all.z = yymsp[-3].minor.yy0.z;
113942 all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
113943 sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
113945 break;
113946 case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
113948 sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
113949 yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
113951 break;
113952 case 270: /* trigger_time ::= BEFORE */
113953 case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
113954 { yygotominor.yy392 = TK_BEFORE; }
113955 break;
113956 case 271: /* trigger_time ::= AFTER */
113957 { yygotominor.yy392 = TK_AFTER; }
113958 break;
113959 case 272: /* trigger_time ::= INSTEAD OF */
113960 { yygotominor.yy392 = TK_INSTEAD;}
113961 break;
113962 case 274: /* trigger_event ::= DELETE|INSERT */
113963 case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
113964 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
113965 break;
113966 case 276: /* trigger_event ::= UPDATE OF inscollist */
113967 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
113968 break;
113969 case 279: /* when_clause ::= */
113970 case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
113971 { yygotominor.yy122 = 0; }
113972 break;
113973 case 280: /* when_clause ::= WHEN expr */
113974 case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
113975 { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
113976 break;
113977 case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
113979 assert( yymsp[-2].minor.yy327!=0 );
113980 yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
113981 yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
113982 yygotominor.yy327 = yymsp[-2].minor.yy327;
113984 break;
113985 case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
113987 assert( yymsp[-1].minor.yy327!=0 );
113988 yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
113989 yygotominor.yy327 = yymsp[-1].minor.yy327;
113991 break;
113992 case 284: /* trnm ::= nm DOT nm */
113994 yygotominor.yy0 = yymsp[0].minor.yy0;
113995 sqlite3ErrorMsg(pParse,
113996 "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
113997 "statements within triggers");
113999 break;
114000 case 286: /* tridxby ::= INDEXED BY nm */
114002 sqlite3ErrorMsg(pParse,
114003 "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
114004 "within triggers");
114006 break;
114007 case 287: /* tridxby ::= NOT INDEXED */
114009 sqlite3ErrorMsg(pParse,
114010 "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
114011 "within triggers");
114013 break;
114014 case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
114015 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
114016 break;
114017 case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
114018 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}
114019 break;
114020 case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
114021 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
114022 break;
114023 case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
114024 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
114025 break;
114026 case 292: /* trigger_cmd ::= select */
114027 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
114028 break;
114029 case 293: /* expr ::= RAISE LP IGNORE RP */
114031 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
114032 if( yygotominor.yy342.pExpr ){
114033 yygotominor.yy342.pExpr->affinity = OE_Ignore;
114035 yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
114036 yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
114038 break;
114039 case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
114041 yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
114042 if( yygotominor.yy342.pExpr ) {
114043 yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
114045 yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
114046 yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
114048 break;
114049 case 295: /* raisetype ::= ROLLBACK */
114050 {yygotominor.yy392 = OE_Rollback;}
114051 break;
114052 case 297: /* raisetype ::= FAIL */
114053 {yygotominor.yy392 = OE_Fail;}
114054 break;
114055 case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
114057 sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
114059 break;
114060 case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
114062 sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
114064 break;
114065 case 300: /* cmd ::= DETACH database_kw_opt expr */
114067 sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
114069 break;
114070 case 305: /* cmd ::= REINDEX */
114071 {sqlite3Reindex(pParse, 0, 0);}
114072 break;
114073 case 306: /* cmd ::= REINDEX nm dbnm */
114074 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
114075 break;
114076 case 307: /* cmd ::= ANALYZE */
114077 {sqlite3Analyze(pParse, 0, 0);}
114078 break;
114079 case 308: /* cmd ::= ANALYZE nm dbnm */
114080 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
114081 break;
114082 case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
114084 sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
114086 break;
114087 case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
114089 sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
114091 break;
114092 case 311: /* add_column_fullname ::= fullname */
114094 pParse->db->lookaside.bEnabled = 0;
114095 sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
114097 break;
114098 case 314: /* cmd ::= create_vtab */
114099 {sqlite3VtabFinishParse(pParse,0);}
114100 break;
114101 case 315: /* cmd ::= create_vtab LP vtabarglist RP */
114102 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
114103 break;
114104 case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
114106 sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
114108 break;
114109 case 319: /* vtabarg ::= */
114110 {sqlite3VtabArgInit(pParse);}
114111 break;
114112 case 321: /* vtabargtoken ::= ANY */
114113 case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
114114 case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
114115 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
114116 break;
114117 default:
114118 /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
114119 /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
114120 /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
114121 /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
114122 /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
114123 /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
114124 /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
114125 /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
114126 /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
114127 /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
114128 /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
114129 /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
114130 /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
114131 /* (44) type ::= */ yytestcase(yyruleno==44);
114132 /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
114133 /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
114134 /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
114135 /* (54) carglist ::= */ yytestcase(yyruleno==54);
114136 /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
114137 /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
114138 /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
114139 /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
114140 /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
114141 /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
114142 /* (285) tridxby ::= */ yytestcase(yyruleno==285);
114143 /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
114144 /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
114145 /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
114146 /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
114147 /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
114148 /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
114149 /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
114150 /* (324) anylist ::= */ yytestcase(yyruleno==324);
114151 /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
114152 /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
114153 break;
114155 assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
114156 yygoto = yyRuleInfo[yyruleno].lhs;
114157 yysize = yyRuleInfo[yyruleno].nrhs;
114158 yypParser->yyidx -= yysize;
114159 yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
114160 if( yyact < YYNSTATE ){
114161 #ifdef NDEBUG
114162 /* If we are not debugging and the reduce action popped at least
114163 ** one element off the stack, then we can push the new element back
114164 ** onto the stack here, and skip the stack overflow test in yy_shift().
114165 ** That gives a significant speed improvement. */
114166 if( yysize ){
114167 yypParser->yyidx++;
114168 yymsp -= yysize-1;
114169 yymsp->stateno = (YYACTIONTYPE)yyact;
114170 yymsp->major = (YYCODETYPE)yygoto;
114171 yymsp->minor = yygotominor;
114172 }else
114173 #endif
114175 yy_shift(yypParser,yyact,yygoto,&yygotominor);
114177 }else{
114178 assert( yyact == YYNSTATE + YYNRULE + 1 );
114179 yy_accept(yypParser);
114184 ** The following code executes when the parse fails
114186 #ifndef YYNOERRORRECOVERY
114187 static void yy_parse_failed(
114188 yyParser *yypParser /* The parser */
114190 sqlite3ParserARG_FETCH;
114191 #ifndef NDEBUG
114192 if( yyTraceFILE ){
114193 fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
114195 #endif
114196 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
114197 /* Here code is inserted which will be executed whenever the
114198 ** parser fails */
114199 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
114201 #endif /* YYNOERRORRECOVERY */
114204 ** The following code executes when a syntax error first occurs.
114206 static void yy_syntax_error(
114207 yyParser *yypParser, /* The parser */
114208 int yymajor, /* The major type of the error token */
114209 YYMINORTYPE yyminor /* The minor type of the error token */
114211 sqlite3ParserARG_FETCH;
114212 #define TOKEN (yyminor.yy0)
114214 UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
114215 assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
114216 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
114217 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
114221 ** The following is executed when the parser accepts
114223 static void yy_accept(
114224 yyParser *yypParser /* The parser */
114226 sqlite3ParserARG_FETCH;
114227 #ifndef NDEBUG
114228 if( yyTraceFILE ){
114229 fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
114231 #endif
114232 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
114233 /* Here code is inserted which will be executed whenever the
114234 ** parser accepts */
114235 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
114238 /* The main parser program.
114239 ** The first argument is a pointer to a structure obtained from
114240 ** "sqlite3ParserAlloc" which describes the current state of the parser.
114241 ** The second argument is the major token number. The third is
114242 ** the minor token. The fourth optional argument is whatever the
114243 ** user wants (and specified in the grammar) and is available for
114244 ** use by the action routines.
114246 ** Inputs:
114247 ** <ul>
114248 ** <li> A pointer to the parser (an opaque structure.)
114249 ** <li> The major token number.
114250 ** <li> The minor token number.
114251 ** <li> An option argument of a grammar-specified type.
114252 ** </ul>
114254 ** Outputs:
114255 ** None.
114257 SQLITE_PRIVATE void sqlite3Parser(
114258 void *yyp, /* The parser */
114259 int yymajor, /* The major token code number */
114260 sqlite3ParserTOKENTYPE yyminor /* The value for the token */
114261 sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
114263 YYMINORTYPE yyminorunion;
114264 int yyact; /* The parser action. */
114265 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
114266 int yyendofinput; /* True if we are at the end of input */
114267 #endif
114268 #ifdef YYERRORSYMBOL
114269 int yyerrorhit = 0; /* True if yymajor has invoked an error */
114270 #endif
114271 yyParser *yypParser; /* The parser */
114273 /* (re)initialize the parser, if necessary */
114274 yypParser = (yyParser*)yyp;
114275 if( yypParser->yyidx<0 ){
114276 #if YYSTACKDEPTH<=0
114277 if( yypParser->yystksz <=0 ){
114278 /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
114279 yyminorunion = yyzerominor;
114280 yyStackOverflow(yypParser, &yyminorunion);
114281 return;
114283 #endif
114284 yypParser->yyidx = 0;
114285 yypParser->yyerrcnt = -1;
114286 yypParser->yystack[0].stateno = 0;
114287 yypParser->yystack[0].major = 0;
114289 yyminorunion.yy0 = yyminor;
114290 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
114291 yyendofinput = (yymajor==0);
114292 #endif
114293 sqlite3ParserARG_STORE;
114295 #ifndef NDEBUG
114296 if( yyTraceFILE ){
114297 fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
114299 #endif
114302 yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
114303 if( yyact<YYNSTATE ){
114304 yy_shift(yypParser,yyact,yymajor,&yyminorunion);
114305 yypParser->yyerrcnt--;
114306 yymajor = YYNOCODE;
114307 }else if( yyact < YYNSTATE + YYNRULE ){
114308 yy_reduce(yypParser,yyact-YYNSTATE);
114309 }else{
114310 assert( yyact == YY_ERROR_ACTION );
114311 #ifdef YYERRORSYMBOL
114312 int yymx;
114313 #endif
114314 #ifndef NDEBUG
114315 if( yyTraceFILE ){
114316 fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
114318 #endif
114319 #ifdef YYERRORSYMBOL
114320 /* A syntax error has occurred.
114321 ** The response to an error depends upon whether or not the
114322 ** grammar defines an error token "ERROR".
114324 ** This is what we do if the grammar does define ERROR:
114326 ** * Call the %syntax_error function.
114328 ** * Begin popping the stack until we enter a state where
114329 ** it is legal to shift the error symbol, then shift
114330 ** the error symbol.
114332 ** * Set the error count to three.
114334 ** * Begin accepting and shifting new tokens. No new error
114335 ** processing will occur until three tokens have been
114336 ** shifted successfully.
114339 if( yypParser->yyerrcnt<0 ){
114340 yy_syntax_error(yypParser,yymajor,yyminorunion);
114342 yymx = yypParser->yystack[yypParser->yyidx].major;
114343 if( yymx==YYERRORSYMBOL || yyerrorhit ){
114344 #ifndef NDEBUG
114345 if( yyTraceFILE ){
114346 fprintf(yyTraceFILE,"%sDiscard input token %s\n",
114347 yyTracePrompt,yyTokenName[yymajor]);
114349 #endif
114350 yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
114351 yymajor = YYNOCODE;
114352 }else{
114353 while(
114354 yypParser->yyidx >= 0 &&
114355 yymx != YYERRORSYMBOL &&
114356 (yyact = yy_find_reduce_action(
114357 yypParser->yystack[yypParser->yyidx].stateno,
114358 YYERRORSYMBOL)) >= YYNSTATE
114360 yy_pop_parser_stack(yypParser);
114362 if( yypParser->yyidx < 0 || yymajor==0 ){
114363 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
114364 yy_parse_failed(yypParser);
114365 yymajor = YYNOCODE;
114366 }else if( yymx!=YYERRORSYMBOL ){
114367 YYMINORTYPE u2;
114368 u2.YYERRSYMDT = 0;
114369 yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
114372 yypParser->yyerrcnt = 3;
114373 yyerrorhit = 1;
114374 #elif defined(YYNOERRORRECOVERY)
114375 /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
114376 ** do any kind of error recovery. Instead, simply invoke the syntax
114377 ** error routine and continue going as if nothing had happened.
114379 ** Applications can set this macro (for example inside %include) if
114380 ** they intend to abandon the parse upon the first syntax error seen.
114382 yy_syntax_error(yypParser,yymajor,yyminorunion);
114383 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
114384 yymajor = YYNOCODE;
114386 #else /* YYERRORSYMBOL is not defined */
114387 /* This is what we do if the grammar does not define ERROR:
114389 ** * Report an error message, and throw away the input token.
114391 ** * If the input token is $, then fail the parse.
114393 ** As before, subsequent error messages are suppressed until
114394 ** three input tokens have been successfully shifted.
114396 if( yypParser->yyerrcnt<=0 ){
114397 yy_syntax_error(yypParser,yymajor,yyminorunion);
114399 yypParser->yyerrcnt = 3;
114400 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
114401 if( yyendofinput ){
114402 yy_parse_failed(yypParser);
114404 yymajor = YYNOCODE;
114405 #endif
114407 }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
114408 return;
114411 /************** End of parse.c ***********************************************/
114412 /************** Begin file tokenize.c ****************************************/
114414 ** 2001 September 15
114416 ** The author disclaims copyright to this source code. In place of
114417 ** a legal notice, here is a blessing:
114419 ** May you do good and not evil.
114420 ** May you find forgiveness for yourself and forgive others.
114421 ** May you share freely, never taking more than you give.
114423 *************************************************************************
114424 ** An tokenizer for SQL
114426 ** This file contains C code that splits an SQL input string up into
114427 ** individual tokens and sends those tokens one-by-one over to the
114428 ** parser for analysis.
114430 /* #include <stdlib.h> */
114433 ** The charMap() macro maps alphabetic characters into their
114434 ** lower-case ASCII equivalent. On ASCII machines, this is just
114435 ** an upper-to-lower case map. On EBCDIC machines we also need
114436 ** to adjust the encoding. Only alphabetic characters and underscores
114437 ** need to be translated.
114439 #ifdef SQLITE_ASCII
114440 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
114441 #endif
114442 #ifdef SQLITE_EBCDIC
114443 # define charMap(X) ebcdicToAscii[(unsigned char)X]
114444 const unsigned char ebcdicToAscii[] = {
114445 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
114446 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
114447 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
114448 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
114449 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
114450 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
114451 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
114452 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
114453 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
114454 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
114455 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
114456 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
114457 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
114458 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
114459 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
114460 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
114461 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
114463 #endif
114466 ** The sqlite3KeywordCode function looks up an identifier to determine if
114467 ** it is a keyword. If it is a keyword, the token code of that keyword is
114468 ** returned. If the input is not a keyword, TK_ID is returned.
114470 ** The implementation of this routine was generated by a program,
114471 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
114472 ** The output of the mkkeywordhash.c program is written into a file
114473 ** named keywordhash.h and then included into this source file by
114474 ** the #include below.
114476 /************** Include keywordhash.h in the middle of tokenize.c ************/
114477 /************** Begin file keywordhash.h *************************************/
114478 /***** This file contains automatically generated code ******
114480 ** The code in this file has been automatically generated by
114482 ** sqlite/tool/mkkeywordhash.c
114484 ** The code in this file implements a function that determines whether
114485 ** or not a given identifier is really an SQL keyword. The same thing
114486 ** might be implemented more directly using a hand-written hash table.
114487 ** But by using this automatically generated code, the size of the code
114488 ** is substantially reduced. This is important for embedded applications
114489 ** on platforms with limited memory.
114491 /* Hash score: 175 */
114492 static int keywordCode(const char *z, int n){
114493 /* zText[] encodes 811 bytes of keywords in 541 bytes */
114494 /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
114495 /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
114496 /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
114497 /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
114498 /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
114499 /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
114500 /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
114501 /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
114502 /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
114503 /* INITIALLY */
114504 static const char zText[540] = {
114505 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
114506 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
114507 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
114508 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
114509 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
114510 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
114511 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
114512 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
114513 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
114514 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
114515 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
114516 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
114517 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
114518 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
114519 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
114520 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
114521 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
114522 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
114523 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
114524 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
114525 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
114526 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
114527 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
114528 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
114529 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
114530 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
114531 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
114532 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
114533 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
114534 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
114536 static const unsigned char aHash[127] = {
114537 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
114538 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
114539 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
114540 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
114541 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
114542 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
114543 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
114544 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
114545 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
114546 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
114548 static const unsigned char aNext[121] = {
114549 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
114550 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
114551 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
114552 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
114553 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
114554 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
114555 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
114556 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
114557 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
114558 35, 64, 0, 0,
114560 static const unsigned char aLen[121] = {
114561 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
114562 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
114563 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
114564 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
114565 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
114566 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
114567 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
114568 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
114569 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
114570 6, 4, 9, 3,
114572 static const unsigned short int aOffset[121] = {
114573 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
114574 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
114575 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
114576 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
114577 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
114578 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
114579 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
114580 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
114581 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
114582 521, 527, 531, 536,
114584 static const unsigned char aCode[121] = {
114585 TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
114586 TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
114587 TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
114588 TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
114589 TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
114590 TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
114591 TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
114592 TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
114593 TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
114594 TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
114595 TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
114596 TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
114597 TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
114598 TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
114599 TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
114600 TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
114601 TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
114602 TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
114603 TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
114604 TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
114605 TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
114606 TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
114607 TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
114608 TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
114609 TK_ALL,
114611 int h, i;
114612 if( n<2 ) return TK_ID;
114613 h = ((charMap(z[0])*4) ^
114614 (charMap(z[n-1])*3) ^
114615 n) % 127;
114616 for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
114617 if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
114618 testcase( i==0 ); /* REINDEX */
114619 testcase( i==1 ); /* INDEXED */
114620 testcase( i==2 ); /* INDEX */
114621 testcase( i==3 ); /* DESC */
114622 testcase( i==4 ); /* ESCAPE */
114623 testcase( i==5 ); /* EACH */
114624 testcase( i==6 ); /* CHECK */
114625 testcase( i==7 ); /* KEY */
114626 testcase( i==8 ); /* BEFORE */
114627 testcase( i==9 ); /* FOREIGN */
114628 testcase( i==10 ); /* FOR */
114629 testcase( i==11 ); /* IGNORE */
114630 testcase( i==12 ); /* REGEXP */
114631 testcase( i==13 ); /* EXPLAIN */
114632 testcase( i==14 ); /* INSTEAD */
114633 testcase( i==15 ); /* ADD */
114634 testcase( i==16 ); /* DATABASE */
114635 testcase( i==17 ); /* AS */
114636 testcase( i==18 ); /* SELECT */
114637 testcase( i==19 ); /* TABLE */
114638 testcase( i==20 ); /* LEFT */
114639 testcase( i==21 ); /* THEN */
114640 testcase( i==22 ); /* END */
114641 testcase( i==23 ); /* DEFERRABLE */
114642 testcase( i==24 ); /* ELSE */
114643 testcase( i==25 ); /* EXCEPT */
114644 testcase( i==26 ); /* TRANSACTION */
114645 testcase( i==27 ); /* ACTION */
114646 testcase( i==28 ); /* ON */
114647 testcase( i==29 ); /* NATURAL */
114648 testcase( i==30 ); /* ALTER */
114649 testcase( i==31 ); /* RAISE */
114650 testcase( i==32 ); /* EXCLUSIVE */
114651 testcase( i==33 ); /* EXISTS */
114652 testcase( i==34 ); /* SAVEPOINT */
114653 testcase( i==35 ); /* INTERSECT */
114654 testcase( i==36 ); /* TRIGGER */
114655 testcase( i==37 ); /* REFERENCES */
114656 testcase( i==38 ); /* CONSTRAINT */
114657 testcase( i==39 ); /* INTO */
114658 testcase( i==40 ); /* OFFSET */
114659 testcase( i==41 ); /* OF */
114660 testcase( i==42 ); /* SET */
114661 testcase( i==43 ); /* TEMPORARY */
114662 testcase( i==44 ); /* TEMP */
114663 testcase( i==45 ); /* OR */
114664 testcase( i==46 ); /* UNIQUE */
114665 testcase( i==47 ); /* QUERY */
114666 testcase( i==48 ); /* ATTACH */
114667 testcase( i==49 ); /* HAVING */
114668 testcase( i==50 ); /* GROUP */
114669 testcase( i==51 ); /* UPDATE */
114670 testcase( i==52 ); /* BEGIN */
114671 testcase( i==53 ); /* INNER */
114672 testcase( i==54 ); /* RELEASE */
114673 testcase( i==55 ); /* BETWEEN */
114674 testcase( i==56 ); /* NOTNULL */
114675 testcase( i==57 ); /* NOT */
114676 testcase( i==58 ); /* NO */
114677 testcase( i==59 ); /* NULL */
114678 testcase( i==60 ); /* LIKE */
114679 testcase( i==61 ); /* CASCADE */
114680 testcase( i==62 ); /* ASC */
114681 testcase( i==63 ); /* DELETE */
114682 testcase( i==64 ); /* CASE */
114683 testcase( i==65 ); /* COLLATE */
114684 testcase( i==66 ); /* CREATE */
114685 testcase( i==67 ); /* CURRENT_DATE */
114686 testcase( i==68 ); /* DETACH */
114687 testcase( i==69 ); /* IMMEDIATE */
114688 testcase( i==70 ); /* JOIN */
114689 testcase( i==71 ); /* INSERT */
114690 testcase( i==72 ); /* MATCH */
114691 testcase( i==73 ); /* PLAN */
114692 testcase( i==74 ); /* ANALYZE */
114693 testcase( i==75 ); /* PRAGMA */
114694 testcase( i==76 ); /* ABORT */
114695 testcase( i==77 ); /* VALUES */
114696 testcase( i==78 ); /* VIRTUAL */
114697 testcase( i==79 ); /* LIMIT */
114698 testcase( i==80 ); /* WHEN */
114699 testcase( i==81 ); /* WHERE */
114700 testcase( i==82 ); /* RENAME */
114701 testcase( i==83 ); /* AFTER */
114702 testcase( i==84 ); /* REPLACE */
114703 testcase( i==85 ); /* AND */
114704 testcase( i==86 ); /* DEFAULT */
114705 testcase( i==87 ); /* AUTOINCREMENT */
114706 testcase( i==88 ); /* TO */
114707 testcase( i==89 ); /* IN */
114708 testcase( i==90 ); /* CAST */
114709 testcase( i==91 ); /* COLUMN */
114710 testcase( i==92 ); /* COMMIT */
114711 testcase( i==93 ); /* CONFLICT */
114712 testcase( i==94 ); /* CROSS */
114713 testcase( i==95 ); /* CURRENT_TIMESTAMP */
114714 testcase( i==96 ); /* CURRENT_TIME */
114715 testcase( i==97 ); /* PRIMARY */
114716 testcase( i==98 ); /* DEFERRED */
114717 testcase( i==99 ); /* DISTINCT */
114718 testcase( i==100 ); /* IS */
114719 testcase( i==101 ); /* DROP */
114720 testcase( i==102 ); /* FAIL */
114721 testcase( i==103 ); /* FROM */
114722 testcase( i==104 ); /* FULL */
114723 testcase( i==105 ); /* GLOB */
114724 testcase( i==106 ); /* BY */
114725 testcase( i==107 ); /* IF */
114726 testcase( i==108 ); /* ISNULL */
114727 testcase( i==109 ); /* ORDER */
114728 testcase( i==110 ); /* RESTRICT */
114729 testcase( i==111 ); /* OUTER */
114730 testcase( i==112 ); /* RIGHT */
114731 testcase( i==113 ); /* ROLLBACK */
114732 testcase( i==114 ); /* ROW */
114733 testcase( i==115 ); /* UNION */
114734 testcase( i==116 ); /* USING */
114735 testcase( i==117 ); /* VACUUM */
114736 testcase( i==118 ); /* VIEW */
114737 testcase( i==119 ); /* INITIALLY */
114738 testcase( i==120 ); /* ALL */
114739 return aCode[i];
114742 return TK_ID;
114744 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
114745 return keywordCode((char*)z, n);
114747 #define SQLITE_N_KEYWORD 121
114749 /************** End of keywordhash.h *****************************************/
114750 /************** Continuing where we left off in tokenize.c *******************/
114754 ** If X is a character that can be used in an identifier then
114755 ** IdChar(X) will be true. Otherwise it is false.
114757 ** For ASCII, any character with the high-order bit set is
114758 ** allowed in an identifier. For 7-bit characters,
114759 ** sqlite3IsIdChar[X] must be 1.
114761 ** For EBCDIC, the rules are more complex but have the same
114762 ** end result.
114764 ** Ticket #1066. the SQL standard does not allow '$' in the
114765 ** middle of identfiers. But many SQL implementations do.
114766 ** SQLite will allow '$' in identifiers for compatibility.
114767 ** But the feature is undocumented.
114769 #ifdef SQLITE_ASCII
114770 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
114771 #endif
114772 #ifdef SQLITE_EBCDIC
114773 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
114774 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
114775 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
114776 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
114777 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
114778 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
114779 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
114780 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
114781 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
114782 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
114783 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
114784 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
114785 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
114786 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
114788 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
114789 #endif
114793 ** Return the length of the token that begins at z[0].
114794 ** Store the token type in *tokenType before returning.
114796 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
114797 int i, c;
114798 switch( *z ){
114799 case ' ': case '\t': case '\n': case '\f': case '\r': {
114800 testcase( z[0]==' ' );
114801 testcase( z[0]=='\t' );
114802 testcase( z[0]=='\n' );
114803 testcase( z[0]=='\f' );
114804 testcase( z[0]=='\r' );
114805 for(i=1; sqlite3Isspace(z[i]); i++){}
114806 *tokenType = TK_SPACE;
114807 return i;
114809 case '-': {
114810 if( z[1]=='-' ){
114811 for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
114812 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
114813 return i;
114815 *tokenType = TK_MINUS;
114816 return 1;
114818 case '(': {
114819 *tokenType = TK_LP;
114820 return 1;
114822 case ')': {
114823 *tokenType = TK_RP;
114824 return 1;
114826 case ';': {
114827 *tokenType = TK_SEMI;
114828 return 1;
114830 case '+': {
114831 *tokenType = TK_PLUS;
114832 return 1;
114834 case '*': {
114835 *tokenType = TK_STAR;
114836 return 1;
114838 case '/': {
114839 if( z[1]!='*' || z[2]==0 ){
114840 *tokenType = TK_SLASH;
114841 return 1;
114843 for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
114844 if( c ) i++;
114845 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
114846 return i;
114848 case '%': {
114849 *tokenType = TK_REM;
114850 return 1;
114852 case '=': {
114853 *tokenType = TK_EQ;
114854 return 1 + (z[1]=='=');
114856 case '<': {
114857 if( (c=z[1])=='=' ){
114858 *tokenType = TK_LE;
114859 return 2;
114860 }else if( c=='>' ){
114861 *tokenType = TK_NE;
114862 return 2;
114863 }else if( c=='<' ){
114864 *tokenType = TK_LSHIFT;
114865 return 2;
114866 }else{
114867 *tokenType = TK_LT;
114868 return 1;
114871 case '>': {
114872 if( (c=z[1])=='=' ){
114873 *tokenType = TK_GE;
114874 return 2;
114875 }else if( c=='>' ){
114876 *tokenType = TK_RSHIFT;
114877 return 2;
114878 }else{
114879 *tokenType = TK_GT;
114880 return 1;
114883 case '!': {
114884 if( z[1]!='=' ){
114885 *tokenType = TK_ILLEGAL;
114886 return 2;
114887 }else{
114888 *tokenType = TK_NE;
114889 return 2;
114892 case '|': {
114893 if( z[1]!='|' ){
114894 *tokenType = TK_BITOR;
114895 return 1;
114896 }else{
114897 *tokenType = TK_CONCAT;
114898 return 2;
114901 case ',': {
114902 *tokenType = TK_COMMA;
114903 return 1;
114905 case '&': {
114906 *tokenType = TK_BITAND;
114907 return 1;
114909 case '~': {
114910 *tokenType = TK_BITNOT;
114911 return 1;
114913 case '`':
114914 case '\'':
114915 case '"': {
114916 int delim = z[0];
114917 testcase( delim=='`' );
114918 testcase( delim=='\'' );
114919 testcase( delim=='"' );
114920 for(i=1; (c=z[i])!=0; i++){
114921 if( c==delim ){
114922 if( z[i+1]==delim ){
114924 }else{
114925 break;
114929 if( c=='\'' ){
114930 *tokenType = TK_STRING;
114931 return i+1;
114932 }else if( c!=0 ){
114933 *tokenType = TK_ID;
114934 return i+1;
114935 }else{
114936 *tokenType = TK_ILLEGAL;
114937 return i;
114940 case '.': {
114941 #ifndef SQLITE_OMIT_FLOATING_POINT
114942 if( !sqlite3Isdigit(z[1]) )
114943 #endif
114945 *tokenType = TK_DOT;
114946 return 1;
114948 /* If the next character is a digit, this is a floating point
114949 ** number that begins with ".". Fall thru into the next case */
114951 case '0': case '1': case '2': case '3': case '4':
114952 case '5': case '6': case '7': case '8': case '9': {
114953 testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
114954 testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
114955 testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
114956 testcase( z[0]=='9' );
114957 *tokenType = TK_INTEGER;
114958 for(i=0; sqlite3Isdigit(z[i]); i++){}
114959 #ifndef SQLITE_OMIT_FLOATING_POINT
114960 if( z[i]=='.' ){
114962 while( sqlite3Isdigit(z[i]) ){ i++; }
114963 *tokenType = TK_FLOAT;
114965 if( (z[i]=='e' || z[i]=='E') &&
114966 ( sqlite3Isdigit(z[i+1])
114967 || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
114970 i += 2;
114971 while( sqlite3Isdigit(z[i]) ){ i++; }
114972 *tokenType = TK_FLOAT;
114974 #endif
114975 while( IdChar(z[i]) ){
114976 *tokenType = TK_ILLEGAL;
114979 return i;
114981 case '[': {
114982 for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
114983 *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
114984 return i;
114986 case '?': {
114987 *tokenType = TK_VARIABLE;
114988 for(i=1; sqlite3Isdigit(z[i]); i++){}
114989 return i;
114991 case '#': {
114992 for(i=1; sqlite3Isdigit(z[i]); i++){}
114993 if( i>1 ){
114994 /* Parameters of the form #NNN (where NNN is a number) are used
114995 ** internally by sqlite3NestedParse. */
114996 *tokenType = TK_REGISTER;
114997 return i;
114999 /* Fall through into the next case if the '#' is not followed by
115000 ** a digit. Try to match #AAAA where AAAA is a parameter name. */
115002 #ifndef SQLITE_OMIT_TCL_VARIABLE
115003 case '$':
115004 #endif
115005 case '@': /* For compatibility with MS SQL Server */
115006 case ':': {
115007 int n = 0;
115008 testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
115009 *tokenType = TK_VARIABLE;
115010 for(i=1; (c=z[i])!=0; i++){
115011 if( IdChar(c) ){
115013 #ifndef SQLITE_OMIT_TCL_VARIABLE
115014 }else if( c=='(' && n>0 ){
115017 }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
115018 if( c==')' ){
115020 }else{
115021 *tokenType = TK_ILLEGAL;
115023 break;
115024 }else if( c==':' && z[i+1]==':' ){
115026 #endif
115027 }else{
115028 break;
115031 if( n==0 ) *tokenType = TK_ILLEGAL;
115032 return i;
115034 #ifndef SQLITE_OMIT_BLOB_LITERAL
115035 case 'x': case 'X': {
115036 testcase( z[0]=='x' ); testcase( z[0]=='X' );
115037 if( z[1]=='\'' ){
115038 *tokenType = TK_BLOB;
115039 for(i=2; sqlite3Isxdigit(z[i]); i++){}
115040 if( z[i]!='\'' || i%2 ){
115041 *tokenType = TK_ILLEGAL;
115042 while( z[i] && z[i]!='\'' ){ i++; }
115044 if( z[i] ) i++;
115045 return i;
115047 /* Otherwise fall through to the next case */
115049 #endif
115050 default: {
115051 if( !IdChar(*z) ){
115052 break;
115054 for(i=1; IdChar(z[i]); i++){}
115055 *tokenType = keywordCode((char*)z, i);
115056 return i;
115059 *tokenType = TK_ILLEGAL;
115060 return 1;
115064 ** Run the parser on the given SQL string. The parser structure is
115065 ** passed in. An SQLITE_ status code is returned. If an error occurs
115066 ** then an and attempt is made to write an error message into
115067 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
115068 ** error message.
115070 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
115071 int nErr = 0; /* Number of errors encountered */
115072 int i; /* Loop counter */
115073 void *pEngine; /* The LEMON-generated LALR(1) parser */
115074 int tokenType; /* type of the next token */
115075 int lastTokenParsed = -1; /* type of the previous token */
115076 u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
115077 sqlite3 *db = pParse->db; /* The database connection */
115078 int mxSqlLen; /* Max length of an SQL string */
115081 mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
115082 if( db->nVdbeActive==0 ){
115083 db->u1.isInterrupted = 0;
115085 pParse->rc = SQLITE_OK;
115086 pParse->zTail = zSql;
115087 i = 0;
115088 assert( pzErrMsg!=0 );
115089 pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
115090 if( pEngine==0 ){
115091 db->mallocFailed = 1;
115092 return SQLITE_NOMEM;
115094 assert( pParse->pNewTable==0 );
115095 assert( pParse->pNewTrigger==0 );
115096 assert( pParse->nVar==0 );
115097 assert( pParse->nzVar==0 );
115098 assert( pParse->azVar==0 );
115099 enableLookaside = db->lookaside.bEnabled;
115100 if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
115101 while( !db->mallocFailed && zSql[i]!=0 ){
115102 assert( i>=0 );
115103 pParse->sLastToken.z = &zSql[i];
115104 pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
115105 i += pParse->sLastToken.n;
115106 if( i>mxSqlLen ){
115107 pParse->rc = SQLITE_TOOBIG;
115108 break;
115110 switch( tokenType ){
115111 case TK_SPACE: {
115112 if( db->u1.isInterrupted ){
115113 sqlite3ErrorMsg(pParse, "interrupt");
115114 pParse->rc = SQLITE_INTERRUPT;
115115 goto abort_parse;
115117 break;
115119 case TK_ILLEGAL: {
115120 sqlite3DbFree(db, *pzErrMsg);
115121 *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
115122 &pParse->sLastToken);
115123 nErr++;
115124 goto abort_parse;
115126 case TK_SEMI: {
115127 pParse->zTail = &zSql[i];
115128 /* Fall thru into the default case */
115130 default: {
115131 sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
115132 lastTokenParsed = tokenType;
115133 if( pParse->rc!=SQLITE_OK ){
115134 goto abort_parse;
115136 break;
115140 abort_parse:
115141 if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
115142 if( lastTokenParsed!=TK_SEMI ){
115143 sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
115144 pParse->zTail = &zSql[i];
115146 sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
115148 #ifdef YYTRACKMAXSTACKDEPTH
115149 sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
115150 sqlite3ParserStackPeak(pEngine)
115152 #endif /* YYDEBUG */
115153 sqlite3ParserFree(pEngine, sqlite3_free);
115154 db->lookaside.bEnabled = enableLookaside;
115155 if( db->mallocFailed ){
115156 pParse->rc = SQLITE_NOMEM;
115158 if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
115159 sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
115161 assert( pzErrMsg!=0 );
115162 if( pParse->zErrMsg ){
115163 *pzErrMsg = pParse->zErrMsg;
115164 sqlite3_log(pParse->rc, "%s", *pzErrMsg);
115165 pParse->zErrMsg = 0;
115166 nErr++;
115168 if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
115169 sqlite3VdbeDelete(pParse->pVdbe);
115170 pParse->pVdbe = 0;
115172 #ifndef SQLITE_OMIT_SHARED_CACHE
115173 if( pParse->nested==0 ){
115174 sqlite3DbFree(db, pParse->aTableLock);
115175 pParse->aTableLock = 0;
115176 pParse->nTableLock = 0;
115178 #endif
115179 #ifndef SQLITE_OMIT_VIRTUALTABLE
115180 sqlite3_free(pParse->apVtabLock);
115181 #endif
115183 if( !IN_DECLARE_VTAB ){
115184 /* If the pParse->declareVtab flag is set, do not delete any table
115185 ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
115186 ** will take responsibility for freeing the Table structure.
115188 sqlite3DeleteTable(db, pParse->pNewTable);
115191 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
115192 for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
115193 sqlite3DbFree(db, pParse->azVar);
115194 sqlite3DbFree(db, pParse->aAlias);
115195 while( pParse->pAinc ){
115196 AutoincInfo *p = pParse->pAinc;
115197 pParse->pAinc = p->pNext;
115198 sqlite3DbFree(db, p);
115200 while( pParse->pZombieTab ){
115201 Table *p = pParse->pZombieTab;
115202 pParse->pZombieTab = p->pNextZombie;
115203 sqlite3DeleteTable(db, p);
115205 if( nErr>0 && pParse->rc==SQLITE_OK ){
115206 pParse->rc = SQLITE_ERROR;
115208 return nErr;
115211 /************** End of tokenize.c ********************************************/
115212 /************** Begin file complete.c ****************************************/
115214 ** 2001 September 15
115216 ** The author disclaims copyright to this source code. In place of
115217 ** a legal notice, here is a blessing:
115219 ** May you do good and not evil.
115220 ** May you find forgiveness for yourself and forgive others.
115221 ** May you share freely, never taking more than you give.
115223 *************************************************************************
115224 ** An tokenizer for SQL
115226 ** This file contains C code that implements the sqlite3_complete() API.
115227 ** This code used to be part of the tokenizer.c source file. But by
115228 ** separating it out, the code will be automatically omitted from
115229 ** static links that do not use it.
115231 #ifndef SQLITE_OMIT_COMPLETE
115234 ** This is defined in tokenize.c. We just have to import the definition.
115236 #ifndef SQLITE_AMALGAMATION
115237 #ifdef SQLITE_ASCII
115238 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
115239 #endif
115240 #ifdef SQLITE_EBCDIC
115241 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
115242 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
115243 #endif
115244 #endif /* SQLITE_AMALGAMATION */
115248 ** Token types used by the sqlite3_complete() routine. See the header
115249 ** comments on that procedure for additional information.
115251 #define tkSEMI 0
115252 #define tkWS 1
115253 #define tkOTHER 2
115254 #ifndef SQLITE_OMIT_TRIGGER
115255 #define tkEXPLAIN 3
115256 #define tkCREATE 4
115257 #define tkTEMP 5
115258 #define tkTRIGGER 6
115259 #define tkEND 7
115260 #endif
115263 ** Return TRUE if the given SQL string ends in a semicolon.
115265 ** Special handling is require for CREATE TRIGGER statements.
115266 ** Whenever the CREATE TRIGGER keywords are seen, the statement
115267 ** must end with ";END;".
115269 ** This implementation uses a state machine with 8 states:
115271 ** (0) INVALID We have not yet seen a non-whitespace character.
115273 ** (1) START At the beginning or end of an SQL statement. This routine
115274 ** returns 1 if it ends in the START state and 0 if it ends
115275 ** in any other state.
115277 ** (2) NORMAL We are in the middle of statement which ends with a single
115278 ** semicolon.
115280 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
115281 ** a statement.
115283 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
115284 ** statement, possibly preceeded by EXPLAIN and/or followed by
115285 ** TEMP or TEMPORARY
115287 ** (5) TRIGGER We are in the middle of a trigger definition that must be
115288 ** ended by a semicolon, the keyword END, and another semicolon.
115290 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
115291 ** the end of a trigger definition.
115293 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
115294 ** of a trigger difinition.
115296 ** Transitions between states above are determined by tokens extracted
115297 ** from the input. The following tokens are significant:
115299 ** (0) tkSEMI A semicolon.
115300 ** (1) tkWS Whitespace.
115301 ** (2) tkOTHER Any other SQL token.
115302 ** (3) tkEXPLAIN The "explain" keyword.
115303 ** (4) tkCREATE The "create" keyword.
115304 ** (5) tkTEMP The "temp" or "temporary" keyword.
115305 ** (6) tkTRIGGER The "trigger" keyword.
115306 ** (7) tkEND The "end" keyword.
115308 ** Whitespace never causes a state transition and is always ignored.
115309 ** This means that a SQL string of all whitespace is invalid.
115311 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
115312 ** to recognize the end of a trigger can be omitted. All we have to do
115313 ** is look for a semicolon that is not part of an string or comment.
115315 SQLITE_API int sqlite3_complete(const char *zSql){
115316 u8 state = 0; /* Current state, using numbers defined in header comment */
115317 u8 token; /* Value of the next token */
115319 #ifndef SQLITE_OMIT_TRIGGER
115320 /* A complex statement machine used to detect the end of a CREATE TRIGGER
115321 ** statement. This is the normal case.
115323 static const u8 trans[8][8] = {
115324 /* Token: */
115325 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
115326 /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
115327 /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
115328 /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
115329 /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
115330 /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
115331 /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
115332 /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
115333 /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
115335 #else
115336 /* If triggers are not supported by this compile then the statement machine
115337 ** used to detect the end of a statement is much simplier
115339 static const u8 trans[3][3] = {
115340 /* Token: */
115341 /* State: ** SEMI WS OTHER */
115342 /* 0 INVALID: */ { 1, 0, 2, },
115343 /* 1 START: */ { 1, 1, 2, },
115344 /* 2 NORMAL: */ { 1, 2, 2, },
115346 #endif /* SQLITE_OMIT_TRIGGER */
115348 while( *zSql ){
115349 switch( *zSql ){
115350 case ';': { /* A semicolon */
115351 token = tkSEMI;
115352 break;
115354 case ' ':
115355 case '\r':
115356 case '\t':
115357 case '\n':
115358 case '\f': { /* White space is ignored */
115359 token = tkWS;
115360 break;
115362 case '/': { /* C-style comments */
115363 if( zSql[1]!='*' ){
115364 token = tkOTHER;
115365 break;
115367 zSql += 2;
115368 while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
115369 if( zSql[0]==0 ) return 0;
115370 zSql++;
115371 token = tkWS;
115372 break;
115374 case '-': { /* SQL-style comments from "--" to end of line */
115375 if( zSql[1]!='-' ){
115376 token = tkOTHER;
115377 break;
115379 while( *zSql && *zSql!='\n' ){ zSql++; }
115380 if( *zSql==0 ) return state==1;
115381 token = tkWS;
115382 break;
115384 case '[': { /* Microsoft-style identifiers in [...] */
115385 zSql++;
115386 while( *zSql && *zSql!=']' ){ zSql++; }
115387 if( *zSql==0 ) return 0;
115388 token = tkOTHER;
115389 break;
115391 case '`': /* Grave-accent quoted symbols used by MySQL */
115392 case '"': /* single- and double-quoted strings */
115393 case '\'': {
115394 int c = *zSql;
115395 zSql++;
115396 while( *zSql && *zSql!=c ){ zSql++; }
115397 if( *zSql==0 ) return 0;
115398 token = tkOTHER;
115399 break;
115401 default: {
115402 #ifdef SQLITE_EBCDIC
115403 unsigned char c;
115404 #endif
115405 if( IdChar((u8)*zSql) ){
115406 /* Keywords and unquoted identifiers */
115407 int nId;
115408 for(nId=1; IdChar(zSql[nId]); nId++){}
115409 #ifdef SQLITE_OMIT_TRIGGER
115410 token = tkOTHER;
115411 #else
115412 switch( *zSql ){
115413 case 'c': case 'C': {
115414 if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
115415 token = tkCREATE;
115416 }else{
115417 token = tkOTHER;
115419 break;
115421 case 't': case 'T': {
115422 if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
115423 token = tkTRIGGER;
115424 }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
115425 token = tkTEMP;
115426 }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
115427 token = tkTEMP;
115428 }else{
115429 token = tkOTHER;
115431 break;
115433 case 'e': case 'E': {
115434 if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
115435 token = tkEND;
115436 }else
115437 #ifndef SQLITE_OMIT_EXPLAIN
115438 if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
115439 token = tkEXPLAIN;
115440 }else
115441 #endif
115443 token = tkOTHER;
115445 break;
115447 default: {
115448 token = tkOTHER;
115449 break;
115452 #endif /* SQLITE_OMIT_TRIGGER */
115453 zSql += nId-1;
115454 }else{
115455 /* Operators and special symbols */
115456 token = tkOTHER;
115458 break;
115461 state = trans[state][token];
115462 zSql++;
115464 return state==1;
115467 #ifndef SQLITE_OMIT_UTF16
115469 ** This routine is the same as the sqlite3_complete() routine described
115470 ** above, except that the parameter is required to be UTF-16 encoded, not
115471 ** UTF-8.
115473 SQLITE_API int sqlite3_complete16(const void *zSql){
115474 sqlite3_value *pVal;
115475 char const *zSql8;
115476 int rc = SQLITE_NOMEM;
115478 #ifndef SQLITE_OMIT_AUTOINIT
115479 rc = sqlite3_initialize();
115480 if( rc ) return rc;
115481 #endif
115482 pVal = sqlite3ValueNew(0);
115483 sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
115484 zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
115485 if( zSql8 ){
115486 rc = sqlite3_complete(zSql8);
115487 }else{
115488 rc = SQLITE_NOMEM;
115490 sqlite3ValueFree(pVal);
115491 return sqlite3ApiExit(0, rc);
115493 #endif /* SQLITE_OMIT_UTF16 */
115494 #endif /* SQLITE_OMIT_COMPLETE */
115496 /************** End of complete.c ********************************************/
115497 /************** Begin file main.c ********************************************/
115499 ** 2001 September 15
115501 ** The author disclaims copyright to this source code. In place of
115502 ** a legal notice, here is a blessing:
115504 ** May you do good and not evil.
115505 ** May you find forgiveness for yourself and forgive others.
115506 ** May you share freely, never taking more than you give.
115508 *************************************************************************
115509 ** Main file for the SQLite library. The routines in this file
115510 ** implement the programmer interface to the library. Routines in
115511 ** other files are for internal use by SQLite and should not be
115512 ** accessed by users of the library.
115515 #ifdef SQLITE_ENABLE_FTS3
115516 /************** Include fts3.h in the middle of main.c ***********************/
115517 /************** Begin file fts3.h ********************************************/
115519 ** 2006 Oct 10
115521 ** The author disclaims copyright to this source code. In place of
115522 ** a legal notice, here is a blessing:
115524 ** May you do good and not evil.
115525 ** May you find forgiveness for yourself and forgive others.
115526 ** May you share freely, never taking more than you give.
115528 ******************************************************************************
115530 ** This header file is used by programs that want to link against the
115531 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
115534 #if 0
115535 extern "C" {
115536 #endif /* __cplusplus */
115538 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
115540 #if 0
115541 } /* extern "C" */
115542 #endif /* __cplusplus */
115544 /************** End of fts3.h ************************************************/
115545 /************** Continuing where we left off in main.c ***********************/
115546 #endif
115547 #ifdef SQLITE_ENABLE_RTREE
115548 /************** Include rtree.h in the middle of main.c **********************/
115549 /************** Begin file rtree.h *******************************************/
115551 ** 2008 May 26
115553 ** The author disclaims copyright to this source code. In place of
115554 ** a legal notice, here is a blessing:
115556 ** May you do good and not evil.
115557 ** May you find forgiveness for yourself and forgive others.
115558 ** May you share freely, never taking more than you give.
115560 ******************************************************************************
115562 ** This header file is used by programs that want to link against the
115563 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
115566 #if 0
115567 extern "C" {
115568 #endif /* __cplusplus */
115570 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
115572 #if 0
115573 } /* extern "C" */
115574 #endif /* __cplusplus */
115576 /************** End of rtree.h ***********************************************/
115577 /************** Continuing where we left off in main.c ***********************/
115578 #endif
115579 #ifdef SQLITE_ENABLE_ICU
115580 /************** Include sqliteicu.h in the middle of main.c ******************/
115581 /************** Begin file sqliteicu.h ***************************************/
115583 ** 2008 May 26
115585 ** The author disclaims copyright to this source code. In place of
115586 ** a legal notice, here is a blessing:
115588 ** May you do good and not evil.
115589 ** May you find forgiveness for yourself and forgive others.
115590 ** May you share freely, never taking more than you give.
115592 ******************************************************************************
115594 ** This header file is used by programs that want to link against the
115595 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
115598 #if 0
115599 extern "C" {
115600 #endif /* __cplusplus */
115602 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
115604 #if 0
115605 } /* extern "C" */
115606 #endif /* __cplusplus */
115609 /************** End of sqliteicu.h *******************************************/
115610 /************** Continuing where we left off in main.c ***********************/
115611 #endif
115613 #ifndef SQLITE_AMALGAMATION
115614 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
115615 ** contains the text of SQLITE_VERSION macro.
115617 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
115618 #endif
115620 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
115621 ** a pointer to the to the sqlite3_version[] string constant.
115623 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
115625 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
115626 ** pointer to a string constant whose value is the same as the
115627 ** SQLITE_SOURCE_ID C preprocessor macro.
115629 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
115631 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
115632 ** returns an integer equal to SQLITE_VERSION_NUMBER.
115634 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
115636 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
115637 ** zero if and only if SQLite was compiled with mutexing code omitted due to
115638 ** the SQLITE_THREADSAFE compile-time option being set to 0.
115640 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
115642 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
115644 ** If the following function pointer is not NULL and if
115645 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
115646 ** I/O active are written using this function. These messages
115647 ** are intended for debugging activity only.
115649 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
115650 #endif
115653 ** If the following global variable points to a string which is the
115654 ** name of a directory, then that directory will be used to store
115655 ** temporary files.
115657 ** See also the "PRAGMA temp_store_directory" SQL command.
115659 SQLITE_API char *sqlite3_temp_directory = 0;
115662 ** If the following global variable points to a string which is the
115663 ** name of a directory, then that directory will be used to store
115664 ** all database files specified with a relative pathname.
115666 ** See also the "PRAGMA data_store_directory" SQL command.
115668 SQLITE_API char *sqlite3_data_directory = 0;
115671 ** Initialize SQLite.
115673 ** This routine must be called to initialize the memory allocation,
115674 ** VFS, and mutex subsystems prior to doing any serious work with
115675 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
115676 ** this routine will be called automatically by key routines such as
115677 ** sqlite3_open().
115679 ** This routine is a no-op except on its very first call for the process,
115680 ** or for the first call after a call to sqlite3_shutdown.
115682 ** The first thread to call this routine runs the initialization to
115683 ** completion. If subsequent threads call this routine before the first
115684 ** thread has finished the initialization process, then the subsequent
115685 ** threads must block until the first thread finishes with the initialization.
115687 ** The first thread might call this routine recursively. Recursive
115688 ** calls to this routine should not block, of course. Otherwise the
115689 ** initialization process would never complete.
115691 ** Let X be the first thread to enter this routine. Let Y be some other
115692 ** thread. Then while the initial invocation of this routine by X is
115693 ** incomplete, it is required that:
115695 ** * Calls to this routine from Y must block until the outer-most
115696 ** call by X completes.
115698 ** * Recursive calls to this routine from thread X return immediately
115699 ** without blocking.
115701 SQLITE_API int sqlite3_initialize(void){
115702 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
115703 int rc; /* Result code */
115704 #ifdef SQLITE_EXTRA_INIT
115705 int bRunExtraInit = 0; /* Extra initialization needed */
115706 #endif
115708 #ifdef SQLITE_OMIT_WSD
115709 rc = sqlite3_wsd_init(4096, 24);
115710 if( rc!=SQLITE_OK ){
115711 return rc;
115713 #endif
115715 /* If SQLite is already completely initialized, then this call
115716 ** to sqlite3_initialize() should be a no-op. But the initialization
115717 ** must be complete. So isInit must not be set until the very end
115718 ** of this routine.
115720 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
115722 #ifdef SQLITE_ENABLE_SQLLOG
115724 extern void sqlite3_init_sqllog(void);
115725 sqlite3_init_sqllog();
115727 #endif
115729 /* Make sure the mutex subsystem is initialized. If unable to
115730 ** initialize the mutex subsystem, return early with the error.
115731 ** If the system is so sick that we are unable to allocate a mutex,
115732 ** there is not much SQLite is going to be able to do.
115734 ** The mutex subsystem must take care of serializing its own
115735 ** initialization.
115737 rc = sqlite3MutexInit();
115738 if( rc ) return rc;
115740 /* Initialize the malloc() system and the recursive pInitMutex mutex.
115741 ** This operation is protected by the STATIC_MASTER mutex. Note that
115742 ** MutexAlloc() is called for a static mutex prior to initializing the
115743 ** malloc subsystem - this implies that the allocation of a static
115744 ** mutex must not require support from the malloc subsystem.
115746 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
115747 sqlite3_mutex_enter(pMaster);
115748 sqlite3GlobalConfig.isMutexInit = 1;
115749 if( !sqlite3GlobalConfig.isMallocInit ){
115750 rc = sqlite3MallocInit();
115752 if( rc==SQLITE_OK ){
115753 sqlite3GlobalConfig.isMallocInit = 1;
115754 if( !sqlite3GlobalConfig.pInitMutex ){
115755 sqlite3GlobalConfig.pInitMutex =
115756 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
115757 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
115758 rc = SQLITE_NOMEM;
115762 if( rc==SQLITE_OK ){
115763 sqlite3GlobalConfig.nRefInitMutex++;
115765 sqlite3_mutex_leave(pMaster);
115767 /* If rc is not SQLITE_OK at this point, then either the malloc
115768 ** subsystem could not be initialized or the system failed to allocate
115769 ** the pInitMutex mutex. Return an error in either case. */
115770 if( rc!=SQLITE_OK ){
115771 return rc;
115774 /* Do the rest of the initialization under the recursive mutex so
115775 ** that we will be able to handle recursive calls into
115776 ** sqlite3_initialize(). The recursive calls normally come through
115777 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
115778 ** recursive calls might also be possible.
115780 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
115781 ** to the xInit method, so the xInit method need not be threadsafe.
115783 ** The following mutex is what serializes access to the appdef pcache xInit
115784 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
115785 ** call to sqlite3PcacheInitialize().
115787 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
115788 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
115789 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
115790 sqlite3GlobalConfig.inProgress = 1;
115791 memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
115792 sqlite3RegisterGlobalFunctions();
115793 if( sqlite3GlobalConfig.isPCacheInit==0 ){
115794 rc = sqlite3PcacheInitialize();
115796 if( rc==SQLITE_OK ){
115797 sqlite3GlobalConfig.isPCacheInit = 1;
115798 rc = sqlite3OsInit();
115800 if( rc==SQLITE_OK ){
115801 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
115802 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
115803 sqlite3GlobalConfig.isInit = 1;
115804 #ifdef SQLITE_EXTRA_INIT
115805 bRunExtraInit = 1;
115806 #endif
115808 sqlite3GlobalConfig.inProgress = 0;
115810 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
115812 /* Go back under the static mutex and clean up the recursive
115813 ** mutex to prevent a resource leak.
115815 sqlite3_mutex_enter(pMaster);
115816 sqlite3GlobalConfig.nRefInitMutex--;
115817 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
115818 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
115819 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
115820 sqlite3GlobalConfig.pInitMutex = 0;
115822 sqlite3_mutex_leave(pMaster);
115824 /* The following is just a sanity check to make sure SQLite has
115825 ** been compiled correctly. It is important to run this code, but
115826 ** we don't want to run it too often and soak up CPU cycles for no
115827 ** reason. So we run it once during initialization.
115829 #ifndef NDEBUG
115830 #ifndef SQLITE_OMIT_FLOATING_POINT
115831 /* This section of code's only "output" is via assert() statements. */
115832 if ( rc==SQLITE_OK ){
115833 u64 x = (((u64)1)<<63)-1;
115834 double y;
115835 assert(sizeof(x)==8);
115836 assert(sizeof(x)==sizeof(y));
115837 memcpy(&y, &x, 8);
115838 assert( sqlite3IsNaN(y) );
115840 #endif
115841 #endif
115843 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
115844 ** compile-time option.
115846 #ifdef SQLITE_EXTRA_INIT
115847 if( bRunExtraInit ){
115848 int SQLITE_EXTRA_INIT(const char*);
115849 rc = SQLITE_EXTRA_INIT(0);
115851 #endif
115853 return rc;
115857 ** Undo the effects of sqlite3_initialize(). Must not be called while
115858 ** there are outstanding database connections or memory allocations or
115859 ** while any part of SQLite is otherwise in use in any thread. This
115860 ** routine is not threadsafe. But it is safe to invoke this routine
115861 ** on when SQLite is already shut down. If SQLite is already shut down
115862 ** when this routine is invoked, then this routine is a harmless no-op.
115864 SQLITE_API int sqlite3_shutdown(void){
115865 if( sqlite3GlobalConfig.isInit ){
115866 #ifdef SQLITE_EXTRA_SHUTDOWN
115867 void SQLITE_EXTRA_SHUTDOWN(void);
115868 SQLITE_EXTRA_SHUTDOWN();
115869 #endif
115870 sqlite3_os_end();
115871 sqlite3_reset_auto_extension();
115872 sqlite3GlobalConfig.isInit = 0;
115874 if( sqlite3GlobalConfig.isPCacheInit ){
115875 sqlite3PcacheShutdown();
115876 sqlite3GlobalConfig.isPCacheInit = 0;
115878 if( sqlite3GlobalConfig.isMallocInit ){
115879 sqlite3MallocEnd();
115880 sqlite3GlobalConfig.isMallocInit = 0;
115882 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
115883 /* The heap subsystem has now been shutdown and these values are supposed
115884 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
115885 ** which would rely on that heap subsystem; therefore, make sure these
115886 ** values cannot refer to heap memory that was just invalidated when the
115887 ** heap subsystem was shutdown. This is only done if the current call to
115888 ** this function resulted in the heap subsystem actually being shutdown.
115890 sqlite3_data_directory = 0;
115891 sqlite3_temp_directory = 0;
115892 #endif
115894 if( sqlite3GlobalConfig.isMutexInit ){
115895 sqlite3MutexEnd();
115896 sqlite3GlobalConfig.isMutexInit = 0;
115899 return SQLITE_OK;
115903 ** This API allows applications to modify the global configuration of
115904 ** the SQLite library at run-time.
115906 ** This routine should only be called when there are no outstanding
115907 ** database connections or memory allocations. This routine is not
115908 ** threadsafe. Failure to heed these warnings can lead to unpredictable
115909 ** behavior.
115911 SQLITE_API int sqlite3_config(int op, ...){
115912 va_list ap;
115913 int rc = SQLITE_OK;
115915 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
115916 ** the SQLite library is in use. */
115917 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
115919 va_start(ap, op);
115920 switch( op ){
115922 /* Mutex configuration options are only available in a threadsafe
115923 ** compile.
115925 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
115926 case SQLITE_CONFIG_SINGLETHREAD: {
115927 /* Disable all mutexing */
115928 sqlite3GlobalConfig.bCoreMutex = 0;
115929 sqlite3GlobalConfig.bFullMutex = 0;
115930 break;
115932 case SQLITE_CONFIG_MULTITHREAD: {
115933 /* Disable mutexing of database connections */
115934 /* Enable mutexing of core data structures */
115935 sqlite3GlobalConfig.bCoreMutex = 1;
115936 sqlite3GlobalConfig.bFullMutex = 0;
115937 break;
115939 case SQLITE_CONFIG_SERIALIZED: {
115940 /* Enable all mutexing */
115941 sqlite3GlobalConfig.bCoreMutex = 1;
115942 sqlite3GlobalConfig.bFullMutex = 1;
115943 break;
115945 case SQLITE_CONFIG_MUTEX: {
115946 /* Specify an alternative mutex implementation */
115947 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
115948 break;
115950 case SQLITE_CONFIG_GETMUTEX: {
115951 /* Retrieve the current mutex implementation */
115952 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
115953 break;
115955 #endif
115958 case SQLITE_CONFIG_MALLOC: {
115959 /* Specify an alternative malloc implementation */
115960 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
115961 break;
115963 case SQLITE_CONFIG_GETMALLOC: {
115964 /* Retrieve the current malloc() implementation */
115965 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
115966 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
115967 break;
115969 case SQLITE_CONFIG_MEMSTATUS: {
115970 /* Enable or disable the malloc status collection */
115971 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
115972 break;
115974 case SQLITE_CONFIG_SCRATCH: {
115975 /* Designate a buffer for scratch memory space */
115976 sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
115977 sqlite3GlobalConfig.szScratch = va_arg(ap, int);
115978 sqlite3GlobalConfig.nScratch = va_arg(ap, int);
115979 break;
115981 case SQLITE_CONFIG_PAGECACHE: {
115982 /* Designate a buffer for page cache memory space */
115983 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
115984 sqlite3GlobalConfig.szPage = va_arg(ap, int);
115985 sqlite3GlobalConfig.nPage = va_arg(ap, int);
115986 break;
115989 case SQLITE_CONFIG_PCACHE: {
115990 /* no-op */
115991 break;
115993 case SQLITE_CONFIG_GETPCACHE: {
115994 /* now an error */
115995 rc = SQLITE_ERROR;
115996 break;
115999 case SQLITE_CONFIG_PCACHE2: {
116000 /* Specify an alternative page cache implementation */
116001 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
116002 break;
116004 case SQLITE_CONFIG_GETPCACHE2: {
116005 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
116006 sqlite3PCacheSetDefault();
116008 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
116009 break;
116012 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
116013 case SQLITE_CONFIG_HEAP: {
116014 /* Designate a buffer for heap memory space */
116015 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
116016 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
116017 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
116019 if( sqlite3GlobalConfig.mnReq<1 ){
116020 sqlite3GlobalConfig.mnReq = 1;
116021 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
116022 /* cap min request size at 2^12 */
116023 sqlite3GlobalConfig.mnReq = (1<<12);
116026 if( sqlite3GlobalConfig.pHeap==0 ){
116027 /* If the heap pointer is NULL, then restore the malloc implementation
116028 ** back to NULL pointers too. This will cause the malloc to go
116029 ** back to its default implementation when sqlite3_initialize() is
116030 ** run.
116032 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
116033 }else{
116034 /* The heap pointer is not NULL, then install one of the
116035 ** mem5.c/mem3.c methods. The enclosing #if guarantees at
116036 ** least one of these methods is currently enabled.
116038 #ifdef SQLITE_ENABLE_MEMSYS3
116039 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
116040 #endif
116041 #ifdef SQLITE_ENABLE_MEMSYS5
116042 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
116043 #endif
116045 break;
116047 #endif
116049 case SQLITE_CONFIG_LOOKASIDE: {
116050 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
116051 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
116052 break;
116055 /* Record a pointer to the logger function and its first argument.
116056 ** The default is NULL. Logging is disabled if the function pointer is
116057 ** NULL.
116059 case SQLITE_CONFIG_LOG: {
116060 /* MSVC is picky about pulling func ptrs from va lists.
116061 ** http://support.microsoft.com/kb/47961
116062 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
116064 typedef void(*LOGFUNC_t)(void*,int,const char*);
116065 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
116066 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
116067 break;
116070 case SQLITE_CONFIG_URI: {
116071 sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
116072 break;
116075 case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
116076 sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
116077 break;
116080 #ifdef SQLITE_ENABLE_SQLLOG
116081 case SQLITE_CONFIG_SQLLOG: {
116082 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
116083 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
116084 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
116085 break;
116087 #endif
116089 case SQLITE_CONFIG_MMAP_SIZE: {
116090 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
116091 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
116092 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
116093 mxMmap = SQLITE_MAX_MMAP_SIZE;
116095 sqlite3GlobalConfig.mxMmap = mxMmap;
116096 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
116097 if( szMmap>mxMmap) szMmap = mxMmap;
116098 sqlite3GlobalConfig.szMmap = szMmap;
116099 break;
116102 default: {
116103 rc = SQLITE_ERROR;
116104 break;
116107 va_end(ap);
116108 return rc;
116112 ** Set up the lookaside buffers for a database connection.
116113 ** Return SQLITE_OK on success.
116114 ** If lookaside is already active, return SQLITE_BUSY.
116116 ** The sz parameter is the number of bytes in each lookaside slot.
116117 ** The cnt parameter is the number of slots. If pStart is NULL the
116118 ** space for the lookaside memory is obtained from sqlite3_malloc().
116119 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
116120 ** the lookaside memory.
116122 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
116123 void *pStart;
116124 if( db->lookaside.nOut ){
116125 return SQLITE_BUSY;
116127 /* Free any existing lookaside buffer for this handle before
116128 ** allocating a new one so we don't have to have space for
116129 ** both at the same time.
116131 if( db->lookaside.bMalloced ){
116132 sqlite3_free(db->lookaside.pStart);
116134 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
116135 ** than a pointer to be useful.
116137 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
116138 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
116139 if( cnt<0 ) cnt = 0;
116140 if( sz==0 || cnt==0 ){
116141 sz = 0;
116142 pStart = 0;
116143 }else if( pBuf==0 ){
116144 sqlite3BeginBenignMalloc();
116145 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
116146 sqlite3EndBenignMalloc();
116147 if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
116148 }else{
116149 pStart = pBuf;
116151 db->lookaside.pStart = pStart;
116152 db->lookaside.pFree = 0;
116153 db->lookaside.sz = (u16)sz;
116154 if( pStart ){
116155 int i;
116156 LookasideSlot *p;
116157 assert( sz > (int)sizeof(LookasideSlot*) );
116158 p = (LookasideSlot*)pStart;
116159 for(i=cnt-1; i>=0; i--){
116160 p->pNext = db->lookaside.pFree;
116161 db->lookaside.pFree = p;
116162 p = (LookasideSlot*)&((u8*)p)[sz];
116164 db->lookaside.pEnd = p;
116165 db->lookaside.bEnabled = 1;
116166 db->lookaside.bMalloced = pBuf==0 ?1:0;
116167 }else{
116168 db->lookaside.pEnd = 0;
116169 db->lookaside.bEnabled = 0;
116170 db->lookaside.bMalloced = 0;
116172 return SQLITE_OK;
116176 ** Return the mutex associated with a database connection.
116178 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
116179 return db->mutex;
116183 ** Free up as much memory as we can from the given database
116184 ** connection.
116186 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
116187 int i;
116188 sqlite3_mutex_enter(db->mutex);
116189 sqlite3BtreeEnterAll(db);
116190 for(i=0; i<db->nDb; i++){
116191 Btree *pBt = db->aDb[i].pBt;
116192 if( pBt ){
116193 Pager *pPager = sqlite3BtreePager(pBt);
116194 sqlite3PagerShrink(pPager);
116197 sqlite3BtreeLeaveAll(db);
116198 sqlite3_mutex_leave(db->mutex);
116199 return SQLITE_OK;
116203 ** Configuration settings for an individual database connection
116205 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
116206 va_list ap;
116207 int rc;
116208 va_start(ap, op);
116209 switch( op ){
116210 case SQLITE_DBCONFIG_LOOKASIDE: {
116211 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
116212 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
116213 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
116214 rc = setupLookaside(db, pBuf, sz, cnt);
116215 break;
116217 default: {
116218 static const struct {
116219 int op; /* The opcode */
116220 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
116221 } aFlagOp[] = {
116222 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
116223 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
116225 unsigned int i;
116226 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
116227 for(i=0; i<ArraySize(aFlagOp); i++){
116228 if( aFlagOp[i].op==op ){
116229 int onoff = va_arg(ap, int);
116230 int *pRes = va_arg(ap, int*);
116231 int oldFlags = db->flags;
116232 if( onoff>0 ){
116233 db->flags |= aFlagOp[i].mask;
116234 }else if( onoff==0 ){
116235 db->flags &= ~aFlagOp[i].mask;
116237 if( oldFlags!=db->flags ){
116238 sqlite3ExpirePreparedStatements(db);
116240 if( pRes ){
116241 *pRes = (db->flags & aFlagOp[i].mask)!=0;
116243 rc = SQLITE_OK;
116244 break;
116247 break;
116250 va_end(ap);
116251 return rc;
116256 ** Return true if the buffer z[0..n-1] contains all spaces.
116258 static int allSpaces(const char *z, int n){
116259 while( n>0 && z[n-1]==' ' ){ n--; }
116260 return n==0;
116264 ** This is the default collating function named "BINARY" which is always
116265 ** available.
116267 ** If the padFlag argument is not NULL then space padding at the end
116268 ** of strings is ignored. This implements the RTRIM collation.
116270 static int binCollFunc(
116271 void *padFlag,
116272 int nKey1, const void *pKey1,
116273 int nKey2, const void *pKey2
116275 int rc, n;
116276 n = nKey1<nKey2 ? nKey1 : nKey2;
116277 rc = memcmp(pKey1, pKey2, n);
116278 if( rc==0 ){
116279 if( padFlag
116280 && allSpaces(((char*)pKey1)+n, nKey1-n)
116281 && allSpaces(((char*)pKey2)+n, nKey2-n)
116283 /* Leave rc unchanged at 0 */
116284 }else{
116285 rc = nKey1 - nKey2;
116288 return rc;
116292 ** Another built-in collating sequence: NOCASE.
116294 ** This collating sequence is intended to be used for "case independent
116295 ** comparison". SQLite's knowledge of upper and lower case equivalents
116296 ** extends only to the 26 characters used in the English language.
116298 ** At the moment there is only a UTF-8 implementation.
116300 static int nocaseCollatingFunc(
116301 void *NotUsed,
116302 int nKey1, const void *pKey1,
116303 int nKey2, const void *pKey2
116305 int r = sqlite3StrNICmp(
116306 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
116307 UNUSED_PARAMETER(NotUsed);
116308 if( 0==r ){
116309 r = nKey1-nKey2;
116311 return r;
116315 ** Return the ROWID of the most recent insert
116317 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
116318 return db->lastRowid;
116322 ** Return the number of changes in the most recent call to sqlite3_exec().
116324 SQLITE_API int sqlite3_changes(sqlite3 *db){
116325 return db->nChange;
116329 ** Return the number of changes since the database handle was opened.
116331 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
116332 return db->nTotalChange;
116336 ** Close all open savepoints. This function only manipulates fields of the
116337 ** database handle object, it does not close any savepoints that may be open
116338 ** at the b-tree/pager level.
116340 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
116341 while( db->pSavepoint ){
116342 Savepoint *pTmp = db->pSavepoint;
116343 db->pSavepoint = pTmp->pNext;
116344 sqlite3DbFree(db, pTmp);
116346 db->nSavepoint = 0;
116347 db->nStatement = 0;
116348 db->isTransactionSavepoint = 0;
116352 ** Invoke the destructor function associated with FuncDef p, if any. Except,
116353 ** if this is not the last copy of the function, do not invoke it. Multiple
116354 ** copies of a single function are created when create_function() is called
116355 ** with SQLITE_ANY as the encoding.
116357 static void functionDestroy(sqlite3 *db, FuncDef *p){
116358 FuncDestructor *pDestructor = p->pDestructor;
116359 if( pDestructor ){
116360 pDestructor->nRef--;
116361 if( pDestructor->nRef==0 ){
116362 pDestructor->xDestroy(pDestructor->pUserData);
116363 sqlite3DbFree(db, pDestructor);
116369 ** Disconnect all sqlite3_vtab objects that belong to database connection
116370 ** db. This is called when db is being closed.
116372 static void disconnectAllVtab(sqlite3 *db){
116373 #ifndef SQLITE_OMIT_VIRTUALTABLE
116374 int i;
116375 sqlite3BtreeEnterAll(db);
116376 for(i=0; i<db->nDb; i++){
116377 Schema *pSchema = db->aDb[i].pSchema;
116378 if( db->aDb[i].pSchema ){
116379 HashElem *p;
116380 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
116381 Table *pTab = (Table *)sqliteHashData(p);
116382 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
116386 sqlite3BtreeLeaveAll(db);
116387 #else
116388 UNUSED_PARAMETER(db);
116389 #endif
116393 ** Return TRUE if database connection db has unfinalized prepared
116394 ** statements or unfinished sqlite3_backup objects.
116396 static int connectionIsBusy(sqlite3 *db){
116397 int j;
116398 assert( sqlite3_mutex_held(db->mutex) );
116399 if( db->pVdbe ) return 1;
116400 for(j=0; j<db->nDb; j++){
116401 Btree *pBt = db->aDb[j].pBt;
116402 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
116404 return 0;
116408 ** Close an existing SQLite database
116410 static int sqlite3Close(sqlite3 *db, int forceZombie){
116411 if( !db ){
116412 return SQLITE_OK;
116414 if( !sqlite3SafetyCheckSickOrOk(db) ){
116415 return SQLITE_MISUSE_BKPT;
116417 sqlite3_mutex_enter(db->mutex);
116419 /* Force xDisconnect calls on all virtual tables */
116420 disconnectAllVtab(db);
116422 /* If a transaction is open, the disconnectAllVtab() call above
116423 ** will not have called the xDisconnect() method on any virtual
116424 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
116425 ** call will do so. We need to do this before the check for active
116426 ** SQL statements below, as the v-table implementation may be storing
116427 ** some prepared statements internally.
116429 sqlite3VtabRollback(db);
116431 /* Legacy behavior (sqlite3_close() behavior) is to return
116432 ** SQLITE_BUSY if the connection can not be closed immediately.
116434 if( !forceZombie && connectionIsBusy(db) ){
116435 sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
116436 "statements or unfinished backups");
116437 sqlite3_mutex_leave(db->mutex);
116438 return SQLITE_BUSY;
116441 #ifdef SQLITE_ENABLE_SQLLOG
116442 if( sqlite3GlobalConfig.xSqllog ){
116443 /* Closing the handle. Fourth parameter is passed the value 2. */
116444 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
116446 #endif
116448 /* Convert the connection into a zombie and then close it.
116450 db->magic = SQLITE_MAGIC_ZOMBIE;
116451 sqlite3LeaveMutexAndCloseZombie(db);
116452 return SQLITE_OK;
116456 ** Two variations on the public interface for closing a database
116457 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
116458 ** leaves the connection option if there are unfinalized prepared
116459 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
116460 ** version forces the connection to become a zombie if there are
116461 ** unclosed resources, and arranges for deallocation when the last
116462 ** prepare statement or sqlite3_backup closes.
116464 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
116465 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
116469 ** Close the mutex on database connection db.
116471 ** Furthermore, if database connection db is a zombie (meaning that there
116472 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
116473 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
116474 ** finished, then free all resources.
116476 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
116477 HashElem *i; /* Hash table iterator */
116478 int j;
116480 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
116481 ** or if the connection has not yet been closed by sqlite3_close_v2(),
116482 ** then just leave the mutex and return.
116484 if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
116485 sqlite3_mutex_leave(db->mutex);
116486 return;
116489 /* If we reach this point, it means that the database connection has
116490 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
116491 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
116492 ** go ahead and free all resources.
116495 /* If a transaction is open, roll it back. This also ensures that if
116496 ** any database schemas have been modified by an uncommitted transaction
116497 ** they are reset. And that the required b-tree mutex is held to make
116498 ** the pager rollback and schema reset an atomic operation. */
116499 sqlite3RollbackAll(db, SQLITE_OK);
116501 /* Free any outstanding Savepoint structures. */
116502 sqlite3CloseSavepoints(db);
116504 /* Close all database connections */
116505 for(j=0; j<db->nDb; j++){
116506 struct Db *pDb = &db->aDb[j];
116507 if( pDb->pBt ){
116508 sqlite3BtreeClose(pDb->pBt);
116509 pDb->pBt = 0;
116510 if( j!=1 ){
116511 pDb->pSchema = 0;
116515 /* Clear the TEMP schema separately and last */
116516 if( db->aDb[1].pSchema ){
116517 sqlite3SchemaClear(db->aDb[1].pSchema);
116519 sqlite3VtabUnlockList(db);
116521 /* Free up the array of auxiliary databases */
116522 sqlite3CollapseDatabaseArray(db);
116523 assert( db->nDb<=2 );
116524 assert( db->aDb==db->aDbStatic );
116526 /* Tell the code in notify.c that the connection no longer holds any
116527 ** locks and does not require any further unlock-notify callbacks.
116529 sqlite3ConnectionClosed(db);
116531 for(j=0; j<ArraySize(db->aFunc.a); j++){
116532 FuncDef *pNext, *pHash, *p;
116533 for(p=db->aFunc.a[j]; p; p=pHash){
116534 pHash = p->pHash;
116535 while( p ){
116536 functionDestroy(db, p);
116537 pNext = p->pNext;
116538 sqlite3DbFree(db, p);
116539 p = pNext;
116543 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
116544 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
116545 /* Invoke any destructors registered for collation sequence user data. */
116546 for(j=0; j<3; j++){
116547 if( pColl[j].xDel ){
116548 pColl[j].xDel(pColl[j].pUser);
116551 sqlite3DbFree(db, pColl);
116553 sqlite3HashClear(&db->aCollSeq);
116554 #ifndef SQLITE_OMIT_VIRTUALTABLE
116555 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
116556 Module *pMod = (Module *)sqliteHashData(i);
116557 if( pMod->xDestroy ){
116558 pMod->xDestroy(pMod->pAux);
116560 sqlite3DbFree(db, pMod);
116562 sqlite3HashClear(&db->aModule);
116563 #endif
116565 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
116566 if( db->pErr ){
116567 sqlite3ValueFree(db->pErr);
116569 sqlite3CloseExtensions(db);
116571 db->magic = SQLITE_MAGIC_ERROR;
116573 /* The temp-database schema is allocated differently from the other schema
116574 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
116575 ** So it needs to be freed here. Todo: Why not roll the temp schema into
116576 ** the same sqliteMalloc() as the one that allocates the database
116577 ** structure?
116579 sqlite3DbFree(db, db->aDb[1].pSchema);
116580 sqlite3_mutex_leave(db->mutex);
116581 db->magic = SQLITE_MAGIC_CLOSED;
116582 sqlite3_mutex_free(db->mutex);
116583 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
116584 if( db->lookaside.bMalloced ){
116585 sqlite3_free(db->lookaside.pStart);
116587 sqlite3_free(db);
116591 ** Rollback all database files. If tripCode is not SQLITE_OK, then
116592 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
116593 ** breaker") and made to return tripCode if there are any further
116594 ** attempts to use that cursor.
116596 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
116597 int i;
116598 int inTrans = 0;
116599 assert( sqlite3_mutex_held(db->mutex) );
116600 sqlite3BeginBenignMalloc();
116602 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
116603 ** This is important in case the transaction being rolled back has
116604 ** modified the database schema. If the b-tree mutexes are not taken
116605 ** here, then another shared-cache connection might sneak in between
116606 ** the database rollback and schema reset, which can cause false
116607 ** corruption reports in some cases. */
116608 sqlite3BtreeEnterAll(db);
116610 for(i=0; i<db->nDb; i++){
116611 Btree *p = db->aDb[i].pBt;
116612 if( p ){
116613 if( sqlite3BtreeIsInTrans(p) ){
116614 inTrans = 1;
116616 sqlite3BtreeRollback(p, tripCode);
116619 sqlite3VtabRollback(db);
116620 sqlite3EndBenignMalloc();
116622 if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
116623 sqlite3ExpirePreparedStatements(db);
116624 sqlite3ResetAllSchemasOfConnection(db);
116626 sqlite3BtreeLeaveAll(db);
116628 /* Any deferred constraint violations have now been resolved. */
116629 db->nDeferredCons = 0;
116630 db->nDeferredImmCons = 0;
116631 db->flags &= ~SQLITE_DeferFKs;
116633 /* If one has been configured, invoke the rollback-hook callback */
116634 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
116635 db->xRollbackCallback(db->pRollbackArg);
116640 ** Return a static string containing the name corresponding to the error code
116641 ** specified in the argument.
116643 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
116644 defined(SQLITE_DEBUG_OS_TRACE)
116645 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
116646 const char *zName = 0;
116647 int i, origRc = rc;
116648 for(i=0; i<2 && zName==0; i++, rc &= 0xff){
116649 switch( rc ){
116650 case SQLITE_OK: zName = "SQLITE_OK"; break;
116651 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
116652 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
116653 case SQLITE_PERM: zName = "SQLITE_PERM"; break;
116654 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
116655 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
116656 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
116657 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
116658 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
116659 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
116660 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
116661 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
116662 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
116663 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
116664 case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
116665 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
116666 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
116667 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
116668 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
116669 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
116670 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
116671 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
116672 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
116673 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
116674 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
116675 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
116676 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
116677 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
116678 case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break;
116679 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
116680 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
116681 case SQLITE_IOERR_CHECKRESERVEDLOCK:
116682 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
116683 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
116684 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
116685 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
116686 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
116687 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
116688 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
116689 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
116690 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
116691 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
116692 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
116693 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
116694 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
116695 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
116696 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
116697 case SQLITE_FULL: zName = "SQLITE_FULL"; break;
116698 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
116699 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
116700 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
116701 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
116702 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
116703 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
116704 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
116705 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
116706 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
116707 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
116708 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
116709 case SQLITE_CONSTRAINT_FOREIGNKEY:
116710 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
116711 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
116712 case SQLITE_CONSTRAINT_PRIMARYKEY:
116713 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
116714 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
116715 case SQLITE_CONSTRAINT_COMMITHOOK:
116716 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
116717 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
116718 case SQLITE_CONSTRAINT_FUNCTION:
116719 zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
116720 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
116721 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
116722 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
116723 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
116724 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
116725 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
116726 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
116727 case SQLITE_ROW: zName = "SQLITE_ROW"; break;
116728 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
116729 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
116730 case SQLITE_NOTICE_RECOVER_ROLLBACK:
116731 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
116732 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
116733 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
116734 case SQLITE_DONE: zName = "SQLITE_DONE"; break;
116737 if( zName==0 ){
116738 static char zBuf[50];
116739 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
116740 zName = zBuf;
116742 return zName;
116744 #endif
116747 ** Return a static string that describes the kind of error specified in the
116748 ** argument.
116750 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
116751 static const char* const aMsg[] = {
116752 /* SQLITE_OK */ "not an error",
116753 /* SQLITE_ERROR */ "SQL logic error or missing database",
116754 /* SQLITE_INTERNAL */ 0,
116755 /* SQLITE_PERM */ "access permission denied",
116756 /* SQLITE_ABORT */ "callback requested query abort",
116757 /* SQLITE_BUSY */ "database is locked",
116758 /* SQLITE_LOCKED */ "database table is locked",
116759 /* SQLITE_NOMEM */ "out of memory",
116760 /* SQLITE_READONLY */ "attempt to write a readonly database",
116761 /* SQLITE_INTERRUPT */ "interrupted",
116762 /* SQLITE_IOERR */ "disk I/O error",
116763 /* SQLITE_CORRUPT */ "database disk image is malformed",
116764 /* SQLITE_NOTFOUND */ "unknown operation",
116765 /* SQLITE_FULL */ "database or disk is full",
116766 /* SQLITE_CANTOPEN */ "unable to open database file",
116767 /* SQLITE_PROTOCOL */ "locking protocol",
116768 /* SQLITE_EMPTY */ "table contains no data",
116769 /* SQLITE_SCHEMA */ "database schema has changed",
116770 /* SQLITE_TOOBIG */ "string or blob too big",
116771 /* SQLITE_CONSTRAINT */ "constraint failed",
116772 /* SQLITE_MISMATCH */ "datatype mismatch",
116773 /* SQLITE_MISUSE */ "library routine called out of sequence",
116774 /* SQLITE_NOLFS */ "large file support is disabled",
116775 /* SQLITE_AUTH */ "authorization denied",
116776 /* SQLITE_FORMAT */ "auxiliary database format error",
116777 /* SQLITE_RANGE */ "bind or column index out of range",
116778 /* SQLITE_NOTADB */ "file is encrypted or is not a database",
116780 const char *zErr = "unknown error";
116781 switch( rc ){
116782 case SQLITE_ABORT_ROLLBACK: {
116783 zErr = "abort due to ROLLBACK";
116784 break;
116786 default: {
116787 rc &= 0xff;
116788 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
116789 zErr = aMsg[rc];
116791 break;
116794 return zErr;
116798 ** This routine implements a busy callback that sleeps and tries
116799 ** again until a timeout value is reached. The timeout value is
116800 ** an integer number of milliseconds passed in as the first
116801 ** argument.
116803 static int sqliteDefaultBusyCallback(
116804 void *ptr, /* Database connection */
116805 int count /* Number of times table has been busy */
116807 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
116808 static const u8 delays[] =
116809 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
116810 static const u8 totals[] =
116811 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
116812 # define NDELAY ArraySize(delays)
116813 sqlite3 *db = (sqlite3 *)ptr;
116814 int timeout = db->busyTimeout;
116815 int delay, prior;
116817 assert( count>=0 );
116818 if( count < NDELAY ){
116819 delay = delays[count];
116820 prior = totals[count];
116821 }else{
116822 delay = delays[NDELAY-1];
116823 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
116825 if( prior + delay > timeout ){
116826 delay = timeout - prior;
116827 if( delay<=0 ) return 0;
116829 sqlite3OsSleep(db->pVfs, delay*1000);
116830 return 1;
116831 #else
116832 sqlite3 *db = (sqlite3 *)ptr;
116833 int timeout = ((sqlite3 *)ptr)->busyTimeout;
116834 if( (count+1)*1000 > timeout ){
116835 return 0;
116837 sqlite3OsSleep(db->pVfs, 1000000);
116838 return 1;
116839 #endif
116843 ** Invoke the given busy handler.
116845 ** This routine is called when an operation failed with a lock.
116846 ** If this routine returns non-zero, the lock is retried. If it
116847 ** returns 0, the operation aborts with an SQLITE_BUSY error.
116849 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
116850 int rc;
116851 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
116852 rc = p->xFunc(p->pArg, p->nBusy);
116853 if( rc==0 ){
116854 p->nBusy = -1;
116855 }else{
116856 p->nBusy++;
116858 return rc;
116862 ** This routine sets the busy callback for an Sqlite database to the
116863 ** given callback function with the given argument.
116865 SQLITE_API int sqlite3_busy_handler(
116866 sqlite3 *db,
116867 int (*xBusy)(void*,int),
116868 void *pArg
116870 sqlite3_mutex_enter(db->mutex);
116871 db->busyHandler.xFunc = xBusy;
116872 db->busyHandler.pArg = pArg;
116873 db->busyHandler.nBusy = 0;
116874 db->busyTimeout = 0;
116875 sqlite3_mutex_leave(db->mutex);
116876 return SQLITE_OK;
116879 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
116881 ** This routine sets the progress callback for an Sqlite database to the
116882 ** given callback function with the given argument. The progress callback will
116883 ** be invoked every nOps opcodes.
116885 SQLITE_API void sqlite3_progress_handler(
116886 sqlite3 *db,
116887 int nOps,
116888 int (*xProgress)(void*),
116889 void *pArg
116891 sqlite3_mutex_enter(db->mutex);
116892 if( nOps>0 ){
116893 db->xProgress = xProgress;
116894 db->nProgressOps = (unsigned)nOps;
116895 db->pProgressArg = pArg;
116896 }else{
116897 db->xProgress = 0;
116898 db->nProgressOps = 0;
116899 db->pProgressArg = 0;
116901 sqlite3_mutex_leave(db->mutex);
116903 #endif
116907 ** This routine installs a default busy handler that waits for the
116908 ** specified number of milliseconds before returning 0.
116910 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
116911 if( ms>0 ){
116912 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
116913 db->busyTimeout = ms;
116914 }else{
116915 sqlite3_busy_handler(db, 0, 0);
116917 return SQLITE_OK;
116921 ** Cause any pending operation to stop at its earliest opportunity.
116923 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
116924 db->u1.isInterrupted = 1;
116929 ** This function is exactly the same as sqlite3_create_function(), except
116930 ** that it is designed to be called by internal code. The difference is
116931 ** that if a malloc() fails in sqlite3_create_function(), an error code
116932 ** is returned and the mallocFailed flag cleared.
116934 SQLITE_PRIVATE int sqlite3CreateFunc(
116935 sqlite3 *db,
116936 const char *zFunctionName,
116937 int nArg,
116938 int enc,
116939 void *pUserData,
116940 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
116941 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
116942 void (*xFinal)(sqlite3_context*),
116943 FuncDestructor *pDestructor
116945 FuncDef *p;
116946 int nName;
116948 assert( sqlite3_mutex_held(db->mutex) );
116949 if( zFunctionName==0 ||
116950 (xFunc && (xFinal || xStep)) ||
116951 (!xFunc && (xFinal && !xStep)) ||
116952 (!xFunc && (!xFinal && xStep)) ||
116953 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
116954 (255<(nName = sqlite3Strlen30( zFunctionName))) ){
116955 return SQLITE_MISUSE_BKPT;
116958 #ifndef SQLITE_OMIT_UTF16
116959 /* If SQLITE_UTF16 is specified as the encoding type, transform this
116960 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
116961 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
116963 ** If SQLITE_ANY is specified, add three versions of the function
116964 ** to the hash table.
116966 if( enc==SQLITE_UTF16 ){
116967 enc = SQLITE_UTF16NATIVE;
116968 }else if( enc==SQLITE_ANY ){
116969 int rc;
116970 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
116971 pUserData, xFunc, xStep, xFinal, pDestructor);
116972 if( rc==SQLITE_OK ){
116973 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
116974 pUserData, xFunc, xStep, xFinal, pDestructor);
116976 if( rc!=SQLITE_OK ){
116977 return rc;
116979 enc = SQLITE_UTF16BE;
116981 #else
116982 enc = SQLITE_UTF8;
116983 #endif
116985 /* Check if an existing function is being overridden or deleted. If so,
116986 ** and there are active VMs, then return SQLITE_BUSY. If a function
116987 ** is being overridden/deleted but there are no active VMs, allow the
116988 ** operation to continue but invalidate all precompiled statements.
116990 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
116991 if( p && p->iPrefEnc==enc && p->nArg==nArg ){
116992 if( db->nVdbeActive ){
116993 sqlite3Error(db, SQLITE_BUSY,
116994 "unable to delete/modify user-function due to active statements");
116995 assert( !db->mallocFailed );
116996 return SQLITE_BUSY;
116997 }else{
116998 sqlite3ExpirePreparedStatements(db);
117002 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
117003 assert(p || db->mallocFailed);
117004 if( !p ){
117005 return SQLITE_NOMEM;
117008 /* If an older version of the function with a configured destructor is
117009 ** being replaced invoke the destructor function here. */
117010 functionDestroy(db, p);
117012 if( pDestructor ){
117013 pDestructor->nRef++;
117015 p->pDestructor = pDestructor;
117016 p->flags = 0;
117017 p->xFunc = xFunc;
117018 p->xStep = xStep;
117019 p->xFinalize = xFinal;
117020 p->pUserData = pUserData;
117021 p->nArg = (u16)nArg;
117022 return SQLITE_OK;
117026 ** Create new user functions.
117028 SQLITE_API int sqlite3_create_function(
117029 sqlite3 *db,
117030 const char *zFunc,
117031 int nArg,
117032 int enc,
117033 void *p,
117034 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
117035 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
117036 void (*xFinal)(sqlite3_context*)
117038 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
117039 xFinal, 0);
117042 SQLITE_API int sqlite3_create_function_v2(
117043 sqlite3 *db,
117044 const char *zFunc,
117045 int nArg,
117046 int enc,
117047 void *p,
117048 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
117049 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
117050 void (*xFinal)(sqlite3_context*),
117051 void (*xDestroy)(void *)
117053 int rc = SQLITE_ERROR;
117054 FuncDestructor *pArg = 0;
117055 sqlite3_mutex_enter(db->mutex);
117056 if( xDestroy ){
117057 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
117058 if( !pArg ){
117059 xDestroy(p);
117060 goto out;
117062 pArg->xDestroy = xDestroy;
117063 pArg->pUserData = p;
117065 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
117066 if( pArg && pArg->nRef==0 ){
117067 assert( rc!=SQLITE_OK );
117068 xDestroy(p);
117069 sqlite3DbFree(db, pArg);
117073 rc = sqlite3ApiExit(db, rc);
117074 sqlite3_mutex_leave(db->mutex);
117075 return rc;
117078 #ifndef SQLITE_OMIT_UTF16
117079 SQLITE_API int sqlite3_create_function16(
117080 sqlite3 *db,
117081 const void *zFunctionName,
117082 int nArg,
117083 int eTextRep,
117084 void *p,
117085 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
117086 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
117087 void (*xFinal)(sqlite3_context*)
117089 int rc;
117090 char *zFunc8;
117091 sqlite3_mutex_enter(db->mutex);
117092 assert( !db->mallocFailed );
117093 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
117094 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
117095 sqlite3DbFree(db, zFunc8);
117096 rc = sqlite3ApiExit(db, rc);
117097 sqlite3_mutex_leave(db->mutex);
117098 return rc;
117100 #endif
117104 ** Declare that a function has been overloaded by a virtual table.
117106 ** If the function already exists as a regular global function, then
117107 ** this routine is a no-op. If the function does not exist, then create
117108 ** a new one that always throws a run-time error.
117110 ** When virtual tables intend to provide an overloaded function, they
117111 ** should call this routine to make sure the global function exists.
117112 ** A global function must exist in order for name resolution to work
117113 ** properly.
117115 SQLITE_API int sqlite3_overload_function(
117116 sqlite3 *db,
117117 const char *zName,
117118 int nArg
117120 int nName = sqlite3Strlen30(zName);
117121 int rc = SQLITE_OK;
117122 sqlite3_mutex_enter(db->mutex);
117123 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
117124 rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
117125 0, sqlite3InvalidFunction, 0, 0, 0);
117127 rc = sqlite3ApiExit(db, rc);
117128 sqlite3_mutex_leave(db->mutex);
117129 return rc;
117132 #ifndef SQLITE_OMIT_TRACE
117134 ** Register a trace function. The pArg from the previously registered trace
117135 ** is returned.
117137 ** A NULL trace function means that no tracing is executes. A non-NULL
117138 ** trace is a pointer to a function that is invoked at the start of each
117139 ** SQL statement.
117141 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
117142 void *pOld;
117143 sqlite3_mutex_enter(db->mutex);
117144 pOld = db->pTraceArg;
117145 db->xTrace = xTrace;
117146 db->pTraceArg = pArg;
117147 sqlite3_mutex_leave(db->mutex);
117148 return pOld;
117151 ** Register a profile function. The pArg from the previously registered
117152 ** profile function is returned.
117154 ** A NULL profile function means that no profiling is executes. A non-NULL
117155 ** profile is a pointer to a function that is invoked at the conclusion of
117156 ** each SQL statement that is run.
117158 SQLITE_API void *sqlite3_profile(
117159 sqlite3 *db,
117160 void (*xProfile)(void*,const char*,sqlite_uint64),
117161 void *pArg
117163 void *pOld;
117164 sqlite3_mutex_enter(db->mutex);
117165 pOld = db->pProfileArg;
117166 db->xProfile = xProfile;
117167 db->pProfileArg = pArg;
117168 sqlite3_mutex_leave(db->mutex);
117169 return pOld;
117171 #endif /* SQLITE_OMIT_TRACE */
117174 ** Register a function to be invoked when a transaction commits.
117175 ** If the invoked function returns non-zero, then the commit becomes a
117176 ** rollback.
117178 SQLITE_API void *sqlite3_commit_hook(
117179 sqlite3 *db, /* Attach the hook to this database */
117180 int (*xCallback)(void*), /* Function to invoke on each commit */
117181 void *pArg /* Argument to the function */
117183 void *pOld;
117184 sqlite3_mutex_enter(db->mutex);
117185 pOld = db->pCommitArg;
117186 db->xCommitCallback = xCallback;
117187 db->pCommitArg = pArg;
117188 sqlite3_mutex_leave(db->mutex);
117189 return pOld;
117193 ** Register a callback to be invoked each time a row is updated,
117194 ** inserted or deleted using this database connection.
117196 SQLITE_API void *sqlite3_update_hook(
117197 sqlite3 *db, /* Attach the hook to this database */
117198 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
117199 void *pArg /* Argument to the function */
117201 void *pRet;
117202 sqlite3_mutex_enter(db->mutex);
117203 pRet = db->pUpdateArg;
117204 db->xUpdateCallback = xCallback;
117205 db->pUpdateArg = pArg;
117206 sqlite3_mutex_leave(db->mutex);
117207 return pRet;
117211 ** Register a callback to be invoked each time a transaction is rolled
117212 ** back by this database connection.
117214 SQLITE_API void *sqlite3_rollback_hook(
117215 sqlite3 *db, /* Attach the hook to this database */
117216 void (*xCallback)(void*), /* Callback function */
117217 void *pArg /* Argument to the function */
117219 void *pRet;
117220 sqlite3_mutex_enter(db->mutex);
117221 pRet = db->pRollbackArg;
117222 db->xRollbackCallback = xCallback;
117223 db->pRollbackArg = pArg;
117224 sqlite3_mutex_leave(db->mutex);
117225 return pRet;
117228 #ifndef SQLITE_OMIT_WAL
117230 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
117231 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
117232 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
117233 ** wal_autocheckpoint()).
117235 SQLITE_PRIVATE int sqlite3WalDefaultHook(
117236 void *pClientData, /* Argument */
117237 sqlite3 *db, /* Connection */
117238 const char *zDb, /* Database */
117239 int nFrame /* Size of WAL */
117241 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
117242 sqlite3BeginBenignMalloc();
117243 sqlite3_wal_checkpoint(db, zDb);
117244 sqlite3EndBenignMalloc();
117246 return SQLITE_OK;
117248 #endif /* SQLITE_OMIT_WAL */
117251 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
117252 ** a database after committing a transaction if there are nFrame or
117253 ** more frames in the log file. Passing zero or a negative value as the
117254 ** nFrame parameter disables automatic checkpoints entirely.
117256 ** The callback registered by this function replaces any existing callback
117257 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
117258 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
117259 ** configured by this function.
117261 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
117262 #ifdef SQLITE_OMIT_WAL
117263 UNUSED_PARAMETER(db);
117264 UNUSED_PARAMETER(nFrame);
117265 #else
117266 if( nFrame>0 ){
117267 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
117268 }else{
117269 sqlite3_wal_hook(db, 0, 0);
117271 #endif
117272 return SQLITE_OK;
117276 ** Register a callback to be invoked each time a transaction is written
117277 ** into the write-ahead-log by this database connection.
117279 SQLITE_API void *sqlite3_wal_hook(
117280 sqlite3 *db, /* Attach the hook to this db handle */
117281 int(*xCallback)(void *, sqlite3*, const char*, int),
117282 void *pArg /* First argument passed to xCallback() */
117284 #ifndef SQLITE_OMIT_WAL
117285 void *pRet;
117286 sqlite3_mutex_enter(db->mutex);
117287 pRet = db->pWalArg;
117288 db->xWalCallback = xCallback;
117289 db->pWalArg = pArg;
117290 sqlite3_mutex_leave(db->mutex);
117291 return pRet;
117292 #else
117293 return 0;
117294 #endif
117298 ** Checkpoint database zDb.
117300 SQLITE_API int sqlite3_wal_checkpoint_v2(
117301 sqlite3 *db, /* Database handle */
117302 const char *zDb, /* Name of attached database (or NULL) */
117303 int eMode, /* SQLITE_CHECKPOINT_* value */
117304 int *pnLog, /* OUT: Size of WAL log in frames */
117305 int *pnCkpt /* OUT: Total number of frames checkpointed */
117307 #ifdef SQLITE_OMIT_WAL
117308 return SQLITE_OK;
117309 #else
117310 int rc; /* Return code */
117311 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
117313 /* Initialize the output variables to -1 in case an error occurs. */
117314 if( pnLog ) *pnLog = -1;
117315 if( pnCkpt ) *pnCkpt = -1;
117317 assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
117318 assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
117319 assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
117320 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
117321 return SQLITE_MISUSE;
117324 sqlite3_mutex_enter(db->mutex);
117325 if( zDb && zDb[0] ){
117326 iDb = sqlite3FindDbName(db, zDb);
117328 if( iDb<0 ){
117329 rc = SQLITE_ERROR;
117330 sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
117331 }else{
117332 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
117333 sqlite3Error(db, rc, 0);
117335 rc = sqlite3ApiExit(db, rc);
117336 sqlite3_mutex_leave(db->mutex);
117337 return rc;
117338 #endif
117343 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
117344 ** to contains a zero-length string, all attached databases are
117345 ** checkpointed.
117347 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
117348 return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
117351 #ifndef SQLITE_OMIT_WAL
117353 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
117354 ** not currently open in WAL mode.
117356 ** If a transaction is open on the database being checkpointed, this
117357 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
117358 ** an error occurs while running the checkpoint, an SQLite error code is
117359 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
117361 ** The mutex on database handle db should be held by the caller. The mutex
117362 ** associated with the specific b-tree being checkpointed is taken by
117363 ** this function while the checkpoint is running.
117365 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
117366 ** checkpointed. If an error is encountered it is returned immediately -
117367 ** no attempt is made to checkpoint any remaining databases.
117369 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
117371 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
117372 int rc = SQLITE_OK; /* Return code */
117373 int i; /* Used to iterate through attached dbs */
117374 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
117376 assert( sqlite3_mutex_held(db->mutex) );
117377 assert( !pnLog || *pnLog==-1 );
117378 assert( !pnCkpt || *pnCkpt==-1 );
117380 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
117381 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
117382 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
117383 pnLog = 0;
117384 pnCkpt = 0;
117385 if( rc==SQLITE_BUSY ){
117386 bBusy = 1;
117387 rc = SQLITE_OK;
117392 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
117394 #endif /* SQLITE_OMIT_WAL */
117397 ** This function returns true if main-memory should be used instead of
117398 ** a temporary file for transient pager files and statement journals.
117399 ** The value returned depends on the value of db->temp_store (runtime
117400 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
117401 ** following table describes the relationship between these two values
117402 ** and this functions return value.
117404 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
117405 ** ----------------- -------------- ------------------------------
117406 ** 0 any file (return 0)
117407 ** 1 1 file (return 0)
117408 ** 1 2 memory (return 1)
117409 ** 1 0 file (return 0)
117410 ** 2 1 file (return 0)
117411 ** 2 2 memory (return 1)
117412 ** 2 0 memory (return 1)
117413 ** 3 any memory (return 1)
117415 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
117416 #if SQLITE_TEMP_STORE==1
117417 return ( db->temp_store==2 );
117418 #endif
117419 #if SQLITE_TEMP_STORE==2
117420 return ( db->temp_store!=1 );
117421 #endif
117422 #if SQLITE_TEMP_STORE==3
117423 return 1;
117424 #endif
117425 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
117426 return 0;
117427 #endif
117431 ** Return UTF-8 encoded English language explanation of the most recent
117432 ** error.
117434 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
117435 const char *z;
117436 if( !db ){
117437 return sqlite3ErrStr(SQLITE_NOMEM);
117439 if( !sqlite3SafetyCheckSickOrOk(db) ){
117440 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
117442 sqlite3_mutex_enter(db->mutex);
117443 if( db->mallocFailed ){
117444 z = sqlite3ErrStr(SQLITE_NOMEM);
117445 }else{
117446 z = (char*)sqlite3_value_text(db->pErr);
117447 assert( !db->mallocFailed );
117448 if( z==0 ){
117449 z = sqlite3ErrStr(db->errCode);
117452 sqlite3_mutex_leave(db->mutex);
117453 return z;
117456 #ifndef SQLITE_OMIT_UTF16
117458 ** Return UTF-16 encoded English language explanation of the most recent
117459 ** error.
117461 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
117462 static const u16 outOfMem[] = {
117463 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
117465 static const u16 misuse[] = {
117466 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
117467 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
117468 'c', 'a', 'l', 'l', 'e', 'd', ' ',
117469 'o', 'u', 't', ' ',
117470 'o', 'f', ' ',
117471 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
117474 const void *z;
117475 if( !db ){
117476 return (void *)outOfMem;
117478 if( !sqlite3SafetyCheckSickOrOk(db) ){
117479 return (void *)misuse;
117481 sqlite3_mutex_enter(db->mutex);
117482 if( db->mallocFailed ){
117483 z = (void *)outOfMem;
117484 }else{
117485 z = sqlite3_value_text16(db->pErr);
117486 if( z==0 ){
117487 sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
117488 SQLITE_UTF8, SQLITE_STATIC);
117489 z = sqlite3_value_text16(db->pErr);
117491 /* A malloc() may have failed within the call to sqlite3_value_text16()
117492 ** above. If this is the case, then the db->mallocFailed flag needs to
117493 ** be cleared before returning. Do this directly, instead of via
117494 ** sqlite3ApiExit(), to avoid setting the database handle error message.
117496 db->mallocFailed = 0;
117498 sqlite3_mutex_leave(db->mutex);
117499 return z;
117501 #endif /* SQLITE_OMIT_UTF16 */
117504 ** Return the most recent error code generated by an SQLite routine. If NULL is
117505 ** passed to this function, we assume a malloc() failed during sqlite3_open().
117507 SQLITE_API int sqlite3_errcode(sqlite3 *db){
117508 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
117509 return SQLITE_MISUSE_BKPT;
117511 if( !db || db->mallocFailed ){
117512 return SQLITE_NOMEM;
117514 return db->errCode & db->errMask;
117516 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
117517 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
117518 return SQLITE_MISUSE_BKPT;
117520 if( !db || db->mallocFailed ){
117521 return SQLITE_NOMEM;
117523 return db->errCode;
117527 ** Return a string that describes the kind of error specified in the
117528 ** argument. For now, this simply calls the internal sqlite3ErrStr()
117529 ** function.
117531 SQLITE_API const char *sqlite3_errstr(int rc){
117532 return sqlite3ErrStr(rc);
117536 ** Create a new collating function for database "db". The name is zName
117537 ** and the encoding is enc.
117539 static int createCollation(
117540 sqlite3* db,
117541 const char *zName,
117542 u8 enc,
117543 void* pCtx,
117544 int(*xCompare)(void*,int,const void*,int,const void*),
117545 void(*xDel)(void*)
117547 CollSeq *pColl;
117548 int enc2;
117549 int nName = sqlite3Strlen30(zName);
117551 assert( sqlite3_mutex_held(db->mutex) );
117553 /* If SQLITE_UTF16 is specified as the encoding type, transform this
117554 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
117555 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
117557 enc2 = enc;
117558 testcase( enc2==SQLITE_UTF16 );
117559 testcase( enc2==SQLITE_UTF16_ALIGNED );
117560 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
117561 enc2 = SQLITE_UTF16NATIVE;
117563 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
117564 return SQLITE_MISUSE_BKPT;
117567 /* Check if this call is removing or replacing an existing collation
117568 ** sequence. If so, and there are active VMs, return busy. If there
117569 ** are no active VMs, invalidate any pre-compiled statements.
117571 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
117572 if( pColl && pColl->xCmp ){
117573 if( db->nVdbeActive ){
117574 sqlite3Error(db, SQLITE_BUSY,
117575 "unable to delete/modify collation sequence due to active statements");
117576 return SQLITE_BUSY;
117578 sqlite3ExpirePreparedStatements(db);
117580 /* If collation sequence pColl was created directly by a call to
117581 ** sqlite3_create_collation, and not generated by synthCollSeq(),
117582 ** then any copies made by synthCollSeq() need to be invalidated.
117583 ** Also, collation destructor - CollSeq.xDel() - function may need
117584 ** to be called.
117586 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
117587 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
117588 int j;
117589 for(j=0; j<3; j++){
117590 CollSeq *p = &aColl[j];
117591 if( p->enc==pColl->enc ){
117592 if( p->xDel ){
117593 p->xDel(p->pUser);
117595 p->xCmp = 0;
117601 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
117602 if( pColl==0 ) return SQLITE_NOMEM;
117603 pColl->xCmp = xCompare;
117604 pColl->pUser = pCtx;
117605 pColl->xDel = xDel;
117606 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
117607 sqlite3Error(db, SQLITE_OK, 0);
117608 return SQLITE_OK;
117613 ** This array defines hard upper bounds on limit values. The
117614 ** initializer must be kept in sync with the SQLITE_LIMIT_*
117615 ** #defines in sqlite3.h.
117617 static const int aHardLimit[] = {
117618 SQLITE_MAX_LENGTH,
117619 SQLITE_MAX_SQL_LENGTH,
117620 SQLITE_MAX_COLUMN,
117621 SQLITE_MAX_EXPR_DEPTH,
117622 SQLITE_MAX_COMPOUND_SELECT,
117623 SQLITE_MAX_VDBE_OP,
117624 SQLITE_MAX_FUNCTION_ARG,
117625 SQLITE_MAX_ATTACHED,
117626 SQLITE_MAX_LIKE_PATTERN_LENGTH,
117627 SQLITE_MAX_VARIABLE_NUMBER,
117628 SQLITE_MAX_TRIGGER_DEPTH,
117632 ** Make sure the hard limits are set to reasonable values
117634 #if SQLITE_MAX_LENGTH<100
117635 # error SQLITE_MAX_LENGTH must be at least 100
117636 #endif
117637 #if SQLITE_MAX_SQL_LENGTH<100
117638 # error SQLITE_MAX_SQL_LENGTH must be at least 100
117639 #endif
117640 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
117641 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
117642 #endif
117643 #if SQLITE_MAX_COMPOUND_SELECT<2
117644 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
117645 #endif
117646 #if SQLITE_MAX_VDBE_OP<40
117647 # error SQLITE_MAX_VDBE_OP must be at least 40
117648 #endif
117649 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
117650 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
117651 #endif
117652 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
117653 # error SQLITE_MAX_ATTACHED must be between 0 and 62
117654 #endif
117655 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
117656 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
117657 #endif
117658 #if SQLITE_MAX_COLUMN>32767
117659 # error SQLITE_MAX_COLUMN must not exceed 32767
117660 #endif
117661 #if SQLITE_MAX_TRIGGER_DEPTH<1
117662 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
117663 #endif
117667 ** Change the value of a limit. Report the old value.
117668 ** If an invalid limit index is supplied, report -1.
117669 ** Make no changes but still report the old value if the
117670 ** new limit is negative.
117672 ** A new lower limit does not shrink existing constructs.
117673 ** It merely prevents new constructs that exceed the limit
117674 ** from forming.
117676 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
117677 int oldLimit;
117680 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
117681 ** there is a hard upper bound set at compile-time by a C preprocessor
117682 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
117683 ** "_MAX_".)
117685 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
117686 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
117687 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
117688 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
117689 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
117690 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
117691 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
117692 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
117693 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
117694 SQLITE_MAX_LIKE_PATTERN_LENGTH );
117695 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
117696 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
117697 assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
117700 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
117701 return -1;
117703 oldLimit = db->aLimit[limitId];
117704 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
117705 if( newLimit>aHardLimit[limitId] ){
117706 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
117708 db->aLimit[limitId] = newLimit;
117710 return oldLimit; /* IMP: R-53341-35419 */
117714 ** This function is used to parse both URIs and non-URI filenames passed by the
117715 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
117716 ** URIs specified as part of ATTACH statements.
117718 ** The first argument to this function is the name of the VFS to use (or
117719 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
117720 ** query parameter. The second argument contains the URI (or non-URI filename)
117721 ** itself. When this function is called the *pFlags variable should contain
117722 ** the default flags to open the database handle with. The value stored in
117723 ** *pFlags may be updated before returning if the URI filename contains
117724 ** "cache=xxx" or "mode=xxx" query parameters.
117726 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
117727 ** the VFS that should be used to open the database file. *pzFile is set to
117728 ** point to a buffer containing the name of the file to open. It is the
117729 ** responsibility of the caller to eventually call sqlite3_free() to release
117730 ** this buffer.
117732 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
117733 ** may be set to point to a buffer containing an English language error
117734 ** message. It is the responsibility of the caller to eventually release
117735 ** this buffer by calling sqlite3_free().
117737 SQLITE_PRIVATE int sqlite3ParseUri(
117738 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
117739 const char *zUri, /* Nul-terminated URI to parse */
117740 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
117741 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
117742 char **pzFile, /* OUT: Filename component of URI */
117743 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
117745 int rc = SQLITE_OK;
117746 unsigned int flags = *pFlags;
117747 const char *zVfs = zDefaultVfs;
117748 char *zFile;
117749 char c;
117750 int nUri = sqlite3Strlen30(zUri);
117752 assert( *pzErrMsg==0 );
117754 if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
117755 && nUri>=5 && memcmp(zUri, "file:", 5)==0
117757 char *zOpt;
117758 int eState; /* Parser state when parsing URI */
117759 int iIn; /* Input character index */
117760 int iOut = 0; /* Output character index */
117761 int nByte = nUri+2; /* Bytes of space to allocate */
117763 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
117764 ** method that there may be extra parameters following the file-name. */
117765 flags |= SQLITE_OPEN_URI;
117767 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
117768 zFile = sqlite3_malloc(nByte);
117769 if( !zFile ) return SQLITE_NOMEM;
117771 iIn = 5;
117772 #ifndef SQLITE_ALLOW_URI_AUTHORITY
117773 /* Discard the scheme and authority segments of the URI. */
117774 if( zUri[5]=='/' && zUri[6]=='/' ){
117775 iIn = 7;
117776 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
117777 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
117778 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
117779 iIn-7, &zUri[7]);
117780 rc = SQLITE_ERROR;
117781 goto parse_uri_out;
117784 #endif
117786 /* Copy the filename and any query parameters into the zFile buffer.
117787 ** Decode %HH escape codes along the way.
117789 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
117790 ** on the parsing context. As follows:
117792 ** 0: Parsing file-name.
117793 ** 1: Parsing name section of a name=value query parameter.
117794 ** 2: Parsing value section of a name=value query parameter.
117796 eState = 0;
117797 while( (c = zUri[iIn])!=0 && c!='#' ){
117798 iIn++;
117799 if( c=='%'
117800 && sqlite3Isxdigit(zUri[iIn])
117801 && sqlite3Isxdigit(zUri[iIn+1])
117803 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
117804 octet += sqlite3HexToInt(zUri[iIn++]);
117806 assert( octet>=0 && octet<256 );
117807 if( octet==0 ){
117808 /* This branch is taken when "%00" appears within the URI. In this
117809 ** case we ignore all text in the remainder of the path, name or
117810 ** value currently being parsed. So ignore the current character
117811 ** and skip to the next "?", "=" or "&", as appropriate. */
117812 while( (c = zUri[iIn])!=0 && c!='#'
117813 && (eState!=0 || c!='?')
117814 && (eState!=1 || (c!='=' && c!='&'))
117815 && (eState!=2 || c!='&')
117817 iIn++;
117819 continue;
117821 c = octet;
117822 }else if( eState==1 && (c=='&' || c=='=') ){
117823 if( zFile[iOut-1]==0 ){
117824 /* An empty option name. Ignore this option altogether. */
117825 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
117826 continue;
117828 if( c=='&' ){
117829 zFile[iOut++] = '\0';
117830 }else{
117831 eState = 2;
117833 c = 0;
117834 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
117835 c = 0;
117836 eState = 1;
117838 zFile[iOut++] = c;
117840 if( eState==1 ) zFile[iOut++] = '\0';
117841 zFile[iOut++] = '\0';
117842 zFile[iOut++] = '\0';
117844 /* Check if there were any options specified that should be interpreted
117845 ** here. Options that are interpreted here include "vfs" and those that
117846 ** correspond to flags that may be passed to the sqlite3_open_v2()
117847 ** method. */
117848 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
117849 while( zOpt[0] ){
117850 int nOpt = sqlite3Strlen30(zOpt);
117851 char *zVal = &zOpt[nOpt+1];
117852 int nVal = sqlite3Strlen30(zVal);
117854 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
117855 zVfs = zVal;
117856 }else{
117857 struct OpenMode {
117858 const char *z;
117859 int mode;
117860 } *aMode = 0;
117861 char *zModeType = 0;
117862 int mask = 0;
117863 int limit = 0;
117865 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
117866 static struct OpenMode aCacheMode[] = {
117867 { "shared", SQLITE_OPEN_SHAREDCACHE },
117868 { "private", SQLITE_OPEN_PRIVATECACHE },
117869 { 0, 0 }
117872 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
117873 aMode = aCacheMode;
117874 limit = mask;
117875 zModeType = "cache";
117877 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
117878 static struct OpenMode aOpenMode[] = {
117879 { "ro", SQLITE_OPEN_READONLY },
117880 { "rw", SQLITE_OPEN_READWRITE },
117881 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
117882 { "memory", SQLITE_OPEN_MEMORY },
117883 { 0, 0 }
117886 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
117887 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
117888 aMode = aOpenMode;
117889 limit = mask & flags;
117890 zModeType = "access";
117893 if( aMode ){
117894 int i;
117895 int mode = 0;
117896 for(i=0; aMode[i].z; i++){
117897 const char *z = aMode[i].z;
117898 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
117899 mode = aMode[i].mode;
117900 break;
117903 if( mode==0 ){
117904 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
117905 rc = SQLITE_ERROR;
117906 goto parse_uri_out;
117908 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
117909 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
117910 zModeType, zVal);
117911 rc = SQLITE_PERM;
117912 goto parse_uri_out;
117914 flags = (flags & ~mask) | mode;
117918 zOpt = &zVal[nVal+1];
117921 }else{
117922 zFile = sqlite3_malloc(nUri+2);
117923 if( !zFile ) return SQLITE_NOMEM;
117924 memcpy(zFile, zUri, nUri);
117925 zFile[nUri] = '\0';
117926 zFile[nUri+1] = '\0';
117927 flags &= ~SQLITE_OPEN_URI;
117930 *ppVfs = sqlite3_vfs_find(zVfs);
117931 if( *ppVfs==0 ){
117932 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
117933 rc = SQLITE_ERROR;
117935 parse_uri_out:
117936 if( rc!=SQLITE_OK ){
117937 sqlite3_free(zFile);
117938 zFile = 0;
117940 *pFlags = flags;
117941 *pzFile = zFile;
117942 return rc;
117947 ** This routine does the work of opening a database on behalf of
117948 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
117949 ** is UTF-8 encoded.
117951 static int openDatabase(
117952 const char *zFilename, /* Database filename UTF-8 encoded */
117953 sqlite3 **ppDb, /* OUT: Returned database handle */
117954 unsigned int flags, /* Operational flags */
117955 const char *zVfs /* Name of the VFS to use */
117957 sqlite3 *db; /* Store allocated handle here */
117958 int rc; /* Return code */
117959 int isThreadsafe; /* True for threadsafe connections */
117960 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
117961 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
117963 *ppDb = 0;
117964 #ifndef SQLITE_OMIT_AUTOINIT
117965 rc = sqlite3_initialize();
117966 if( rc ) return rc;
117967 #endif
117969 /* Only allow sensible combinations of bits in the flags argument.
117970 ** Throw an error if any non-sense combination is used. If we
117971 ** do not block illegal combinations here, it could trigger
117972 ** assert() statements in deeper layers. Sensible combinations
117973 ** are:
117975 ** 1: SQLITE_OPEN_READONLY
117976 ** 2: SQLITE_OPEN_READWRITE
117977 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
117979 assert( SQLITE_OPEN_READONLY == 0x01 );
117980 assert( SQLITE_OPEN_READWRITE == 0x02 );
117981 assert( SQLITE_OPEN_CREATE == 0x04 );
117982 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
117983 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
117984 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
117985 if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
117987 if( sqlite3GlobalConfig.bCoreMutex==0 ){
117988 isThreadsafe = 0;
117989 }else if( flags & SQLITE_OPEN_NOMUTEX ){
117990 isThreadsafe = 0;
117991 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
117992 isThreadsafe = 1;
117993 }else{
117994 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
117996 if( flags & SQLITE_OPEN_PRIVATECACHE ){
117997 flags &= ~SQLITE_OPEN_SHAREDCACHE;
117998 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
117999 flags |= SQLITE_OPEN_SHAREDCACHE;
118002 /* Remove harmful bits from the flags parameter
118004 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
118005 ** dealt with in the previous code block. Besides these, the only
118006 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
118007 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
118008 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
118009 ** off all other flags.
118011 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
118012 SQLITE_OPEN_EXCLUSIVE |
118013 SQLITE_OPEN_MAIN_DB |
118014 SQLITE_OPEN_TEMP_DB |
118015 SQLITE_OPEN_TRANSIENT_DB |
118016 SQLITE_OPEN_MAIN_JOURNAL |
118017 SQLITE_OPEN_TEMP_JOURNAL |
118018 SQLITE_OPEN_SUBJOURNAL |
118019 SQLITE_OPEN_MASTER_JOURNAL |
118020 SQLITE_OPEN_NOMUTEX |
118021 SQLITE_OPEN_FULLMUTEX |
118022 SQLITE_OPEN_WAL
118025 /* Allocate the sqlite data structure */
118026 db = sqlite3MallocZero( sizeof(sqlite3) );
118027 if( db==0 ) goto opendb_out;
118028 if( isThreadsafe ){
118029 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
118030 if( db->mutex==0 ){
118031 sqlite3_free(db);
118032 db = 0;
118033 goto opendb_out;
118036 sqlite3_mutex_enter(db->mutex);
118037 db->errMask = 0xff;
118038 db->nDb = 2;
118039 db->magic = SQLITE_MAGIC_BUSY;
118040 db->aDb = db->aDbStatic;
118042 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
118043 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
118044 db->autoCommit = 1;
118045 db->nextAutovac = -1;
118046 db->szMmap = sqlite3GlobalConfig.szMmap;
118047 db->nextPagesize = 0;
118048 db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
118049 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
118050 | SQLITE_AutoIndex
118051 #endif
118052 #if SQLITE_DEFAULT_FILE_FORMAT<4
118053 | SQLITE_LegacyFileFmt
118054 #endif
118055 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
118056 | SQLITE_LoadExtension
118057 #endif
118058 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
118059 | SQLITE_RecTriggers
118060 #endif
118061 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
118062 | SQLITE_ForeignKeys
118063 #endif
118065 sqlite3HashInit(&db->aCollSeq);
118066 #ifndef SQLITE_OMIT_VIRTUALTABLE
118067 sqlite3HashInit(&db->aModule);
118068 #endif
118070 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
118071 ** and UTF-16, so add a version for each to avoid any unnecessary
118072 ** conversions. The only error that can occur here is a malloc() failure.
118074 createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
118075 createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
118076 createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
118077 createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
118078 if( db->mallocFailed ){
118079 goto opendb_out;
118081 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
118082 assert( db->pDfltColl!=0 );
118084 /* Also add a UTF-8 case-insensitive collation sequence. */
118085 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
118087 /* Parse the filename/URI argument. */
118088 db->openFlags = flags;
118089 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
118090 if( rc!=SQLITE_OK ){
118091 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
118092 sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
118093 sqlite3_free(zErrMsg);
118094 goto opendb_out;
118097 /* Open the backend database driver */
118098 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
118099 flags | SQLITE_OPEN_MAIN_DB);
118100 if( rc!=SQLITE_OK ){
118101 if( rc==SQLITE_IOERR_NOMEM ){
118102 rc = SQLITE_NOMEM;
118104 sqlite3Error(db, rc, 0);
118105 goto opendb_out;
118107 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
118108 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
118111 /* The default safety_level for the main database is 'full'; for the temp
118112 ** database it is 'NONE'. This matches the pager layer defaults.
118114 db->aDb[0].zName = "main";
118115 db->aDb[0].safety_level = 3;
118116 db->aDb[1].zName = "temp";
118117 db->aDb[1].safety_level = 1;
118119 db->magic = SQLITE_MAGIC_OPEN;
118120 if( db->mallocFailed ){
118121 goto opendb_out;
118124 /* Register all built-in functions, but do not attempt to read the
118125 ** database schema yet. This is delayed until the first time the database
118126 ** is accessed.
118128 sqlite3Error(db, SQLITE_OK, 0);
118129 sqlite3RegisterBuiltinFunctions(db);
118131 /* Load automatic extensions - extensions that have been registered
118132 ** using the sqlite3_automatic_extension() API.
118134 rc = sqlite3_errcode(db);
118135 if( rc==SQLITE_OK ){
118136 sqlite3AutoLoadExtensions(db);
118137 rc = sqlite3_errcode(db);
118138 if( rc!=SQLITE_OK ){
118139 goto opendb_out;
118143 #ifdef SQLITE_ENABLE_FTS1
118144 if( !db->mallocFailed ){
118145 extern int sqlite3Fts1Init(sqlite3*);
118146 rc = sqlite3Fts1Init(db);
118148 #endif
118150 #ifdef SQLITE_ENABLE_FTS2
118151 if( !db->mallocFailed && rc==SQLITE_OK ){
118152 extern int sqlite3Fts2Init(sqlite3*);
118153 rc = sqlite3Fts2Init(db);
118155 #endif
118157 #ifdef SQLITE_ENABLE_FTS3
118158 if( !db->mallocFailed && rc==SQLITE_OK ){
118159 rc = sqlite3Fts3Init(db);
118161 #endif
118163 #ifdef SQLITE_ENABLE_ICU
118164 if( !db->mallocFailed && rc==SQLITE_OK ){
118165 rc = sqlite3IcuInit(db);
118167 #endif
118169 #ifdef SQLITE_ENABLE_RTREE
118170 if( !db->mallocFailed && rc==SQLITE_OK){
118171 rc = sqlite3RtreeInit(db);
118173 #endif
118175 sqlite3Error(db, rc, 0);
118177 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
118178 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
118179 ** mode. Doing nothing at all also makes NORMAL the default.
118181 #ifdef SQLITE_DEFAULT_LOCKING_MODE
118182 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
118183 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
118184 SQLITE_DEFAULT_LOCKING_MODE);
118185 #endif
118187 /* Enable the lookaside-malloc subsystem */
118188 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
118189 sqlite3GlobalConfig.nLookaside);
118191 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
118193 opendb_out:
118194 sqlite3_free(zOpen);
118195 if( db ){
118196 assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
118197 sqlite3_mutex_leave(db->mutex);
118199 rc = sqlite3_errcode(db);
118200 assert( db!=0 || rc==SQLITE_NOMEM );
118201 if( rc==SQLITE_NOMEM ){
118202 sqlite3_close(db);
118203 db = 0;
118204 }else if( rc!=SQLITE_OK ){
118205 db->magic = SQLITE_MAGIC_SICK;
118207 *ppDb = db;
118208 #ifdef SQLITE_ENABLE_SQLLOG
118209 if( sqlite3GlobalConfig.xSqllog ){
118210 /* Opening a db handle. Fourth parameter is passed 0. */
118211 void *pArg = sqlite3GlobalConfig.pSqllogArg;
118212 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
118214 #endif
118215 return sqlite3ApiExit(0, rc);
118219 ** Open a new database handle.
118221 SQLITE_API int sqlite3_open(
118222 const char *zFilename,
118223 sqlite3 **ppDb
118225 return openDatabase(zFilename, ppDb,
118226 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
118228 SQLITE_API int sqlite3_open_v2(
118229 const char *filename, /* Database filename (UTF-8) */
118230 sqlite3 **ppDb, /* OUT: SQLite db handle */
118231 int flags, /* Flags */
118232 const char *zVfs /* Name of VFS module to use */
118234 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
118237 #ifndef SQLITE_OMIT_UTF16
118239 ** Open a new database handle.
118241 SQLITE_API int sqlite3_open16(
118242 const void *zFilename,
118243 sqlite3 **ppDb
118245 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
118246 sqlite3_value *pVal;
118247 int rc;
118249 assert( zFilename );
118250 assert( ppDb );
118251 *ppDb = 0;
118252 #ifndef SQLITE_OMIT_AUTOINIT
118253 rc = sqlite3_initialize();
118254 if( rc ) return rc;
118255 #endif
118256 pVal = sqlite3ValueNew(0);
118257 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
118258 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
118259 if( zFilename8 ){
118260 rc = openDatabase(zFilename8, ppDb,
118261 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
118262 assert( *ppDb || rc==SQLITE_NOMEM );
118263 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
118264 ENC(*ppDb) = SQLITE_UTF16NATIVE;
118266 }else{
118267 rc = SQLITE_NOMEM;
118269 sqlite3ValueFree(pVal);
118271 return sqlite3ApiExit(0, rc);
118273 #endif /* SQLITE_OMIT_UTF16 */
118276 ** Register a new collation sequence with the database handle db.
118278 SQLITE_API int sqlite3_create_collation(
118279 sqlite3* db,
118280 const char *zName,
118281 int enc,
118282 void* pCtx,
118283 int(*xCompare)(void*,int,const void*,int,const void*)
118285 int rc;
118286 sqlite3_mutex_enter(db->mutex);
118287 assert( !db->mallocFailed );
118288 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
118289 rc = sqlite3ApiExit(db, rc);
118290 sqlite3_mutex_leave(db->mutex);
118291 return rc;
118295 ** Register a new collation sequence with the database handle db.
118297 SQLITE_API int sqlite3_create_collation_v2(
118298 sqlite3* db,
118299 const char *zName,
118300 int enc,
118301 void* pCtx,
118302 int(*xCompare)(void*,int,const void*,int,const void*),
118303 void(*xDel)(void*)
118305 int rc;
118306 sqlite3_mutex_enter(db->mutex);
118307 assert( !db->mallocFailed );
118308 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
118309 rc = sqlite3ApiExit(db, rc);
118310 sqlite3_mutex_leave(db->mutex);
118311 return rc;
118314 #ifndef SQLITE_OMIT_UTF16
118316 ** Register a new collation sequence with the database handle db.
118318 SQLITE_API int sqlite3_create_collation16(
118319 sqlite3* db,
118320 const void *zName,
118321 int enc,
118322 void* pCtx,
118323 int(*xCompare)(void*,int,const void*,int,const void*)
118325 int rc = SQLITE_OK;
118326 char *zName8;
118327 sqlite3_mutex_enter(db->mutex);
118328 assert( !db->mallocFailed );
118329 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
118330 if( zName8 ){
118331 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
118332 sqlite3DbFree(db, zName8);
118334 rc = sqlite3ApiExit(db, rc);
118335 sqlite3_mutex_leave(db->mutex);
118336 return rc;
118338 #endif /* SQLITE_OMIT_UTF16 */
118341 ** Register a collation sequence factory callback with the database handle
118342 ** db. Replace any previously installed collation sequence factory.
118344 SQLITE_API int sqlite3_collation_needed(
118345 sqlite3 *db,
118346 void *pCollNeededArg,
118347 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
118349 sqlite3_mutex_enter(db->mutex);
118350 db->xCollNeeded = xCollNeeded;
118351 db->xCollNeeded16 = 0;
118352 db->pCollNeededArg = pCollNeededArg;
118353 sqlite3_mutex_leave(db->mutex);
118354 return SQLITE_OK;
118357 #ifndef SQLITE_OMIT_UTF16
118359 ** Register a collation sequence factory callback with the database handle
118360 ** db. Replace any previously installed collation sequence factory.
118362 SQLITE_API int sqlite3_collation_needed16(
118363 sqlite3 *db,
118364 void *pCollNeededArg,
118365 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
118367 sqlite3_mutex_enter(db->mutex);
118368 db->xCollNeeded = 0;
118369 db->xCollNeeded16 = xCollNeeded16;
118370 db->pCollNeededArg = pCollNeededArg;
118371 sqlite3_mutex_leave(db->mutex);
118372 return SQLITE_OK;
118374 #endif /* SQLITE_OMIT_UTF16 */
118376 #ifndef SQLITE_OMIT_DEPRECATED
118378 ** This function is now an anachronism. It used to be used to recover from a
118379 ** malloc() failure, but SQLite now does this automatically.
118381 SQLITE_API int sqlite3_global_recover(void){
118382 return SQLITE_OK;
118384 #endif
118387 ** Test to see whether or not the database connection is in autocommit
118388 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
118389 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
118390 ** by the next COMMIT or ROLLBACK.
118392 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
118393 return db->autoCommit;
118397 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
118398 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
118399 ** constants. They server two purposes:
118401 ** 1. Serve as a convenient place to set a breakpoint in a debugger
118402 ** to detect when version error conditions occurs.
118404 ** 2. Invoke sqlite3_log() to provide the source code location where
118405 ** a low-level error is first detected.
118407 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
118408 testcase( sqlite3GlobalConfig.xLog!=0 );
118409 sqlite3_log(SQLITE_CORRUPT,
118410 "database corruption at line %d of [%.10s]",
118411 lineno, 20+sqlite3_sourceid());
118412 return SQLITE_CORRUPT;
118414 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
118415 testcase( sqlite3GlobalConfig.xLog!=0 );
118416 sqlite3_log(SQLITE_MISUSE,
118417 "misuse at line %d of [%.10s]",
118418 lineno, 20+sqlite3_sourceid());
118419 return SQLITE_MISUSE;
118421 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
118422 testcase( sqlite3GlobalConfig.xLog!=0 );
118423 sqlite3_log(SQLITE_CANTOPEN,
118424 "cannot open file at line %d of [%.10s]",
118425 lineno, 20+sqlite3_sourceid());
118426 return SQLITE_CANTOPEN;
118430 #ifndef SQLITE_OMIT_DEPRECATED
118432 ** This is a convenience routine that makes sure that all thread-specific
118433 ** data for this thread has been deallocated.
118435 ** SQLite no longer uses thread-specific data so this routine is now a
118436 ** no-op. It is retained for historical compatibility.
118438 SQLITE_API void sqlite3_thread_cleanup(void){
118440 #endif
118443 ** Return meta information about a specific column of a database table.
118444 ** See comment in sqlite3.h (sqlite.h.in) for details.
118446 #ifdef SQLITE_ENABLE_COLUMN_METADATA
118447 SQLITE_API int sqlite3_table_column_metadata(
118448 sqlite3 *db, /* Connection handle */
118449 const char *zDbName, /* Database name or NULL */
118450 const char *zTableName, /* Table name */
118451 const char *zColumnName, /* Column name */
118452 char const **pzDataType, /* OUTPUT: Declared data type */
118453 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
118454 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
118455 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
118456 int *pAutoinc /* OUTPUT: True if column is auto-increment */
118458 int rc;
118459 char *zErrMsg = 0;
118460 Table *pTab = 0;
118461 Column *pCol = 0;
118462 int iCol;
118464 char const *zDataType = 0;
118465 char const *zCollSeq = 0;
118466 int notnull = 0;
118467 int primarykey = 0;
118468 int autoinc = 0;
118470 /* Ensure the database schema has been loaded */
118471 sqlite3_mutex_enter(db->mutex);
118472 sqlite3BtreeEnterAll(db);
118473 rc = sqlite3Init(db, &zErrMsg);
118474 if( SQLITE_OK!=rc ){
118475 goto error_out;
118478 /* Locate the table in question */
118479 pTab = sqlite3FindTable(db, zTableName, zDbName);
118480 if( !pTab || pTab->pSelect ){
118481 pTab = 0;
118482 goto error_out;
118485 /* Find the column for which info is requested */
118486 if( sqlite3IsRowid(zColumnName) ){
118487 iCol = pTab->iPKey;
118488 if( iCol>=0 ){
118489 pCol = &pTab->aCol[iCol];
118491 }else{
118492 for(iCol=0; iCol<pTab->nCol; iCol++){
118493 pCol = &pTab->aCol[iCol];
118494 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
118495 break;
118498 if( iCol==pTab->nCol ){
118499 pTab = 0;
118500 goto error_out;
118504 /* The following block stores the meta information that will be returned
118505 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
118506 ** and autoinc. At this point there are two possibilities:
118508 ** 1. The specified column name was rowid", "oid" or "_rowid_"
118509 ** and there is no explicitly declared IPK column.
118511 ** 2. The table is not a view and the column name identified an
118512 ** explicitly declared column. Copy meta information from *pCol.
118514 if( pCol ){
118515 zDataType = pCol->zType;
118516 zCollSeq = pCol->zColl;
118517 notnull = pCol->notNull!=0;
118518 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
118519 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
118520 }else{
118521 zDataType = "INTEGER";
118522 primarykey = 1;
118524 if( !zCollSeq ){
118525 zCollSeq = "BINARY";
118528 error_out:
118529 sqlite3BtreeLeaveAll(db);
118531 /* Whether the function call succeeded or failed, set the output parameters
118532 ** to whatever their local counterparts contain. If an error did occur,
118533 ** this has the effect of zeroing all output parameters.
118535 if( pzDataType ) *pzDataType = zDataType;
118536 if( pzCollSeq ) *pzCollSeq = zCollSeq;
118537 if( pNotNull ) *pNotNull = notnull;
118538 if( pPrimaryKey ) *pPrimaryKey = primarykey;
118539 if( pAutoinc ) *pAutoinc = autoinc;
118541 if( SQLITE_OK==rc && !pTab ){
118542 sqlite3DbFree(db, zErrMsg);
118543 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
118544 zColumnName);
118545 rc = SQLITE_ERROR;
118547 sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
118548 sqlite3DbFree(db, zErrMsg);
118549 rc = sqlite3ApiExit(db, rc);
118550 sqlite3_mutex_leave(db->mutex);
118551 return rc;
118553 #endif
118556 ** Sleep for a little while. Return the amount of time slept.
118558 SQLITE_API int sqlite3_sleep(int ms){
118559 sqlite3_vfs *pVfs;
118560 int rc;
118561 pVfs = sqlite3_vfs_find(0);
118562 if( pVfs==0 ) return 0;
118564 /* This function works in milliseconds, but the underlying OsSleep()
118565 ** API uses microseconds. Hence the 1000's.
118567 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
118568 return rc;
118572 ** Enable or disable the extended result codes.
118574 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
118575 sqlite3_mutex_enter(db->mutex);
118576 db->errMask = onoff ? 0xffffffff : 0xff;
118577 sqlite3_mutex_leave(db->mutex);
118578 return SQLITE_OK;
118582 ** Invoke the xFileControl method on a particular database.
118584 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
118585 int rc = SQLITE_ERROR;
118586 Btree *pBtree;
118588 sqlite3_mutex_enter(db->mutex);
118589 pBtree = sqlite3DbNameToBtree(db, zDbName);
118590 if( pBtree ){
118591 Pager *pPager;
118592 sqlite3_file *fd;
118593 sqlite3BtreeEnter(pBtree);
118594 pPager = sqlite3BtreePager(pBtree);
118595 assert( pPager!=0 );
118596 fd = sqlite3PagerFile(pPager);
118597 assert( fd!=0 );
118598 if( op==SQLITE_FCNTL_FILE_POINTER ){
118599 *(sqlite3_file**)pArg = fd;
118600 rc = SQLITE_OK;
118601 }else if( fd->pMethods ){
118602 rc = sqlite3OsFileControl(fd, op, pArg);
118603 }else{
118604 rc = SQLITE_NOTFOUND;
118606 sqlite3BtreeLeave(pBtree);
118608 sqlite3_mutex_leave(db->mutex);
118609 return rc;
118613 ** Interface to the testing logic.
118615 SQLITE_API int sqlite3_test_control(int op, ...){
118616 int rc = 0;
118617 #ifndef SQLITE_OMIT_BUILTIN_TEST
118618 va_list ap;
118619 va_start(ap, op);
118620 switch( op ){
118623 ** Save the current state of the PRNG.
118625 case SQLITE_TESTCTRL_PRNG_SAVE: {
118626 sqlite3PrngSaveState();
118627 break;
118631 ** Restore the state of the PRNG to the last state saved using
118632 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
118633 ** this verb acts like PRNG_RESET.
118635 case SQLITE_TESTCTRL_PRNG_RESTORE: {
118636 sqlite3PrngRestoreState();
118637 break;
118641 ** Reset the PRNG back to its uninitialized state. The next call
118642 ** to sqlite3_randomness() will reseed the PRNG using a single call
118643 ** to the xRandomness method of the default VFS.
118645 case SQLITE_TESTCTRL_PRNG_RESET: {
118646 sqlite3PrngResetState();
118647 break;
118651 ** sqlite3_test_control(BITVEC_TEST, size, program)
118653 ** Run a test against a Bitvec object of size. The program argument
118654 ** is an array of integers that defines the test. Return -1 on a
118655 ** memory allocation error, 0 on success, or non-zero for an error.
118656 ** See the sqlite3BitvecBuiltinTest() for additional information.
118658 case SQLITE_TESTCTRL_BITVEC_TEST: {
118659 int sz = va_arg(ap, int);
118660 int *aProg = va_arg(ap, int*);
118661 rc = sqlite3BitvecBuiltinTest(sz, aProg);
118662 break;
118666 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
118668 ** Register hooks to call to indicate which malloc() failures
118669 ** are benign.
118671 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
118672 typedef void (*void_function)(void);
118673 void_function xBenignBegin;
118674 void_function xBenignEnd;
118675 xBenignBegin = va_arg(ap, void_function);
118676 xBenignEnd = va_arg(ap, void_function);
118677 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
118678 break;
118682 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
118684 ** Set the PENDING byte to the value in the argument, if X>0.
118685 ** Make no changes if X==0. Return the value of the pending byte
118686 ** as it existing before this routine was called.
118688 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
118689 ** an incompatible database file format. Changing the PENDING byte
118690 ** while any database connection is open results in undefined and
118691 ** dileterious behavior.
118693 case SQLITE_TESTCTRL_PENDING_BYTE: {
118694 rc = PENDING_BYTE;
118695 #ifndef SQLITE_OMIT_WSD
118697 unsigned int newVal = va_arg(ap, unsigned int);
118698 if( newVal ) sqlite3PendingByte = newVal;
118700 #endif
118701 break;
118705 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
118707 ** This action provides a run-time test to see whether or not
118708 ** assert() was enabled at compile-time. If X is true and assert()
118709 ** is enabled, then the return value is true. If X is true and
118710 ** assert() is disabled, then the return value is zero. If X is
118711 ** false and assert() is enabled, then the assertion fires and the
118712 ** process aborts. If X is false and assert() is disabled, then the
118713 ** return value is zero.
118715 case SQLITE_TESTCTRL_ASSERT: {
118716 volatile int x = 0;
118717 assert( (x = va_arg(ap,int))!=0 );
118718 rc = x;
118719 break;
118724 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
118726 ** This action provides a run-time test to see how the ALWAYS and
118727 ** NEVER macros were defined at compile-time.
118729 ** The return value is ALWAYS(X).
118731 ** The recommended test is X==2. If the return value is 2, that means
118732 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
118733 ** default setting. If the return value is 1, then ALWAYS() is either
118734 ** hard-coded to true or else it asserts if its argument is false.
118735 ** The first behavior (hard-coded to true) is the case if
118736 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
118737 ** behavior (assert if the argument to ALWAYS() is false) is the case if
118738 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
118740 ** The run-time test procedure might look something like this:
118742 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
118743 ** // ALWAYS() and NEVER() are no-op pass-through macros
118744 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
118745 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
118746 ** }else{
118747 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
118750 case SQLITE_TESTCTRL_ALWAYS: {
118751 int x = va_arg(ap,int);
118752 rc = ALWAYS(x);
118753 break;
118756 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
118758 ** Set the nReserve size to N for the main database on the database
118759 ** connection db.
118761 case SQLITE_TESTCTRL_RESERVE: {
118762 sqlite3 *db = va_arg(ap, sqlite3*);
118763 int x = va_arg(ap,int);
118764 sqlite3_mutex_enter(db->mutex);
118765 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
118766 sqlite3_mutex_leave(db->mutex);
118767 break;
118770 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
118772 ** Enable or disable various optimizations for testing purposes. The
118773 ** argument N is a bitmask of optimizations to be disabled. For normal
118774 ** operation N should be 0. The idea is that a test program (like the
118775 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
118776 ** with various optimizations disabled to verify that the same answer
118777 ** is obtained in every case.
118779 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
118780 sqlite3 *db = va_arg(ap, sqlite3*);
118781 db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
118782 break;
118785 #ifdef SQLITE_N_KEYWORD
118786 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
118788 ** If zWord is a keyword recognized by the parser, then return the
118789 ** number of keywords. Or if zWord is not a keyword, return 0.
118791 ** This test feature is only available in the amalgamation since
118792 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
118793 ** is built using separate source files.
118795 case SQLITE_TESTCTRL_ISKEYWORD: {
118796 const char *zWord = va_arg(ap, const char*);
118797 int n = sqlite3Strlen30(zWord);
118798 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
118799 break;
118801 #endif
118803 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
118805 ** Pass pFree into sqlite3ScratchFree().
118806 ** If sz>0 then allocate a scratch buffer into pNew.
118808 case SQLITE_TESTCTRL_SCRATCHMALLOC: {
118809 void *pFree, **ppNew;
118810 int sz;
118811 sz = va_arg(ap, int);
118812 ppNew = va_arg(ap, void**);
118813 pFree = va_arg(ap, void*);
118814 if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
118815 sqlite3ScratchFree(pFree);
118816 break;
118819 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
118821 ** If parameter onoff is non-zero, configure the wrappers so that all
118822 ** subsequent calls to localtime() and variants fail. If onoff is zero,
118823 ** undo this setting.
118825 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
118826 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
118827 break;
118830 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
118831 /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
118832 ** sqlite3_stmt*,const char**);
118834 ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
118835 ** a string that describes the optimized parse tree. This test-control
118836 ** returns a pointer to that string.
118838 case SQLITE_TESTCTRL_EXPLAIN_STMT: {
118839 sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
118840 const char **pzRet = va_arg(ap, const char**);
118841 *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
118842 break;
118844 #endif
118847 va_end(ap);
118848 #endif /* SQLITE_OMIT_BUILTIN_TEST */
118849 return rc;
118853 ** This is a utility routine, useful to VFS implementations, that checks
118854 ** to see if a database file was a URI that contained a specific query
118855 ** parameter, and if so obtains the value of the query parameter.
118857 ** The zFilename argument is the filename pointer passed into the xOpen()
118858 ** method of a VFS implementation. The zParam argument is the name of the
118859 ** query parameter we seek. This routine returns the value of the zParam
118860 ** parameter if it exists. If the parameter does not exist, this routine
118861 ** returns a NULL pointer.
118863 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
118864 if( zFilename==0 ) return 0;
118865 zFilename += sqlite3Strlen30(zFilename) + 1;
118866 while( zFilename[0] ){
118867 int x = strcmp(zFilename, zParam);
118868 zFilename += sqlite3Strlen30(zFilename) + 1;
118869 if( x==0 ) return zFilename;
118870 zFilename += sqlite3Strlen30(zFilename) + 1;
118872 return 0;
118876 ** Return a boolean value for a query parameter.
118878 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
118879 const char *z = sqlite3_uri_parameter(zFilename, zParam);
118880 bDflt = bDflt!=0;
118881 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
118885 ** Return a 64-bit integer value for a query parameter.
118887 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
118888 const char *zFilename, /* Filename as passed to xOpen */
118889 const char *zParam, /* URI parameter sought */
118890 sqlite3_int64 bDflt /* return if parameter is missing */
118892 const char *z = sqlite3_uri_parameter(zFilename, zParam);
118893 sqlite3_int64 v;
118894 if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
118895 bDflt = v;
118897 return bDflt;
118901 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
118903 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
118904 int i;
118905 for(i=0; i<db->nDb; i++){
118906 if( db->aDb[i].pBt
118907 && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
118909 return db->aDb[i].pBt;
118912 return 0;
118916 ** Return the filename of the database associated with a database
118917 ** connection.
118919 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
118920 Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
118921 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
118925 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
118926 ** no such database exists.
118928 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
118929 Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
118930 return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
118933 /************** End of main.c ************************************************/
118934 /************** Begin file notify.c ******************************************/
118936 ** 2009 March 3
118938 ** The author disclaims copyright to this source code. In place of
118939 ** a legal notice, here is a blessing:
118941 ** May you do good and not evil.
118942 ** May you find forgiveness for yourself and forgive others.
118943 ** May you share freely, never taking more than you give.
118945 *************************************************************************
118947 ** This file contains the implementation of the sqlite3_unlock_notify()
118948 ** API method and its associated functionality.
118951 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
118952 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
118955 ** Public interfaces:
118957 ** sqlite3ConnectionBlocked()
118958 ** sqlite3ConnectionUnlocked()
118959 ** sqlite3ConnectionClosed()
118960 ** sqlite3_unlock_notify()
118963 #define assertMutexHeld() \
118964 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
118967 ** Head of a linked list of all sqlite3 objects created by this process
118968 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
118969 ** is not NULL. This variable may only accessed while the STATIC_MASTER
118970 ** mutex is held.
118972 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
118974 #ifndef NDEBUG
118976 ** This function is a complex assert() that verifies the following
118977 ** properties of the blocked connections list:
118979 ** 1) Each entry in the list has a non-NULL value for either
118980 ** pUnlockConnection or pBlockingConnection, or both.
118982 ** 2) All entries in the list that share a common value for
118983 ** xUnlockNotify are grouped together.
118985 ** 3) If the argument db is not NULL, then none of the entries in the
118986 ** blocked connections list have pUnlockConnection or pBlockingConnection
118987 ** set to db. This is used when closing connection db.
118989 static void checkListProperties(sqlite3 *db){
118990 sqlite3 *p;
118991 for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
118992 int seen = 0;
118993 sqlite3 *p2;
118995 /* Verify property (1) */
118996 assert( p->pUnlockConnection || p->pBlockingConnection );
118998 /* Verify property (2) */
118999 for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
119000 if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
119001 assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
119002 assert( db==0 || p->pUnlockConnection!=db );
119003 assert( db==0 || p->pBlockingConnection!=db );
119007 #else
119008 # define checkListProperties(x)
119009 #endif
119012 ** Remove connection db from the blocked connections list. If connection
119013 ** db is not currently a part of the list, this function is a no-op.
119015 static void removeFromBlockedList(sqlite3 *db){
119016 sqlite3 **pp;
119017 assertMutexHeld();
119018 for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
119019 if( *pp==db ){
119020 *pp = (*pp)->pNextBlocked;
119021 break;
119027 ** Add connection db to the blocked connections list. It is assumed
119028 ** that it is not already a part of the list.
119030 static void addToBlockedList(sqlite3 *db){
119031 sqlite3 **pp;
119032 assertMutexHeld();
119034 pp=&sqlite3BlockedList;
119035 *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
119036 pp=&(*pp)->pNextBlocked
119038 db->pNextBlocked = *pp;
119039 *pp = db;
119043 ** Obtain the STATIC_MASTER mutex.
119045 static void enterMutex(void){
119046 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
119047 checkListProperties(0);
119051 ** Release the STATIC_MASTER mutex.
119053 static void leaveMutex(void){
119054 assertMutexHeld();
119055 checkListProperties(0);
119056 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
119060 ** Register an unlock-notify callback.
119062 ** This is called after connection "db" has attempted some operation
119063 ** but has received an SQLITE_LOCKED error because another connection
119064 ** (call it pOther) in the same process was busy using the same shared
119065 ** cache. pOther is found by looking at db->pBlockingConnection.
119067 ** If there is no blocking connection, the callback is invoked immediately,
119068 ** before this routine returns.
119070 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
119071 ** a deadlock.
119073 ** Otherwise, make arrangements to invoke xNotify when pOther drops
119074 ** its locks.
119076 ** Each call to this routine overrides any prior callbacks registered
119077 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
119078 ** cancelled.
119080 SQLITE_API int sqlite3_unlock_notify(
119081 sqlite3 *db,
119082 void (*xNotify)(void **, int),
119083 void *pArg
119085 int rc = SQLITE_OK;
119087 sqlite3_mutex_enter(db->mutex);
119088 enterMutex();
119090 if( xNotify==0 ){
119091 removeFromBlockedList(db);
119092 db->pBlockingConnection = 0;
119093 db->pUnlockConnection = 0;
119094 db->xUnlockNotify = 0;
119095 db->pUnlockArg = 0;
119096 }else if( 0==db->pBlockingConnection ){
119097 /* The blocking transaction has been concluded. Or there never was a
119098 ** blocking transaction. In either case, invoke the notify callback
119099 ** immediately.
119101 xNotify(&pArg, 1);
119102 }else{
119103 sqlite3 *p;
119105 for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
119106 if( p ){
119107 rc = SQLITE_LOCKED; /* Deadlock detected. */
119108 }else{
119109 db->pUnlockConnection = db->pBlockingConnection;
119110 db->xUnlockNotify = xNotify;
119111 db->pUnlockArg = pArg;
119112 removeFromBlockedList(db);
119113 addToBlockedList(db);
119117 leaveMutex();
119118 assert( !db->mallocFailed );
119119 sqlite3Error(db, rc, (rc?"database is deadlocked":0));
119120 sqlite3_mutex_leave(db->mutex);
119121 return rc;
119125 ** This function is called while stepping or preparing a statement
119126 ** associated with connection db. The operation will return SQLITE_LOCKED
119127 ** to the user because it requires a lock that will not be available
119128 ** until connection pBlocker concludes its current transaction.
119130 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
119131 enterMutex();
119132 if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
119133 addToBlockedList(db);
119135 db->pBlockingConnection = pBlocker;
119136 leaveMutex();
119140 ** This function is called when
119141 ** the transaction opened by database db has just finished. Locks held
119142 ** by database connection db have been released.
119144 ** This function loops through each entry in the blocked connections
119145 ** list and does the following:
119147 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
119148 ** set to db, then set pBlockingConnection=0.
119150 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
119151 ** set to db, then invoke the configured unlock-notify callback and
119152 ** set pUnlockConnection=0.
119154 ** 3) If the two steps above mean that pBlockingConnection==0 and
119155 ** pUnlockConnection==0, remove the entry from the blocked connections
119156 ** list.
119158 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
119159 void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
119160 int nArg = 0; /* Number of entries in aArg[] */
119161 sqlite3 **pp; /* Iterator variable */
119162 void **aArg; /* Arguments to the unlock callback */
119163 void **aDyn = 0; /* Dynamically allocated space for aArg[] */
119164 void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
119166 aArg = aStatic;
119167 enterMutex(); /* Enter STATIC_MASTER mutex */
119169 /* This loop runs once for each entry in the blocked-connections list. */
119170 for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
119171 sqlite3 *p = *pp;
119173 /* Step 1. */
119174 if( p->pBlockingConnection==db ){
119175 p->pBlockingConnection = 0;
119178 /* Step 2. */
119179 if( p->pUnlockConnection==db ){
119180 assert( p->xUnlockNotify );
119181 if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
119182 xUnlockNotify(aArg, nArg);
119183 nArg = 0;
119186 sqlite3BeginBenignMalloc();
119187 assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
119188 assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
119189 if( (!aDyn && nArg==(int)ArraySize(aStatic))
119190 || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
119192 /* The aArg[] array needs to grow. */
119193 void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
119194 if( pNew ){
119195 memcpy(pNew, aArg, nArg*sizeof(void *));
119196 sqlite3_free(aDyn);
119197 aDyn = aArg = pNew;
119198 }else{
119199 /* This occurs when the array of context pointers that need to
119200 ** be passed to the unlock-notify callback is larger than the
119201 ** aStatic[] array allocated on the stack and the attempt to
119202 ** allocate a larger array from the heap has failed.
119204 ** This is a difficult situation to handle. Returning an error
119205 ** code to the caller is insufficient, as even if an error code
119206 ** is returned the transaction on connection db will still be
119207 ** closed and the unlock-notify callbacks on blocked connections
119208 ** will go unissued. This might cause the application to wait
119209 ** indefinitely for an unlock-notify callback that will never
119210 ** arrive.
119212 ** Instead, invoke the unlock-notify callback with the context
119213 ** array already accumulated. We can then clear the array and
119214 ** begin accumulating any further context pointers without
119215 ** requiring any dynamic allocation. This is sub-optimal because
119216 ** it means that instead of one callback with a large array of
119217 ** context pointers the application will receive two or more
119218 ** callbacks with smaller arrays of context pointers, which will
119219 ** reduce the applications ability to prioritize multiple
119220 ** connections. But it is the best that can be done under the
119221 ** circumstances.
119223 xUnlockNotify(aArg, nArg);
119224 nArg = 0;
119227 sqlite3EndBenignMalloc();
119229 aArg[nArg++] = p->pUnlockArg;
119230 xUnlockNotify = p->xUnlockNotify;
119231 p->pUnlockConnection = 0;
119232 p->xUnlockNotify = 0;
119233 p->pUnlockArg = 0;
119236 /* Step 3. */
119237 if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
119238 /* Remove connection p from the blocked connections list. */
119239 *pp = p->pNextBlocked;
119240 p->pNextBlocked = 0;
119241 }else{
119242 pp = &p->pNextBlocked;
119246 if( nArg!=0 ){
119247 xUnlockNotify(aArg, nArg);
119249 sqlite3_free(aDyn);
119250 leaveMutex(); /* Leave STATIC_MASTER mutex */
119254 ** This is called when the database connection passed as an argument is
119255 ** being closed. The connection is removed from the blocked list.
119257 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
119258 sqlite3ConnectionUnlocked(db);
119259 enterMutex();
119260 removeFromBlockedList(db);
119261 checkListProperties(db);
119262 leaveMutex();
119264 #endif
119266 /************** End of notify.c **********************************************/
119267 /************** Begin file fts3.c ********************************************/
119269 ** 2006 Oct 10
119271 ** The author disclaims copyright to this source code. In place of
119272 ** a legal notice, here is a blessing:
119274 ** May you do good and not evil.
119275 ** May you find forgiveness for yourself and forgive others.
119276 ** May you share freely, never taking more than you give.
119278 ******************************************************************************
119280 ** This is an SQLite module implementing full-text search.
119284 ** The code in this file is only compiled if:
119286 ** * The FTS3 module is being built as an extension
119287 ** (in which case SQLITE_CORE is not defined), or
119289 ** * The FTS3 module is being built into the core of
119290 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
119293 /* The full-text index is stored in a series of b+tree (-like)
119294 ** structures called segments which map terms to doclists. The
119295 ** structures are like b+trees in layout, but are constructed from the
119296 ** bottom up in optimal fashion and are not updatable. Since trees
119297 ** are built from the bottom up, things will be described from the
119298 ** bottom up.
119301 **** Varints ****
119302 ** The basic unit of encoding is a variable-length integer called a
119303 ** varint. We encode variable-length integers in little-endian order
119304 ** using seven bits * per byte as follows:
119306 ** KEY:
119307 ** A = 0xxxxxxx 7 bits of data and one flag bit
119308 ** B = 1xxxxxxx 7 bits of data and one flag bit
119310 ** 7 bits - A
119311 ** 14 bits - BA
119312 ** 21 bits - BBA
119313 ** and so on.
119315 ** This is similar in concept to how sqlite encodes "varints" but
119316 ** the encoding is not the same. SQLite varints are big-endian
119317 ** are are limited to 9 bytes in length whereas FTS3 varints are
119318 ** little-endian and can be up to 10 bytes in length (in theory).
119320 ** Example encodings:
119322 ** 1: 0x01
119323 ** 127: 0x7f
119324 ** 128: 0x81 0x00
119327 **** Document lists ****
119328 ** A doclist (document list) holds a docid-sorted list of hits for a
119329 ** given term. Doclists hold docids and associated token positions.
119330 ** A docid is the unique integer identifier for a single document.
119331 ** A position is the index of a word within the document. The first
119332 ** word of the document has a position of 0.
119334 ** FTS3 used to optionally store character offsets using a compile-time
119335 ** option. But that functionality is no longer supported.
119337 ** A doclist is stored like this:
119339 ** array {
119340 ** varint docid; (delta from previous doclist)
119341 ** array { (position list for column 0)
119342 ** varint position; (2 more than the delta from previous position)
119344 ** array {
119345 ** varint POS_COLUMN; (marks start of position list for new column)
119346 ** varint column; (index of new column)
119347 ** array {
119348 ** varint position; (2 more than the delta from previous position)
119351 ** varint POS_END; (marks end of positions for this document.
119354 ** Here, array { X } means zero or more occurrences of X, adjacent in
119355 ** memory. A "position" is an index of a token in the token stream
119356 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
119357 ** in the same logical place as the position element, and act as sentinals
119358 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
119359 ** The positions numbers are not stored literally but rather as two more
119360 ** than the difference from the prior position, or the just the position plus
119361 ** 2 for the first position. Example:
119363 ** label: A B C D E F G H I J K
119364 ** value: 123 5 9 1 1 14 35 0 234 72 0
119366 ** The 123 value is the first docid. For column zero in this document
119367 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
119368 ** at D signals the start of a new column; the 1 at E indicates that the
119369 ** new column is column number 1. There are two positions at 12 and 45
119370 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
119371 ** 234 at I is the delta to next docid (357). It has one position 70
119372 ** (72-2) and then terminates with the 0 at K.
119374 ** A "position-list" is the list of positions for multiple columns for
119375 ** a single docid. A "column-list" is the set of positions for a single
119376 ** column. Hence, a position-list consists of one or more column-lists,
119377 ** a document record consists of a docid followed by a position-list and
119378 ** a doclist consists of one or more document records.
119380 ** A bare doclist omits the position information, becoming an
119381 ** array of varint-encoded docids.
119383 **** Segment leaf nodes ****
119384 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
119385 ** nodes are written using LeafWriter, and read using LeafReader (to
119386 ** iterate through a single leaf node's data) and LeavesReader (to
119387 ** iterate through a segment's entire leaf layer). Leaf nodes have
119388 ** the format:
119390 ** varint iHeight; (height from leaf level, always 0)
119391 ** varint nTerm; (length of first term)
119392 ** char pTerm[nTerm]; (content of first term)
119393 ** varint nDoclist; (length of term's associated doclist)
119394 ** char pDoclist[nDoclist]; (content of doclist)
119395 ** array {
119396 ** (further terms are delta-encoded)
119397 ** varint nPrefix; (length of prefix shared with previous term)
119398 ** varint nSuffix; (length of unshared suffix)
119399 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
119400 ** varint nDoclist; (length of term's associated doclist)
119401 ** char pDoclist[nDoclist]; (content of doclist)
119404 ** Here, array { X } means zero or more occurrences of X, adjacent in
119405 ** memory.
119407 ** Leaf nodes are broken into blocks which are stored contiguously in
119408 ** the %_segments table in sorted order. This means that when the end
119409 ** of a node is reached, the next term is in the node with the next
119410 ** greater node id.
119412 ** New data is spilled to a new leaf node when the current node
119413 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
119414 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
119415 ** node (a leaf node with a single term and doclist). The goal of
119416 ** these settings is to pack together groups of small doclists while
119417 ** making it efficient to directly access large doclists. The
119418 ** assumption is that large doclists represent terms which are more
119419 ** likely to be query targets.
119421 ** TODO(shess) It may be useful for blocking decisions to be more
119422 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
119423 ** node rather than splitting into 2k and .5k nodes. My intuition is
119424 ** that this might extend through 2x or 4x the pagesize.
119427 **** Segment interior nodes ****
119428 ** Segment interior nodes store blockids for subtree nodes and terms
119429 ** to describe what data is stored by the each subtree. Interior
119430 ** nodes are written using InteriorWriter, and read using
119431 ** InteriorReader. InteriorWriters are created as needed when
119432 ** SegmentWriter creates new leaf nodes, or when an interior node
119433 ** itself grows too big and must be split. The format of interior
119434 ** nodes:
119436 ** varint iHeight; (height from leaf level, always >0)
119437 ** varint iBlockid; (block id of node's leftmost subtree)
119438 ** optional {
119439 ** varint nTerm; (length of first term)
119440 ** char pTerm[nTerm]; (content of first term)
119441 ** array {
119442 ** (further terms are delta-encoded)
119443 ** varint nPrefix; (length of shared prefix with previous term)
119444 ** varint nSuffix; (length of unshared suffix)
119445 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
119449 ** Here, optional { X } means an optional element, while array { X }
119450 ** means zero or more occurrences of X, adjacent in memory.
119452 ** An interior node encodes n terms separating n+1 subtrees. The
119453 ** subtree blocks are contiguous, so only the first subtree's blockid
119454 ** is encoded. The subtree at iBlockid will contain all terms less
119455 ** than the first term encoded (or all terms if no term is encoded).
119456 ** Otherwise, for terms greater than or equal to pTerm[i] but less
119457 ** than pTerm[i+1], the subtree for that term will be rooted at
119458 ** iBlockid+i. Interior nodes only store enough term data to
119459 ** distinguish adjacent children (if the rightmost term of the left
119460 ** child is "something", and the leftmost term of the right child is
119461 ** "wicked", only "w" is stored).
119463 ** New data is spilled to a new interior node at the same height when
119464 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
119465 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
119466 ** interior nodes and making the tree too skinny. The interior nodes
119467 ** at a given height are naturally tracked by interior nodes at
119468 ** height+1, and so on.
119471 **** Segment directory ****
119472 ** The segment directory in table %_segdir stores meta-information for
119473 ** merging and deleting segments, and also the root node of the
119474 ** segment's tree.
119476 ** The root node is the top node of the segment's tree after encoding
119477 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
119478 ** This could be either a leaf node or an interior node. If the top
119479 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
119480 ** and a new root interior node is generated (which should always fit
119481 ** within ROOT_MAX because it only needs space for 2 varints, the
119482 ** height and the blockid of the previous root).
119484 ** The meta-information in the segment directory is:
119485 ** level - segment level (see below)
119486 ** idx - index within level
119487 ** - (level,idx uniquely identify a segment)
119488 ** start_block - first leaf node
119489 ** leaves_end_block - last leaf node
119490 ** end_block - last block (including interior nodes)
119491 ** root - contents of root node
119493 ** If the root node is a leaf node, then start_block,
119494 ** leaves_end_block, and end_block are all 0.
119497 **** Segment merging ****
119498 ** To amortize update costs, segments are grouped into levels and
119499 ** merged in batches. Each increase in level represents exponentially
119500 ** more documents.
119502 ** New documents (actually, document updates) are tokenized and
119503 ** written individually (using LeafWriter) to a level 0 segment, with
119504 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
119505 ** level 0 segments are merged into a single level 1 segment. Level 1
119506 ** is populated like level 0, and eventually MERGE_COUNT level 1
119507 ** segments are merged to a single level 2 segment (representing
119508 ** MERGE_COUNT^2 updates), and so on.
119510 ** A segment merge traverses all segments at a given level in
119511 ** parallel, performing a straightforward sorted merge. Since segment
119512 ** leaf nodes are written in to the %_segments table in order, this
119513 ** merge traverses the underlying sqlite disk structures efficiently.
119514 ** After the merge, all segment blocks from the merged level are
119515 ** deleted.
119517 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
119518 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
119519 ** very similar performance numbers to 16 on insertion, though they're
119520 ** a tiny bit slower (perhaps due to more overhead in merge-time
119521 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
119522 ** 16, 2 about 66% slower than 16.
119524 ** At query time, high MERGE_COUNT increases the number of segments
119525 ** which need to be scanned and merged. For instance, with 100k docs
119526 ** inserted:
119528 ** MERGE_COUNT segments
119529 ** 16 25
119530 ** 8 12
119531 ** 4 10
119532 ** 2 6
119534 ** This appears to have only a moderate impact on queries for very
119535 ** frequent terms (which are somewhat dominated by segment merge
119536 ** costs), and infrequent and non-existent terms still seem to be fast
119537 ** even with many segments.
119539 ** TODO(shess) That said, it would be nice to have a better query-side
119540 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
119541 ** optimizations to things like doclist merging will swing the sweet
119542 ** spot around.
119546 **** Handling of deletions and updates ****
119547 ** Since we're using a segmented structure, with no docid-oriented
119548 ** index into the term index, we clearly cannot simply update the term
119549 ** index when a document is deleted or updated. For deletions, we
119550 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
119551 ** we simply write the new doclist. Segment merges overwrite older
119552 ** data for a particular docid with newer data, so deletes or updates
119553 ** will eventually overtake the earlier data and knock it out. The
119554 ** query logic likewise merges doclists so that newer data knocks out
119555 ** older data.
119558 /************** Include fts3Int.h in the middle of fts3.c ********************/
119559 /************** Begin file fts3Int.h *****************************************/
119561 ** 2009 Nov 12
119563 ** The author disclaims copyright to this source code. In place of
119564 ** a legal notice, here is a blessing:
119566 ** May you do good and not evil.
119567 ** May you find forgiveness for yourself and forgive others.
119568 ** May you share freely, never taking more than you give.
119570 ******************************************************************************
119573 #ifndef _FTSINT_H
119574 #define _FTSINT_H
119576 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
119577 # define NDEBUG 1
119578 #endif
119581 ** FTS4 is really an extension for FTS3. It is enabled using the
119582 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
119583 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
119585 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
119586 # define SQLITE_ENABLE_FTS3
119587 #endif
119589 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119591 /* If not building as part of the core, include sqlite3ext.h. */
119592 #ifndef SQLITE_CORE
119593 SQLITE_EXTENSION_INIT3
119594 #endif
119596 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
119597 /************** Begin file fts3_tokenizer.h **********************************/
119599 ** 2006 July 10
119601 ** The author disclaims copyright to this source code.
119603 *************************************************************************
119604 ** Defines the interface to tokenizers used by fulltext-search. There
119605 ** are three basic components:
119607 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
119608 ** interface functions. This is essentially the class structure for
119609 ** tokenizers.
119611 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
119612 ** including customization information defined at creation time.
119614 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
119615 ** tokens from a particular input.
119617 #ifndef _FTS3_TOKENIZER_H_
119618 #define _FTS3_TOKENIZER_H_
119620 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
119621 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
119622 ** we will need a way to register the API consistently.
119626 ** Structures used by the tokenizer interface. When a new tokenizer
119627 ** implementation is registered, the caller provides a pointer to
119628 ** an sqlite3_tokenizer_module containing pointers to the callback
119629 ** functions that make up an implementation.
119631 ** When an fts3 table is created, it passes any arguments passed to
119632 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
119633 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
119634 ** implementation. The xCreate() function in turn returns an
119635 ** sqlite3_tokenizer structure representing the specific tokenizer to
119636 ** be used for the fts3 table (customized by the tokenizer clause arguments).
119638 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
119639 ** method is called. It returns an sqlite3_tokenizer_cursor object
119640 ** that may be used to tokenize a specific input buffer based on
119641 ** the tokenization rules supplied by a specific sqlite3_tokenizer
119642 ** object.
119644 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
119645 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
119646 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
119648 struct sqlite3_tokenizer_module {
119651 ** Structure version. Should always be set to 0 or 1.
119653 int iVersion;
119656 ** Create a new tokenizer. The values in the argv[] array are the
119657 ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
119658 ** TABLE statement that created the fts3 table. For example, if
119659 ** the following SQL is executed:
119661 ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
119663 ** then argc is set to 2, and the argv[] array contains pointers
119664 ** to the strings "arg1" and "arg2".
119666 ** This method should return either SQLITE_OK (0), or an SQLite error
119667 ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
119668 ** to point at the newly created tokenizer structure. The generic
119669 ** sqlite3_tokenizer.pModule variable should not be initialized by
119670 ** this callback. The caller will do so.
119672 int (*xCreate)(
119673 int argc, /* Size of argv array */
119674 const char *const*argv, /* Tokenizer argument strings */
119675 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
119679 ** Destroy an existing tokenizer. The fts3 module calls this method
119680 ** exactly once for each successful call to xCreate().
119682 int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
119685 ** Create a tokenizer cursor to tokenize an input buffer. The caller
119686 ** is responsible for ensuring that the input buffer remains valid
119687 ** until the cursor is closed (using the xClose() method).
119689 int (*xOpen)(
119690 sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
119691 const char *pInput, int nBytes, /* Input buffer */
119692 sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
119696 ** Destroy an existing tokenizer cursor. The fts3 module calls this
119697 ** method exactly once for each successful call to xOpen().
119699 int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
119702 ** Retrieve the next token from the tokenizer cursor pCursor. This
119703 ** method should either return SQLITE_OK and set the values of the
119704 ** "OUT" variables identified below, or SQLITE_DONE to indicate that
119705 ** the end of the buffer has been reached, or an SQLite error code.
119707 ** *ppToken should be set to point at a buffer containing the
119708 ** normalized version of the token (i.e. after any case-folding and/or
119709 ** stemming has been performed). *pnBytes should be set to the length
119710 ** of this buffer in bytes. The input text that generated the token is
119711 ** identified by the byte offsets returned in *piStartOffset and
119712 ** *piEndOffset. *piStartOffset should be set to the index of the first
119713 ** byte of the token in the input buffer. *piEndOffset should be set
119714 ** to the index of the first byte just past the end of the token in
119715 ** the input buffer.
119717 ** The buffer *ppToken is set to point at is managed by the tokenizer
119718 ** implementation. It is only required to be valid until the next call
119719 ** to xNext() or xClose().
119721 /* TODO(shess) current implementation requires pInput to be
119722 ** nul-terminated. This should either be fixed, or pInput/nBytes
119723 ** should be converted to zInput.
119725 int (*xNext)(
119726 sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
119727 const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
119728 int *piStartOffset, /* OUT: Byte offset of token in input buffer */
119729 int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
119730 int *piPosition /* OUT: Number of tokens returned before this one */
119733 /***********************************************************************
119734 ** Methods below this point are only available if iVersion>=1.
119738 ** Configure the language id of a tokenizer cursor.
119740 int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
119743 struct sqlite3_tokenizer {
119744 const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
119745 /* Tokenizer implementations will typically add additional fields */
119748 struct sqlite3_tokenizer_cursor {
119749 sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
119750 /* Tokenizer implementations will typically add additional fields */
119753 int fts3_global_term_cnt(int iTerm, int iCol);
119754 int fts3_term_cnt(int iTerm, int iCol);
119757 #endif /* _FTS3_TOKENIZER_H_ */
119759 /************** End of fts3_tokenizer.h **************************************/
119760 /************** Continuing where we left off in fts3Int.h ********************/
119761 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
119762 /************** Begin file fts3_hash.h ***************************************/
119764 ** 2001 September 22
119766 ** The author disclaims copyright to this source code. In place of
119767 ** a legal notice, here is a blessing:
119769 ** May you do good and not evil.
119770 ** May you find forgiveness for yourself and forgive others.
119771 ** May you share freely, never taking more than you give.
119773 *************************************************************************
119774 ** This is the header file for the generic hash-table implementation
119775 ** used in SQLite. We've modified it slightly to serve as a standalone
119776 ** hash table implementation for the full-text indexing module.
119779 #ifndef _FTS3_HASH_H_
119780 #define _FTS3_HASH_H_
119782 /* Forward declarations of structures. */
119783 typedef struct Fts3Hash Fts3Hash;
119784 typedef struct Fts3HashElem Fts3HashElem;
119786 /* A complete hash table is an instance of the following structure.
119787 ** The internals of this structure are intended to be opaque -- client
119788 ** code should not attempt to access or modify the fields of this structure
119789 ** directly. Change this structure only by using the routines below.
119790 ** However, many of the "procedures" and "functions" for modifying and
119791 ** accessing this structure are really macros, so we can't really make
119792 ** this structure opaque.
119794 struct Fts3Hash {
119795 char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
119796 char copyKey; /* True if copy of key made on insert */
119797 int count; /* Number of entries in this table */
119798 Fts3HashElem *first; /* The first element of the array */
119799 int htsize; /* Number of buckets in the hash table */
119800 struct _fts3ht { /* the hash table */
119801 int count; /* Number of entries with this hash */
119802 Fts3HashElem *chain; /* Pointer to first entry with this hash */
119803 } *ht;
119806 /* Each element in the hash table is an instance of the following
119807 ** structure. All elements are stored on a single doubly-linked list.
119809 ** Again, this structure is intended to be opaque, but it can't really
119810 ** be opaque because it is used by macros.
119812 struct Fts3HashElem {
119813 Fts3HashElem *next, *prev; /* Next and previous elements in the table */
119814 void *data; /* Data associated with this element */
119815 void *pKey; int nKey; /* Key associated with this element */
119819 ** There are 2 different modes of operation for a hash table:
119821 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
119822 ** (including the null-terminator, if any). Case
119823 ** is respected in comparisons.
119825 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
119826 ** memcmp() is used to compare keys.
119828 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
119830 #define FTS3_HASH_STRING 1
119831 #define FTS3_HASH_BINARY 2
119834 ** Access routines. To delete, insert a NULL pointer.
119836 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
119837 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
119838 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
119839 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
119840 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
119843 ** Shorthand for the functions above
119845 #define fts3HashInit sqlite3Fts3HashInit
119846 #define fts3HashInsert sqlite3Fts3HashInsert
119847 #define fts3HashFind sqlite3Fts3HashFind
119848 #define fts3HashClear sqlite3Fts3HashClear
119849 #define fts3HashFindElem sqlite3Fts3HashFindElem
119852 ** Macros for looping over all elements of a hash table. The idiom is
119853 ** like this:
119855 ** Fts3Hash h;
119856 ** Fts3HashElem *p;
119857 ** ...
119858 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
119859 ** SomeStructure *pData = fts3HashData(p);
119860 ** // do something with pData
119863 #define fts3HashFirst(H) ((H)->first)
119864 #define fts3HashNext(E) ((E)->next)
119865 #define fts3HashData(E) ((E)->data)
119866 #define fts3HashKey(E) ((E)->pKey)
119867 #define fts3HashKeysize(E) ((E)->nKey)
119870 ** Number of entries in a hash table
119872 #define fts3HashCount(H) ((H)->count)
119874 #endif /* _FTS3_HASH_H_ */
119876 /************** End of fts3_hash.h *******************************************/
119877 /************** Continuing where we left off in fts3Int.h ********************/
119880 ** This constant determines the maximum depth of an FTS expression tree
119881 ** that the library will create and use. FTS uses recursion to perform
119882 ** various operations on the query tree, so the disadvantage of a large
119883 ** limit is that it may allow very large queries to use large amounts
119884 ** of stack space (perhaps causing a stack overflow).
119886 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
119887 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
119888 #endif
119892 ** This constant controls how often segments are merged. Once there are
119893 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
119894 ** segment of level N+1.
119896 #define FTS3_MERGE_COUNT 16
119899 ** This is the maximum amount of data (in bytes) to store in the
119900 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
119901 ** populated as documents are inserted/updated/deleted in a transaction
119902 ** and used to create a new segment when the transaction is committed.
119903 ** However if this limit is reached midway through a transaction, a new
119904 ** segment is created and the hash table cleared immediately.
119906 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
119909 ** Macro to return the number of elements in an array. SQLite has a
119910 ** similar macro called ArraySize(). Use a different name to avoid
119911 ** a collision when building an amalgamation with built-in FTS3.
119913 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
119916 #ifndef MIN
119917 # define MIN(x,y) ((x)<(y)?(x):(y))
119918 #endif
119919 #ifndef MAX
119920 # define MAX(x,y) ((x)>(y)?(x):(y))
119921 #endif
119924 ** Maximum length of a varint encoded integer. The varint format is different
119925 ** from that used by SQLite, so the maximum length is 10, not 9.
119927 #define FTS3_VARINT_MAX 10
119930 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
119931 ** in the document set and zero or more prefix indexes. All indexes are stored
119932 ** as one or more b+-trees in the %_segments and %_segdir tables.
119934 ** It is possible to determine which index a b+-tree belongs to based on the
119935 ** value stored in the "%_segdir.level" column. Given this value L, the index
119936 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
119937 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
119938 ** between 1024 and 2047 to index 1, and so on.
119940 ** It is considered impossible for an index to use more than 1024 levels. In
119941 ** theory though this may happen, but only after at least
119942 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
119944 #define FTS3_SEGDIR_MAXLEVEL 1024
119945 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
119948 ** The testcase() macro is only used by the amalgamation. If undefined,
119949 ** make it a no-op.
119951 #ifndef testcase
119952 # define testcase(X)
119953 #endif
119956 ** Terminator values for position-lists and column-lists.
119958 #define POS_COLUMN (1) /* Column-list terminator */
119959 #define POS_END (0) /* Position-list terminator */
119962 ** This section provides definitions to allow the
119963 ** FTS3 extension to be compiled outside of the
119964 ** amalgamation.
119966 #ifndef SQLITE_AMALGAMATION
119968 ** Macros indicating that conditional expressions are always true or
119969 ** false.
119971 #ifdef SQLITE_COVERAGE_TEST
119972 # define ALWAYS(x) (1)
119973 # define NEVER(X) (0)
119974 #else
119975 # define ALWAYS(x) (x)
119976 # define NEVER(x) (x)
119977 #endif
119980 ** Internal types used by SQLite.
119982 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
119983 typedef short int i16; /* 2-byte (or larger) signed integer */
119984 typedef unsigned int u32; /* 4-byte unsigned integer */
119985 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
119986 typedef sqlite3_int64 i64; /* 8-byte signed integer */
119989 ** Macro used to suppress compiler warnings for unused parameters.
119991 #define UNUSED_PARAMETER(x) (void)(x)
119994 ** Activate assert() only if SQLITE_TEST is enabled.
119996 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
119997 # define NDEBUG 1
119998 #endif
120001 ** The TESTONLY macro is used to enclose variable declarations or
120002 ** other bits of code that are needed to support the arguments
120003 ** within testcase() and assert() macros.
120005 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
120006 # define TESTONLY(X) X
120007 #else
120008 # define TESTONLY(X)
120009 #endif
120011 #endif /* SQLITE_AMALGAMATION */
120013 #ifdef SQLITE_DEBUG
120014 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
120015 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
120016 #else
120017 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
120018 #endif
120020 typedef struct Fts3Table Fts3Table;
120021 typedef struct Fts3Cursor Fts3Cursor;
120022 typedef struct Fts3Expr Fts3Expr;
120023 typedef struct Fts3Phrase Fts3Phrase;
120024 typedef struct Fts3PhraseToken Fts3PhraseToken;
120026 typedef struct Fts3Doclist Fts3Doclist;
120027 typedef struct Fts3SegFilter Fts3SegFilter;
120028 typedef struct Fts3DeferredToken Fts3DeferredToken;
120029 typedef struct Fts3SegReader Fts3SegReader;
120030 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
120033 ** A connection to a fulltext index is an instance of the following
120034 ** structure. The xCreate and xConnect methods create an instance
120035 ** of this structure and xDestroy and xDisconnect free that instance.
120036 ** All other methods receive a pointer to the structure as one of their
120037 ** arguments.
120039 struct Fts3Table {
120040 sqlite3_vtab base; /* Base class used by SQLite core */
120041 sqlite3 *db; /* The database connection */
120042 const char *zDb; /* logical database name */
120043 const char *zName; /* virtual table name */
120044 int nColumn; /* number of named columns in virtual table */
120045 char **azColumn; /* column names. malloced */
120046 u8 *abNotindexed; /* True for 'notindexed' columns */
120047 sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
120048 char *zContentTbl; /* content=xxx option, or NULL */
120049 char *zLanguageid; /* languageid=xxx option, or NULL */
120050 u8 bAutoincrmerge; /* True if automerge=1 */
120051 u32 nLeafAdd; /* Number of leaf blocks added this trans */
120053 /* Precompiled statements used by the implementation. Each of these
120054 ** statements is run and reset within a single virtual table API call.
120056 sqlite3_stmt *aStmt[37];
120058 char *zReadExprlist;
120059 char *zWriteExprlist;
120061 int nNodeSize; /* Soft limit for node size */
120062 u8 bFts4; /* True for FTS4, false for FTS3 */
120063 u8 bHasStat; /* True if %_stat table exists */
120064 u8 bHasDocsize; /* True if %_docsize table exists */
120065 u8 bDescIdx; /* True if doclists are in reverse order */
120066 u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
120067 int nPgsz; /* Page size for host database */
120068 char *zSegmentsTbl; /* Name of %_segments table */
120069 sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
120072 ** The following array of hash tables is used to buffer pending index
120073 ** updates during transactions. All pending updates buffered at any one
120074 ** time must share a common language-id (see the FTS4 langid= feature).
120075 ** The current language id is stored in variable iPrevLangid.
120077 ** A single FTS4 table may have multiple full-text indexes. For each index
120078 ** there is an entry in the aIndex[] array. Index 0 is an index of all the
120079 ** terms that appear in the document set. Each subsequent index in aIndex[]
120080 ** is an index of prefixes of a specific length.
120082 ** Variable nPendingData contains an estimate the memory consumed by the
120083 ** pending data structures, including hash table overhead, but not including
120084 ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
120085 ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
120086 ** recently inserted record.
120088 int nIndex; /* Size of aIndex[] */
120089 struct Fts3Index {
120090 int nPrefix; /* Prefix length (0 for main terms index) */
120091 Fts3Hash hPending; /* Pending terms table for this index */
120092 } *aIndex;
120093 int nMaxPendingData; /* Max pending data before flush to disk */
120094 int nPendingData; /* Current bytes of pending data */
120095 sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
120096 int iPrevLangid; /* Langid of recently inserted document */
120098 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
120099 /* State variables used for validating that the transaction control
120100 ** methods of the virtual table are called at appropriate times. These
120101 ** values do not contribute to FTS functionality; they are used for
120102 ** verifying the operation of the SQLite core.
120104 int inTransaction; /* True after xBegin but before xCommit/xRollback */
120105 int mxSavepoint; /* Largest valid xSavepoint integer */
120106 #endif
120110 ** When the core wants to read from the virtual table, it creates a
120111 ** virtual table cursor (an instance of the following structure) using
120112 ** the xOpen method. Cursors are destroyed using the xClose method.
120114 struct Fts3Cursor {
120115 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
120116 i16 eSearch; /* Search strategy (see below) */
120117 u8 isEof; /* True if at End Of Results */
120118 u8 isRequireSeek; /* True if must seek pStmt to %_content row */
120119 sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
120120 Fts3Expr *pExpr; /* Parsed MATCH query string */
120121 int iLangid; /* Language being queried for */
120122 int nPhrase; /* Number of matchable phrases in query */
120123 Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
120124 sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
120125 char *pNextId; /* Pointer into the body of aDoclist */
120126 char *aDoclist; /* List of docids for full-text queries */
120127 int nDoclist; /* Size of buffer at aDoclist */
120128 u8 bDesc; /* True to sort in descending order */
120129 int eEvalmode; /* An FTS3_EVAL_XX constant */
120130 int nRowAvg; /* Average size of database rows, in pages */
120131 sqlite3_int64 nDoc; /* Documents in table */
120133 int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
120134 u32 *aMatchinfo; /* Information about most recent match */
120135 int nMatchinfo; /* Number of elements in aMatchinfo[] */
120136 char *zMatchinfo; /* Matchinfo specification */
120139 #define FTS3_EVAL_FILTER 0
120140 #define FTS3_EVAL_NEXT 1
120141 #define FTS3_EVAL_MATCHINFO 2
120144 ** The Fts3Cursor.eSearch member is always set to one of the following.
120145 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
120146 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
120147 ** of the column to be searched. For example, in
120149 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
120150 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
120152 ** Because the LHS of the MATCH operator is 2nd column "b",
120153 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
120154 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
120155 ** indicating that all columns should be searched,
120156 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
120158 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
120159 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
120160 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
120163 struct Fts3Doclist {
120164 char *aAll; /* Array containing doclist (or NULL) */
120165 int nAll; /* Size of a[] in bytes */
120166 char *pNextDocid; /* Pointer to next docid */
120168 sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
120169 int bFreeList; /* True if pList should be sqlite3_free()d */
120170 char *pList; /* Pointer to position list following iDocid */
120171 int nList; /* Length of position list */
120175 ** A "phrase" is a sequence of one or more tokens that must match in
120176 ** sequence. A single token is the base case and the most common case.
120177 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
120178 ** nToken will be the number of tokens in the string.
120180 struct Fts3PhraseToken {
120181 char *z; /* Text of the token */
120182 int n; /* Number of bytes in buffer z */
120183 int isPrefix; /* True if token ends with a "*" character */
120184 int bFirst; /* True if token must appear at position 0 */
120186 /* Variables above this point are populated when the expression is
120187 ** parsed (by code in fts3_expr.c). Below this point the variables are
120188 ** used when evaluating the expression. */
120189 Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
120190 Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
120193 struct Fts3Phrase {
120194 /* Cache of doclist for this phrase. */
120195 Fts3Doclist doclist;
120196 int bIncr; /* True if doclist is loaded incrementally */
120197 int iDoclistToken;
120199 /* Variables below this point are populated by fts3_expr.c when parsing
120200 ** a MATCH expression. Everything above is part of the evaluation phase.
120202 int nToken; /* Number of tokens in the phrase */
120203 int iColumn; /* Index of column this phrase must match */
120204 Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
120208 ** A tree of these objects forms the RHS of a MATCH operator.
120210 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
120211 ** points to a malloced buffer, size nDoclist bytes, containing the results
120212 ** of this phrase query in FTS3 doclist format. As usual, the initial
120213 ** "Length" field found in doclists stored on disk is omitted from this
120214 ** buffer.
120216 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
120217 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
120218 ** where nCol is the number of columns in the queried FTS table. The array
120219 ** is populated as follows:
120221 ** aMI[iCol*3 + 0] = Undefined
120222 ** aMI[iCol*3 + 1] = Number of occurrences
120223 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
120225 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
120226 ** when the expression node is.
120228 struct Fts3Expr {
120229 int eType; /* One of the FTSQUERY_XXX values defined below */
120230 int nNear; /* Valid if eType==FTSQUERY_NEAR */
120231 Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
120232 Fts3Expr *pLeft; /* Left operand */
120233 Fts3Expr *pRight; /* Right operand */
120234 Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
120236 /* The following are used by the fts3_eval.c module. */
120237 sqlite3_int64 iDocid; /* Current docid */
120238 u8 bEof; /* True this expression is at EOF already */
120239 u8 bStart; /* True if iDocid is valid */
120240 u8 bDeferred; /* True if this expression is entirely deferred */
120242 u32 *aMI;
120246 ** Candidate values for Fts3Query.eType. Note that the order of the first
120247 ** four values is in order of precedence when parsing expressions. For
120248 ** example, the following:
120250 ** "a OR b AND c NOT d NEAR e"
120252 ** is equivalent to:
120254 ** "a OR (b AND (c NOT (d NEAR e)))"
120256 #define FTSQUERY_NEAR 1
120257 #define FTSQUERY_NOT 2
120258 #define FTSQUERY_AND 3
120259 #define FTSQUERY_OR 4
120260 #define FTSQUERY_PHRASE 5
120263 /* fts3_write.c */
120264 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
120265 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
120266 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
120267 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
120268 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
120269 sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
120270 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
120271 Fts3Table*,int,const char*,int,int,Fts3SegReader**);
120272 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
120273 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
120274 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
120276 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
120277 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
120279 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
120280 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
120281 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
120282 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
120283 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
120284 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
120285 #else
120286 # define sqlite3Fts3FreeDeferredTokens(x)
120287 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
120288 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
120289 # define sqlite3Fts3FreeDeferredDoclists(x)
120290 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
120291 #endif
120293 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
120294 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
120296 /* Special values interpreted by sqlite3SegReaderCursor() */
120297 #define FTS3_SEGCURSOR_PENDING -1
120298 #define FTS3_SEGCURSOR_ALL -2
120300 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
120301 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
120302 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
120304 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
120305 int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
120307 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
120308 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
120309 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
120310 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
120311 #define FTS3_SEGMENT_PREFIX 0x00000008
120312 #define FTS3_SEGMENT_SCAN 0x00000010
120313 #define FTS3_SEGMENT_FIRST 0x00000020
120315 /* Type passed as 4th argument to SegmentReaderIterate() */
120316 struct Fts3SegFilter {
120317 const char *zTerm;
120318 int nTerm;
120319 int iCol;
120320 int flags;
120323 struct Fts3MultiSegReader {
120324 /* Used internally by sqlite3Fts3SegReaderXXX() calls */
120325 Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
120326 int nSegment; /* Size of apSegment array */
120327 int nAdvance; /* How many seg-readers to advance */
120328 Fts3SegFilter *pFilter; /* Pointer to filter object */
120329 char *aBuffer; /* Buffer to merge doclists in */
120330 int nBuffer; /* Allocated size of aBuffer[] in bytes */
120332 int iColFilter; /* If >=0, filter for this column */
120333 int bRestart;
120335 /* Used by fts3.c only. */
120336 int nCost; /* Cost of running iterator */
120337 int bLookup; /* True if a lookup of a single entry. */
120339 /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
120340 char *zTerm; /* Pointer to term buffer */
120341 int nTerm; /* Size of zTerm in bytes */
120342 char *aDoclist; /* Pointer to doclist buffer */
120343 int nDoclist; /* Size of aDoclist[] in bytes */
120346 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
120348 /* fts3.c */
120349 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
120350 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
120351 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
120352 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
120353 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
120354 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
120355 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
120356 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
120357 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
120359 /* fts3_tokenizer.c */
120360 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
120361 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
120362 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
120363 sqlite3_tokenizer **, char **
120365 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
120367 /* fts3_snippet.c */
120368 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
120369 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
120370 const char *, const char *, int, int
120372 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
120374 /* fts3_expr.c */
120375 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
120376 char **, int, int, int, const char *, int, Fts3Expr **, char **
120378 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
120379 #ifdef SQLITE_TEST
120380 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
120381 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
120382 #endif
120384 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
120385 sqlite3_tokenizer_cursor **
120388 /* fts3_aux.c */
120389 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
120391 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
120393 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
120394 Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
120395 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
120396 Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
120397 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
120398 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
120399 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
120401 /* fts3_tokenize_vtab.c */
120402 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
120404 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
120405 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
120406 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
120407 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
120408 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
120409 #endif
120411 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
120412 #endif /* _FTSINT_H */
120414 /************** End of fts3Int.h *********************************************/
120415 /************** Continuing where we left off in fts3.c ***********************/
120416 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
120418 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
120419 # define SQLITE_CORE 1
120420 #endif
120422 /* #include <assert.h> */
120423 /* #include <stdlib.h> */
120424 /* #include <stddef.h> */
120425 /* #include <stdio.h> */
120426 /* #include <string.h> */
120427 /* #include <stdarg.h> */
120429 #ifndef SQLITE_CORE
120430 SQLITE_EXTENSION_INIT1
120431 #endif
120433 static int fts3EvalNext(Fts3Cursor *pCsr);
120434 static int fts3EvalStart(Fts3Cursor *pCsr);
120435 static int fts3TermSegReaderCursor(
120436 Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
120439 ** Write a 64-bit variable-length integer to memory starting at p[0].
120440 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
120441 ** The number of bytes written is returned.
120443 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
120444 unsigned char *q = (unsigned char *) p;
120445 sqlite_uint64 vu = v;
120447 *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
120448 vu >>= 7;
120449 }while( vu!=0 );
120450 q[-1] &= 0x7f; /* turn off high bit in final byte */
120451 assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
120452 return (int) (q - (unsigned char *)p);
120456 ** Read a 64-bit variable-length integer from memory starting at p[0].
120457 ** Return the number of bytes read, or 0 on error.
120458 ** The value is stored in *v.
120460 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
120461 const unsigned char *q = (const unsigned char *) p;
120462 sqlite_uint64 x = 0, y = 1;
120463 while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
120464 x += y * (*q++ & 0x7f);
120465 y <<= 7;
120467 x += y * (*q++);
120468 *v = (sqlite_int64) x;
120469 return (int) (q - (unsigned char *)p);
120473 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
120474 ** 32-bit integer before it is returned.
120476 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
120477 sqlite_int64 i;
120478 int ret = sqlite3Fts3GetVarint(p, &i);
120479 *pi = (int) i;
120480 return ret;
120484 ** Return the number of bytes required to encode v as a varint
120486 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
120487 int i = 0;
120490 v >>= 7;
120491 }while( v!=0 );
120492 return i;
120496 ** Convert an SQL-style quoted string into a normal string by removing
120497 ** the quote characters. The conversion is done in-place. If the
120498 ** input does not begin with a quote character, then this routine
120499 ** is a no-op.
120501 ** Examples:
120503 ** "abc" becomes abc
120504 ** 'xyz' becomes xyz
120505 ** [pqr] becomes pqr
120506 ** `mno` becomes mno
120509 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
120510 char quote; /* Quote character (if any ) */
120512 quote = z[0];
120513 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
120514 int iIn = 1; /* Index of next byte to read from input */
120515 int iOut = 0; /* Index of next byte to write to output */
120517 /* If the first byte was a '[', then the close-quote character is a ']' */
120518 if( quote=='[' ) quote = ']';
120520 while( ALWAYS(z[iIn]) ){
120521 if( z[iIn]==quote ){
120522 if( z[iIn+1]!=quote ) break;
120523 z[iOut++] = quote;
120524 iIn += 2;
120525 }else{
120526 z[iOut++] = z[iIn++];
120529 z[iOut] = '\0';
120534 ** Read a single varint from the doclist at *pp and advance *pp to point
120535 ** to the first byte past the end of the varint. Add the value of the varint
120536 ** to *pVal.
120538 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
120539 sqlite3_int64 iVal;
120540 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
120541 *pVal += iVal;
120545 ** When this function is called, *pp points to the first byte following a
120546 ** varint that is part of a doclist (or position-list, or any other list
120547 ** of varints). This function moves *pp to point to the start of that varint,
120548 ** and sets *pVal by the varint value.
120550 ** Argument pStart points to the first byte of the doclist that the
120551 ** varint is part of.
120553 static void fts3GetReverseVarint(
120554 char **pp,
120555 char *pStart,
120556 sqlite3_int64 *pVal
120558 sqlite3_int64 iVal;
120559 char *p;
120561 /* Pointer p now points at the first byte past the varint we are
120562 ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
120563 ** clear on character p[-1]. */
120564 for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
120566 *pp = p;
120568 sqlite3Fts3GetVarint(p, &iVal);
120569 *pVal = iVal;
120573 ** The xDisconnect() virtual table method.
120575 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
120576 Fts3Table *p = (Fts3Table *)pVtab;
120577 int i;
120579 assert( p->nPendingData==0 );
120580 assert( p->pSegments==0 );
120582 /* Free any prepared statements held */
120583 for(i=0; i<SizeofArray(p->aStmt); i++){
120584 sqlite3_finalize(p->aStmt[i]);
120586 sqlite3_free(p->zSegmentsTbl);
120587 sqlite3_free(p->zReadExprlist);
120588 sqlite3_free(p->zWriteExprlist);
120589 sqlite3_free(p->zContentTbl);
120590 sqlite3_free(p->zLanguageid);
120592 /* Invoke the tokenizer destructor to free the tokenizer. */
120593 p->pTokenizer->pModule->xDestroy(p->pTokenizer);
120595 sqlite3_free(p);
120596 return SQLITE_OK;
120600 ** Construct one or more SQL statements from the format string given
120601 ** and then evaluate those statements. The success code is written
120602 ** into *pRc.
120604 ** If *pRc is initially non-zero then this routine is a no-op.
120606 static void fts3DbExec(
120607 int *pRc, /* Success code */
120608 sqlite3 *db, /* Database in which to run SQL */
120609 const char *zFormat, /* Format string for SQL */
120610 ... /* Arguments to the format string */
120612 va_list ap;
120613 char *zSql;
120614 if( *pRc ) return;
120615 va_start(ap, zFormat);
120616 zSql = sqlite3_vmprintf(zFormat, ap);
120617 va_end(ap);
120618 if( zSql==0 ){
120619 *pRc = SQLITE_NOMEM;
120620 }else{
120621 *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
120622 sqlite3_free(zSql);
120627 ** The xDestroy() virtual table method.
120629 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
120630 Fts3Table *p = (Fts3Table *)pVtab;
120631 int rc = SQLITE_OK; /* Return code */
120632 const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
120633 sqlite3 *db = p->db; /* Database handle */
120635 /* Drop the shadow tables */
120636 if( p->zContentTbl==0 ){
120637 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
120639 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
120640 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
120641 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
120642 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
120644 /* If everything has worked, invoke fts3DisconnectMethod() to free the
120645 ** memory associated with the Fts3Table structure and return SQLITE_OK.
120646 ** Otherwise, return an SQLite error code.
120648 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
120653 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
120654 ** passed as the first argument. This is done as part of the xConnect()
120655 ** and xCreate() methods.
120657 ** If *pRc is non-zero when this function is called, it is a no-op.
120658 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
120659 ** before returning.
120661 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
120662 if( *pRc==SQLITE_OK ){
120663 int i; /* Iterator variable */
120664 int rc; /* Return code */
120665 char *zSql; /* SQL statement passed to declare_vtab() */
120666 char *zCols; /* List of user defined columns */
120667 const char *zLanguageid;
120669 zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
120670 sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
120672 /* Create a list of user columns for the virtual table */
120673 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
120674 for(i=1; zCols && i<p->nColumn; i++){
120675 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
120678 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
120679 zSql = sqlite3_mprintf(
120680 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
120681 zCols, p->zName, zLanguageid
120683 if( !zCols || !zSql ){
120684 rc = SQLITE_NOMEM;
120685 }else{
120686 rc = sqlite3_declare_vtab(p->db, zSql);
120689 sqlite3_free(zSql);
120690 sqlite3_free(zCols);
120691 *pRc = rc;
120696 ** Create the %_stat table if it does not already exist.
120698 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
120699 fts3DbExec(pRc, p->db,
120700 "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
120701 "(id INTEGER PRIMARY KEY, value BLOB);",
120702 p->zDb, p->zName
120704 if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
120708 ** Create the backing store tables (%_content, %_segments and %_segdir)
120709 ** required by the FTS3 table passed as the only argument. This is done
120710 ** as part of the vtab xCreate() method.
120712 ** If the p->bHasDocsize boolean is true (indicating that this is an
120713 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
120714 ** %_stat tables required by FTS4.
120716 static int fts3CreateTables(Fts3Table *p){
120717 int rc = SQLITE_OK; /* Return code */
120718 int i; /* Iterator variable */
120719 sqlite3 *db = p->db; /* The database connection */
120721 if( p->zContentTbl==0 ){
120722 const char *zLanguageid = p->zLanguageid;
120723 char *zContentCols; /* Columns of %_content table */
120725 /* Create a list of user columns for the content table */
120726 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
120727 for(i=0; zContentCols && i<p->nColumn; i++){
120728 char *z = p->azColumn[i];
120729 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
120731 if( zLanguageid && zContentCols ){
120732 zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
120734 if( zContentCols==0 ) rc = SQLITE_NOMEM;
120736 /* Create the content table */
120737 fts3DbExec(&rc, db,
120738 "CREATE TABLE %Q.'%q_content'(%s)",
120739 p->zDb, p->zName, zContentCols
120741 sqlite3_free(zContentCols);
120744 /* Create other tables */
120745 fts3DbExec(&rc, db,
120746 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
120747 p->zDb, p->zName
120749 fts3DbExec(&rc, db,
120750 "CREATE TABLE %Q.'%q_segdir'("
120751 "level INTEGER,"
120752 "idx INTEGER,"
120753 "start_block INTEGER,"
120754 "leaves_end_block INTEGER,"
120755 "end_block INTEGER,"
120756 "root BLOB,"
120757 "PRIMARY KEY(level, idx)"
120758 ");",
120759 p->zDb, p->zName
120761 if( p->bHasDocsize ){
120762 fts3DbExec(&rc, db,
120763 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
120764 p->zDb, p->zName
120767 assert( p->bHasStat==p->bFts4 );
120768 if( p->bHasStat ){
120769 sqlite3Fts3CreateStatTable(&rc, p);
120771 return rc;
120775 ** Store the current database page-size in bytes in p->nPgsz.
120777 ** If *pRc is non-zero when this function is called, it is a no-op.
120778 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
120779 ** before returning.
120781 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
120782 if( *pRc==SQLITE_OK ){
120783 int rc; /* Return code */
120784 char *zSql; /* SQL text "PRAGMA %Q.page_size" */
120785 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
120787 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
120788 if( !zSql ){
120789 rc = SQLITE_NOMEM;
120790 }else{
120791 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
120792 if( rc==SQLITE_OK ){
120793 sqlite3_step(pStmt);
120794 p->nPgsz = sqlite3_column_int(pStmt, 0);
120795 rc = sqlite3_finalize(pStmt);
120796 }else if( rc==SQLITE_AUTH ){
120797 p->nPgsz = 1024;
120798 rc = SQLITE_OK;
120801 assert( p->nPgsz>0 || rc!=SQLITE_OK );
120802 sqlite3_free(zSql);
120803 *pRc = rc;
120808 ** "Special" FTS4 arguments are column specifications of the following form:
120810 ** <key> = <value>
120812 ** There may not be whitespace surrounding the "=" character. The <value>
120813 ** term may be quoted, but the <key> may not.
120815 static int fts3IsSpecialColumn(
120816 const char *z,
120817 int *pnKey,
120818 char **pzValue
120820 char *zValue;
120821 const char *zCsr = z;
120823 while( *zCsr!='=' ){
120824 if( *zCsr=='\0' ) return 0;
120825 zCsr++;
120828 *pnKey = (int)(zCsr-z);
120829 zValue = sqlite3_mprintf("%s", &zCsr[1]);
120830 if( zValue ){
120831 sqlite3Fts3Dequote(zValue);
120833 *pzValue = zValue;
120834 return 1;
120838 ** Append the output of a printf() style formatting to an existing string.
120840 static void fts3Appendf(
120841 int *pRc, /* IN/OUT: Error code */
120842 char **pz, /* IN/OUT: Pointer to string buffer */
120843 const char *zFormat, /* Printf format string to append */
120844 ... /* Arguments for printf format string */
120846 if( *pRc==SQLITE_OK ){
120847 va_list ap;
120848 char *z;
120849 va_start(ap, zFormat);
120850 z = sqlite3_vmprintf(zFormat, ap);
120851 va_end(ap);
120852 if( z && *pz ){
120853 char *z2 = sqlite3_mprintf("%s%s", *pz, z);
120854 sqlite3_free(z);
120855 z = z2;
120857 if( z==0 ) *pRc = SQLITE_NOMEM;
120858 sqlite3_free(*pz);
120859 *pz = z;
120864 ** Return a copy of input string zInput enclosed in double-quotes (") and
120865 ** with all double quote characters escaped. For example:
120867 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
120869 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
120870 ** is the callers responsibility to call sqlite3_free() to release this
120871 ** memory.
120873 static char *fts3QuoteId(char const *zInput){
120874 int nRet;
120875 char *zRet;
120876 nRet = 2 + (int)strlen(zInput)*2 + 1;
120877 zRet = sqlite3_malloc(nRet);
120878 if( zRet ){
120879 int i;
120880 char *z = zRet;
120881 *(z++) = '"';
120882 for(i=0; zInput[i]; i++){
120883 if( zInput[i]=='"' ) *(z++) = '"';
120884 *(z++) = zInput[i];
120886 *(z++) = '"';
120887 *(z++) = '\0';
120889 return zRet;
120893 ** Return a list of comma separated SQL expressions and a FROM clause that
120894 ** could be used in a SELECT statement such as the following:
120896 ** SELECT <list of expressions> FROM %_content AS x ...
120898 ** to return the docid, followed by each column of text data in order
120899 ** from left to write. If parameter zFunc is not NULL, then instead of
120900 ** being returned directly each column of text data is passed to an SQL
120901 ** function named zFunc first. For example, if zFunc is "unzip" and the
120902 ** table has the three user-defined columns "a", "b", and "c", the following
120903 ** string is returned:
120905 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
120907 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
120908 ** is the responsibility of the caller to eventually free it.
120910 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
120911 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
120912 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
120913 ** no error occurs, *pRc is left unmodified.
120915 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
120916 char *zRet = 0;
120917 char *zFree = 0;
120918 char *zFunction;
120919 int i;
120921 if( p->zContentTbl==0 ){
120922 if( !zFunc ){
120923 zFunction = "";
120924 }else{
120925 zFree = zFunction = fts3QuoteId(zFunc);
120927 fts3Appendf(pRc, &zRet, "docid");
120928 for(i=0; i<p->nColumn; i++){
120929 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
120931 if( p->zLanguageid ){
120932 fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
120934 sqlite3_free(zFree);
120935 }else{
120936 fts3Appendf(pRc, &zRet, "rowid");
120937 for(i=0; i<p->nColumn; i++){
120938 fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
120940 if( p->zLanguageid ){
120941 fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
120944 fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
120945 p->zDb,
120946 (p->zContentTbl ? p->zContentTbl : p->zName),
120947 (p->zContentTbl ? "" : "_content")
120949 return zRet;
120953 ** Return a list of N comma separated question marks, where N is the number
120954 ** of columns in the %_content table (one for the docid plus one for each
120955 ** user-defined text column).
120957 ** If argument zFunc is not NULL, then all but the first question mark
120958 ** is preceded by zFunc and an open bracket, and followed by a closed
120959 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
120960 ** user-defined text columns, the following string is returned:
120962 ** "?, zip(?), zip(?), zip(?)"
120964 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
120965 ** is the responsibility of the caller to eventually free it.
120967 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
120968 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
120969 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
120970 ** no error occurs, *pRc is left unmodified.
120972 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
120973 char *zRet = 0;
120974 char *zFree = 0;
120975 char *zFunction;
120976 int i;
120978 if( !zFunc ){
120979 zFunction = "";
120980 }else{
120981 zFree = zFunction = fts3QuoteId(zFunc);
120983 fts3Appendf(pRc, &zRet, "?");
120984 for(i=0; i<p->nColumn; i++){
120985 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
120987 if( p->zLanguageid ){
120988 fts3Appendf(pRc, &zRet, ", ?");
120990 sqlite3_free(zFree);
120991 return zRet;
120995 ** This function interprets the string at (*pp) as a non-negative integer
120996 ** value. It reads the integer and sets *pnOut to the value read, then
120997 ** sets *pp to point to the byte immediately following the last byte of
120998 ** the integer value.
121000 ** Only decimal digits ('0'..'9') may be part of an integer value.
121002 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
121003 ** the output value undefined. Otherwise SQLITE_OK is returned.
121005 ** This function is used when parsing the "prefix=" FTS4 parameter.
121007 static int fts3GobbleInt(const char **pp, int *pnOut){
121008 const char *p; /* Iterator pointer */
121009 int nInt = 0; /* Output value */
121011 for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
121012 nInt = nInt * 10 + (p[0] - '0');
121014 if( p==*pp ) return SQLITE_ERROR;
121015 *pnOut = nInt;
121016 *pp = p;
121017 return SQLITE_OK;
121021 ** This function is called to allocate an array of Fts3Index structures
121022 ** representing the indexes maintained by the current FTS table. FTS tables
121023 ** always maintain the main "terms" index, but may also maintain one or
121024 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
121025 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
121027 ** Argument zParam is passed the value of the "prefix=" option if one was
121028 ** specified, or NULL otherwise.
121030 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
121031 ** the allocated array. *pnIndex is set to the number of elements in the
121032 ** array. If an error does occur, an SQLite error code is returned.
121034 ** Regardless of whether or not an error is returned, it is the responsibility
121035 ** of the caller to call sqlite3_free() on the output array to free it.
121037 static int fts3PrefixParameter(
121038 const char *zParam, /* ABC in prefix=ABC parameter to parse */
121039 int *pnIndex, /* OUT: size of *apIndex[] array */
121040 struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
121042 struct Fts3Index *aIndex; /* Allocated array */
121043 int nIndex = 1; /* Number of entries in array */
121045 if( zParam && zParam[0] ){
121046 const char *p;
121047 nIndex++;
121048 for(p=zParam; *p; p++){
121049 if( *p==',' ) nIndex++;
121053 aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
121054 *apIndex = aIndex;
121055 *pnIndex = nIndex;
121056 if( !aIndex ){
121057 return SQLITE_NOMEM;
121060 memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
121061 if( zParam ){
121062 const char *p = zParam;
121063 int i;
121064 for(i=1; i<nIndex; i++){
121065 int nPrefix;
121066 if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
121067 aIndex[i].nPrefix = nPrefix;
121072 return SQLITE_OK;
121076 ** This function is called when initializing an FTS4 table that uses the
121077 ** content=xxx option. It determines the number of and names of the columns
121078 ** of the new FTS4 table.
121080 ** The third argument passed to this function is the value passed to the
121081 ** config=xxx option (i.e. "xxx"). This function queries the database for
121082 ** a table of that name. If found, the output variables are populated
121083 ** as follows:
121085 ** *pnCol: Set to the number of columns table xxx has,
121087 ** *pnStr: Set to the total amount of space required to store a copy
121088 ** of each columns name, including the nul-terminator.
121090 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
121091 ** the name of the corresponding column in table xxx. The array
121092 ** and its contents are allocated using a single allocation. It
121093 ** is the responsibility of the caller to free this allocation
121094 ** by eventually passing the *pazCol value to sqlite3_free().
121096 ** If the table cannot be found, an error code is returned and the output
121097 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
121098 ** returned (and the output variables are undefined).
121100 static int fts3ContentColumns(
121101 sqlite3 *db, /* Database handle */
121102 const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
121103 const char *zTbl, /* Name of content table */
121104 const char ***pazCol, /* OUT: Malloc'd array of column names */
121105 int *pnCol, /* OUT: Size of array *pazCol */
121106 int *pnStr /* OUT: Bytes of string content */
121108 int rc = SQLITE_OK; /* Return code */
121109 char *zSql; /* "SELECT *" statement on zTbl */
121110 sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
121112 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
121113 if( !zSql ){
121114 rc = SQLITE_NOMEM;
121115 }else{
121116 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
121118 sqlite3_free(zSql);
121120 if( rc==SQLITE_OK ){
121121 const char **azCol; /* Output array */
121122 int nStr = 0; /* Size of all column names (incl. 0x00) */
121123 int nCol; /* Number of table columns */
121124 int i; /* Used to iterate through columns */
121126 /* Loop through the returned columns. Set nStr to the number of bytes of
121127 ** space required to store a copy of each column name, including the
121128 ** nul-terminator byte. */
121129 nCol = sqlite3_column_count(pStmt);
121130 for(i=0; i<nCol; i++){
121131 const char *zCol = sqlite3_column_name(pStmt, i);
121132 nStr += (int)strlen(zCol) + 1;
121135 /* Allocate and populate the array to return. */
121136 azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
121137 if( azCol==0 ){
121138 rc = SQLITE_NOMEM;
121139 }else{
121140 char *p = (char *)&azCol[nCol];
121141 for(i=0; i<nCol; i++){
121142 const char *zCol = sqlite3_column_name(pStmt, i);
121143 int n = (int)strlen(zCol)+1;
121144 memcpy(p, zCol, n);
121145 azCol[i] = p;
121146 p += n;
121149 sqlite3_finalize(pStmt);
121151 /* Set the output variables. */
121152 *pnCol = nCol;
121153 *pnStr = nStr;
121154 *pazCol = azCol;
121157 return rc;
121161 ** This function is the implementation of both the xConnect and xCreate
121162 ** methods of the FTS3 virtual table.
121164 ** The argv[] array contains the following:
121166 ** argv[0] -> module name ("fts3" or "fts4")
121167 ** argv[1] -> database name
121168 ** argv[2] -> table name
121169 ** argv[...] -> "column name" and other module argument fields.
121171 static int fts3InitVtab(
121172 int isCreate, /* True for xCreate, false for xConnect */
121173 sqlite3 *db, /* The SQLite database connection */
121174 void *pAux, /* Hash table containing tokenizers */
121175 int argc, /* Number of elements in argv array */
121176 const char * const *argv, /* xCreate/xConnect argument array */
121177 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
121178 char **pzErr /* Write any error message here */
121180 Fts3Hash *pHash = (Fts3Hash *)pAux;
121181 Fts3Table *p = 0; /* Pointer to allocated vtab */
121182 int rc = SQLITE_OK; /* Return code */
121183 int i; /* Iterator variable */
121184 int nByte; /* Size of allocation used for *p */
121185 int iCol; /* Column index */
121186 int nString = 0; /* Bytes required to hold all column names */
121187 int nCol = 0; /* Number of columns in the FTS table */
121188 char *zCsr; /* Space for holding column names */
121189 int nDb; /* Bytes required to hold database name */
121190 int nName; /* Bytes required to hold table name */
121191 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
121192 const char **aCol; /* Array of column names */
121193 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
121195 int nIndex; /* Size of aIndex[] array */
121196 struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
121198 /* The results of parsing supported FTS4 key=value options: */
121199 int bNoDocsize = 0; /* True to omit %_docsize table */
121200 int bDescIdx = 0; /* True to store descending indexes */
121201 char *zPrefix = 0; /* Prefix parameter value (or NULL) */
121202 char *zCompress = 0; /* compress=? parameter (or NULL) */
121203 char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
121204 char *zContent = 0; /* content=? parameter (or NULL) */
121205 char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
121206 char **azNotindexed = 0; /* The set of notindexed= columns */
121207 int nNotindexed = 0; /* Size of azNotindexed[] array */
121209 assert( strlen(argv[0])==4 );
121210 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
121211 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
121214 nDb = (int)strlen(argv[1]) + 1;
121215 nName = (int)strlen(argv[2]) + 1;
121217 nByte = sizeof(const char *) * (argc-2);
121218 aCol = (const char **)sqlite3_malloc(nByte);
121219 if( aCol ){
121220 memset((void*)aCol, 0, nByte);
121221 azNotindexed = (char **)sqlite3_malloc(nByte);
121223 if( azNotindexed ){
121224 memset(azNotindexed, 0, nByte);
121226 if( !aCol || !azNotindexed ){
121227 rc = SQLITE_NOMEM;
121228 goto fts3_init_out;
121231 /* Loop through all of the arguments passed by the user to the FTS3/4
121232 ** module (i.e. all the column names and special arguments). This loop
121233 ** does the following:
121235 ** + Figures out the number of columns the FTSX table will have, and
121236 ** the number of bytes of space that must be allocated to store copies
121237 ** of the column names.
121239 ** + If there is a tokenizer specification included in the arguments,
121240 ** initializes the tokenizer pTokenizer.
121242 for(i=3; rc==SQLITE_OK && i<argc; i++){
121243 char const *z = argv[i];
121244 int nKey;
121245 char *zVal;
121247 /* Check if this is a tokenizer specification */
121248 if( !pTokenizer
121249 && strlen(z)>8
121250 && 0==sqlite3_strnicmp(z, "tokenize", 8)
121251 && 0==sqlite3Fts3IsIdChar(z[8])
121253 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
121256 /* Check if it is an FTS4 special argument. */
121257 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
121258 struct Fts4Option {
121259 const char *zOpt;
121260 int nOpt;
121261 } aFts4Opt[] = {
121262 { "matchinfo", 9 }, /* 0 -> MATCHINFO */
121263 { "prefix", 6 }, /* 1 -> PREFIX */
121264 { "compress", 8 }, /* 2 -> COMPRESS */
121265 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
121266 { "order", 5 }, /* 4 -> ORDER */
121267 { "content", 7 }, /* 5 -> CONTENT */
121268 { "languageid", 10 }, /* 6 -> LANGUAGEID */
121269 { "notindexed", 10 } /* 7 -> NOTINDEXED */
121272 int iOpt;
121273 if( !zVal ){
121274 rc = SQLITE_NOMEM;
121275 }else{
121276 for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
121277 struct Fts4Option *pOp = &aFts4Opt[iOpt];
121278 if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
121279 break;
121282 if( iOpt==SizeofArray(aFts4Opt) ){
121283 *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
121284 rc = SQLITE_ERROR;
121285 }else{
121286 switch( iOpt ){
121287 case 0: /* MATCHINFO */
121288 if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
121289 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
121290 rc = SQLITE_ERROR;
121292 bNoDocsize = 1;
121293 break;
121295 case 1: /* PREFIX */
121296 sqlite3_free(zPrefix);
121297 zPrefix = zVal;
121298 zVal = 0;
121299 break;
121301 case 2: /* COMPRESS */
121302 sqlite3_free(zCompress);
121303 zCompress = zVal;
121304 zVal = 0;
121305 break;
121307 case 3: /* UNCOMPRESS */
121308 sqlite3_free(zUncompress);
121309 zUncompress = zVal;
121310 zVal = 0;
121311 break;
121313 case 4: /* ORDER */
121314 if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
121315 && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
121317 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
121318 rc = SQLITE_ERROR;
121320 bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
121321 break;
121323 case 5: /* CONTENT */
121324 sqlite3_free(zContent);
121325 zContent = zVal;
121326 zVal = 0;
121327 break;
121329 case 6: /* LANGUAGEID */
121330 assert( iOpt==6 );
121331 sqlite3_free(zLanguageid);
121332 zLanguageid = zVal;
121333 zVal = 0;
121334 break;
121336 case 7: /* NOTINDEXED */
121337 azNotindexed[nNotindexed++] = zVal;
121338 zVal = 0;
121339 break;
121342 sqlite3_free(zVal);
121346 /* Otherwise, the argument is a column name. */
121347 else {
121348 nString += (int)(strlen(z) + 1);
121349 aCol[nCol++] = z;
121353 /* If a content=xxx option was specified, the following:
121355 ** 1. Ignore any compress= and uncompress= options.
121357 ** 2. If no column names were specified as part of the CREATE VIRTUAL
121358 ** TABLE statement, use all columns from the content table.
121360 if( rc==SQLITE_OK && zContent ){
121361 sqlite3_free(zCompress);
121362 sqlite3_free(zUncompress);
121363 zCompress = 0;
121364 zUncompress = 0;
121365 if( nCol==0 ){
121366 sqlite3_free((void*)aCol);
121367 aCol = 0;
121368 rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
121370 /* If a languageid= option was specified, remove the language id
121371 ** column from the aCol[] array. */
121372 if( rc==SQLITE_OK && zLanguageid ){
121373 int j;
121374 for(j=0; j<nCol; j++){
121375 if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
121376 int k;
121377 for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
121378 nCol--;
121379 break;
121385 if( rc!=SQLITE_OK ) goto fts3_init_out;
121387 if( nCol==0 ){
121388 assert( nString==0 );
121389 aCol[0] = "content";
121390 nString = 8;
121391 nCol = 1;
121394 if( pTokenizer==0 ){
121395 rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
121396 if( rc!=SQLITE_OK ) goto fts3_init_out;
121398 assert( pTokenizer );
121400 rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
121401 if( rc==SQLITE_ERROR ){
121402 assert( zPrefix );
121403 *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
121405 if( rc!=SQLITE_OK ) goto fts3_init_out;
121407 /* Allocate and populate the Fts3Table structure. */
121408 nByte = sizeof(Fts3Table) + /* Fts3Table */
121409 nCol * sizeof(char *) + /* azColumn */
121410 nIndex * sizeof(struct Fts3Index) + /* aIndex */
121411 nCol * sizeof(u8) + /* abNotindexed */
121412 nName + /* zName */
121413 nDb + /* zDb */
121414 nString; /* Space for azColumn strings */
121415 p = (Fts3Table*)sqlite3_malloc(nByte);
121416 if( p==0 ){
121417 rc = SQLITE_NOMEM;
121418 goto fts3_init_out;
121420 memset(p, 0, nByte);
121421 p->db = db;
121422 p->nColumn = nCol;
121423 p->nPendingData = 0;
121424 p->azColumn = (char **)&p[1];
121425 p->pTokenizer = pTokenizer;
121426 p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
121427 p->bHasDocsize = (isFts4 && bNoDocsize==0);
121428 p->bHasStat = isFts4;
121429 p->bFts4 = isFts4;
121430 p->bDescIdx = bDescIdx;
121431 p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */
121432 p->zContentTbl = zContent;
121433 p->zLanguageid = zLanguageid;
121434 zContent = 0;
121435 zLanguageid = 0;
121436 TESTONLY( p->inTransaction = -1 );
121437 TESTONLY( p->mxSavepoint = -1 );
121439 p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
121440 memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
121441 p->nIndex = nIndex;
121442 for(i=0; i<nIndex; i++){
121443 fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
121445 p->abNotindexed = (u8 *)&p->aIndex[nIndex];
121447 /* Fill in the zName and zDb fields of the vtab structure. */
121448 zCsr = (char *)&p->abNotindexed[nCol];
121449 p->zName = zCsr;
121450 memcpy(zCsr, argv[2], nName);
121451 zCsr += nName;
121452 p->zDb = zCsr;
121453 memcpy(zCsr, argv[1], nDb);
121454 zCsr += nDb;
121456 /* Fill in the azColumn array */
121457 for(iCol=0; iCol<nCol; iCol++){
121458 char *z;
121459 int n = 0;
121460 z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
121461 memcpy(zCsr, z, n);
121462 zCsr[n] = '\0';
121463 sqlite3Fts3Dequote(zCsr);
121464 p->azColumn[iCol] = zCsr;
121465 zCsr += n+1;
121466 assert( zCsr <= &((char *)p)[nByte] );
121469 /* Fill in the abNotindexed array */
121470 for(iCol=0; iCol<nCol; iCol++){
121471 int n = (int)strlen(p->azColumn[iCol]);
121472 for(i=0; i<nNotindexed; i++){
121473 char *zNot = azNotindexed[i];
121474 if( zNot && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) ){
121475 p->abNotindexed[iCol] = 1;
121476 sqlite3_free(zNot);
121477 azNotindexed[i] = 0;
121481 for(i=0; i<nNotindexed; i++){
121482 if( azNotindexed[i] ){
121483 *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
121484 rc = SQLITE_ERROR;
121488 if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
121489 char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
121490 rc = SQLITE_ERROR;
121491 *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
121493 p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
121494 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
121495 if( rc!=SQLITE_OK ) goto fts3_init_out;
121497 /* If this is an xCreate call, create the underlying tables in the
121498 ** database. TODO: For xConnect(), it could verify that said tables exist.
121500 if( isCreate ){
121501 rc = fts3CreateTables(p);
121504 /* Check to see if a legacy fts3 table has been "upgraded" by the
121505 ** addition of a %_stat table so that it can use incremental merge.
121507 if( !isFts4 && !isCreate ){
121508 int rc2 = SQLITE_OK;
121509 fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
121510 p->zDb, p->zName);
121511 if( rc2==SQLITE_OK ) p->bHasStat = 1;
121514 /* Figure out the page-size for the database. This is required in order to
121515 ** estimate the cost of loading large doclists from the database. */
121516 fts3DatabasePageSize(&rc, p);
121517 p->nNodeSize = p->nPgsz-35;
121519 /* Declare the table schema to SQLite. */
121520 fts3DeclareVtab(&rc, p);
121522 fts3_init_out:
121523 sqlite3_free(zPrefix);
121524 sqlite3_free(aIndex);
121525 sqlite3_free(zCompress);
121526 sqlite3_free(zUncompress);
121527 sqlite3_free(zContent);
121528 sqlite3_free(zLanguageid);
121529 for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
121530 sqlite3_free((void *)aCol);
121531 sqlite3_free((void *)azNotindexed);
121532 if( rc!=SQLITE_OK ){
121533 if( p ){
121534 fts3DisconnectMethod((sqlite3_vtab *)p);
121535 }else if( pTokenizer ){
121536 pTokenizer->pModule->xDestroy(pTokenizer);
121538 }else{
121539 assert( p->pSegments==0 );
121540 *ppVTab = &p->base;
121542 return rc;
121546 ** The xConnect() and xCreate() methods for the virtual table. All the
121547 ** work is done in function fts3InitVtab().
121549 static int fts3ConnectMethod(
121550 sqlite3 *db, /* Database connection */
121551 void *pAux, /* Pointer to tokenizer hash table */
121552 int argc, /* Number of elements in argv array */
121553 const char * const *argv, /* xCreate/xConnect argument array */
121554 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
121555 char **pzErr /* OUT: sqlite3_malloc'd error message */
121557 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
121559 static int fts3CreateMethod(
121560 sqlite3 *db, /* Database connection */
121561 void *pAux, /* Pointer to tokenizer hash table */
121562 int argc, /* Number of elements in argv array */
121563 const char * const *argv, /* xCreate/xConnect argument array */
121564 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
121565 char **pzErr /* OUT: sqlite3_malloc'd error message */
121567 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
121571 ** Implementation of the xBestIndex method for FTS3 tables. There
121572 ** are three possible strategies, in order of preference:
121574 ** 1. Direct lookup by rowid or docid.
121575 ** 2. Full-text search using a MATCH operator on a non-docid column.
121576 ** 3. Linear scan of %_content table.
121578 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
121579 Fts3Table *p = (Fts3Table *)pVTab;
121580 int i; /* Iterator variable */
121581 int iCons = -1; /* Index of constraint to use */
121582 int iLangidCons = -1; /* Index of langid=x constraint, if present */
121584 /* By default use a full table scan. This is an expensive option,
121585 ** so search through the constraints to see if a more efficient
121586 ** strategy is possible.
121588 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
121589 pInfo->estimatedCost = 5000000;
121590 for(i=0; i<pInfo->nConstraint; i++){
121591 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
121592 if( pCons->usable==0 ) continue;
121594 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
121595 if( iCons<0
121596 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
121597 && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
121599 pInfo->idxNum = FTS3_DOCID_SEARCH;
121600 pInfo->estimatedCost = 1.0;
121601 iCons = i;
121604 /* A MATCH constraint. Use a full-text search.
121606 ** If there is more than one MATCH constraint available, use the first
121607 ** one encountered. If there is both a MATCH constraint and a direct
121608 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
121609 ** though the rowid/docid lookup is faster than a MATCH query, selecting
121610 ** it would lead to an "unable to use function MATCH in the requested
121611 ** context" error.
121613 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
121614 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
121616 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
121617 pInfo->estimatedCost = 2.0;
121618 iCons = i;
121621 /* Equality constraint on the langid column */
121622 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
121623 && pCons->iColumn==p->nColumn + 2
121625 iLangidCons = i;
121629 if( iCons>=0 ){
121630 pInfo->aConstraintUsage[iCons].argvIndex = 1;
121631 pInfo->aConstraintUsage[iCons].omit = 1;
121633 if( iLangidCons>=0 ){
121634 pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
121637 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
121638 ** docid) order. Both ascending and descending are possible.
121640 if( pInfo->nOrderBy==1 ){
121641 struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
121642 if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
121643 if( pOrder->desc ){
121644 pInfo->idxStr = "DESC";
121645 }else{
121646 pInfo->idxStr = "ASC";
121648 pInfo->orderByConsumed = 1;
121652 assert( p->pSegments==0 );
121653 return SQLITE_OK;
121657 ** Implementation of xOpen method.
121659 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
121660 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
121662 UNUSED_PARAMETER(pVTab);
121664 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
121665 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
121666 ** if the allocation fails, return SQLITE_NOMEM.
121668 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
121669 if( !pCsr ){
121670 return SQLITE_NOMEM;
121672 memset(pCsr, 0, sizeof(Fts3Cursor));
121673 return SQLITE_OK;
121677 ** Close the cursor. For additional information see the documentation
121678 ** on the xClose method of the virtual table interface.
121680 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
121681 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
121682 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
121683 sqlite3_finalize(pCsr->pStmt);
121684 sqlite3Fts3ExprFree(pCsr->pExpr);
121685 sqlite3Fts3FreeDeferredTokens(pCsr);
121686 sqlite3_free(pCsr->aDoclist);
121687 sqlite3_free(pCsr->aMatchinfo);
121688 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
121689 sqlite3_free(pCsr);
121690 return SQLITE_OK;
121694 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
121695 ** compose and prepare an SQL statement of the form:
121697 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
121699 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
121700 ** it. If an error occurs, return an SQLite error code.
121702 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
121704 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
121705 int rc = SQLITE_OK;
121706 if( pCsr->pStmt==0 ){
121707 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
121708 char *zSql;
121709 zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
121710 if( !zSql ) return SQLITE_NOMEM;
121711 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
121712 sqlite3_free(zSql);
121714 *ppStmt = pCsr->pStmt;
121715 return rc;
121719 ** Position the pCsr->pStmt statement so that it is on the row
121720 ** of the %_content table that contains the last match. Return
121721 ** SQLITE_OK on success.
121723 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
121724 int rc = SQLITE_OK;
121725 if( pCsr->isRequireSeek ){
121726 sqlite3_stmt *pStmt = 0;
121728 rc = fts3CursorSeekStmt(pCsr, &pStmt);
121729 if( rc==SQLITE_OK ){
121730 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
121731 pCsr->isRequireSeek = 0;
121732 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
121733 return SQLITE_OK;
121734 }else{
121735 rc = sqlite3_reset(pCsr->pStmt);
121736 if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
121737 /* If no row was found and no error has occurred, then the %_content
121738 ** table is missing a row that is present in the full-text index.
121739 ** The data structures are corrupt. */
121740 rc = FTS_CORRUPT_VTAB;
121741 pCsr->isEof = 1;
121747 if( rc!=SQLITE_OK && pContext ){
121748 sqlite3_result_error_code(pContext, rc);
121750 return rc;
121754 ** This function is used to process a single interior node when searching
121755 ** a b-tree for a term or term prefix. The node data is passed to this
121756 ** function via the zNode/nNode parameters. The term to search for is
121757 ** passed in zTerm/nTerm.
121759 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
121760 ** of the child node that heads the sub-tree that may contain the term.
121762 ** If piLast is not NULL, then *piLast is set to the right-most child node
121763 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
121764 ** a prefix.
121766 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
121768 static int fts3ScanInteriorNode(
121769 const char *zTerm, /* Term to select leaves for */
121770 int nTerm, /* Size of term zTerm in bytes */
121771 const char *zNode, /* Buffer containing segment interior node */
121772 int nNode, /* Size of buffer at zNode */
121773 sqlite3_int64 *piFirst, /* OUT: Selected child node */
121774 sqlite3_int64 *piLast /* OUT: Selected child node */
121776 int rc = SQLITE_OK; /* Return code */
121777 const char *zCsr = zNode; /* Cursor to iterate through node */
121778 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
121779 char *zBuffer = 0; /* Buffer to load terms into */
121780 int nAlloc = 0; /* Size of allocated buffer */
121781 int isFirstTerm = 1; /* True when processing first term on page */
121782 sqlite3_int64 iChild; /* Block id of child node to descend to */
121784 /* Skip over the 'height' varint that occurs at the start of every
121785 ** interior node. Then load the blockid of the left-child of the b-tree
121786 ** node into variable iChild.
121788 ** Even if the data structure on disk is corrupted, this (reading two
121789 ** varints from the buffer) does not risk an overread. If zNode is a
121790 ** root node, then the buffer comes from a SELECT statement. SQLite does
121791 ** not make this guarantee explicitly, but in practice there are always
121792 ** either more than 20 bytes of allocated space following the nNode bytes of
121793 ** contents, or two zero bytes. Or, if the node is read from the %_segments
121794 ** table, then there are always 20 bytes of zeroed padding following the
121795 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
121797 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
121798 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
121799 if( zCsr>zEnd ){
121800 return FTS_CORRUPT_VTAB;
121803 while( zCsr<zEnd && (piFirst || piLast) ){
121804 int cmp; /* memcmp() result */
121805 int nSuffix; /* Size of term suffix */
121806 int nPrefix = 0; /* Size of term prefix */
121807 int nBuffer; /* Total term size */
121809 /* Load the next term on the node into zBuffer. Use realloc() to expand
121810 ** the size of zBuffer if required. */
121811 if( !isFirstTerm ){
121812 zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
121814 isFirstTerm = 0;
121815 zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
121817 if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
121818 rc = FTS_CORRUPT_VTAB;
121819 goto finish_scan;
121821 if( nPrefix+nSuffix>nAlloc ){
121822 char *zNew;
121823 nAlloc = (nPrefix+nSuffix) * 2;
121824 zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
121825 if( !zNew ){
121826 rc = SQLITE_NOMEM;
121827 goto finish_scan;
121829 zBuffer = zNew;
121831 assert( zBuffer );
121832 memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
121833 nBuffer = nPrefix + nSuffix;
121834 zCsr += nSuffix;
121836 /* Compare the term we are searching for with the term just loaded from
121837 ** the interior node. If the specified term is greater than or equal
121838 ** to the term from the interior node, then all terms on the sub-tree
121839 ** headed by node iChild are smaller than zTerm. No need to search
121840 ** iChild.
121842 ** If the interior node term is larger than the specified term, then
121843 ** the tree headed by iChild may contain the specified term.
121845 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
121846 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
121847 *piFirst = iChild;
121848 piFirst = 0;
121851 if( piLast && cmp<0 ){
121852 *piLast = iChild;
121853 piLast = 0;
121856 iChild++;
121859 if( piFirst ) *piFirst = iChild;
121860 if( piLast ) *piLast = iChild;
121862 finish_scan:
121863 sqlite3_free(zBuffer);
121864 return rc;
121869 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
121870 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
121871 ** contains a term. This function searches the sub-tree headed by the zNode
121872 ** node for the range of leaf nodes that may contain the specified term
121873 ** or terms for which the specified term is a prefix.
121875 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
121876 ** left-most leaf node in the tree that may contain the specified term.
121877 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
121878 ** right-most leaf node that may contain a term for which the specified
121879 ** term is a prefix.
121881 ** It is possible that the range of returned leaf nodes does not contain
121882 ** the specified term or any terms for which it is a prefix. However, if the
121883 ** segment does contain any such terms, they are stored within the identified
121884 ** range. Because this function only inspects interior segment nodes (and
121885 ** never loads leaf nodes into memory), it is not possible to be sure.
121887 ** If an error occurs, an error code other than SQLITE_OK is returned.
121889 static int fts3SelectLeaf(
121890 Fts3Table *p, /* Virtual table handle */
121891 const char *zTerm, /* Term to select leaves for */
121892 int nTerm, /* Size of term zTerm in bytes */
121893 const char *zNode, /* Buffer containing segment interior node */
121894 int nNode, /* Size of buffer at zNode */
121895 sqlite3_int64 *piLeaf, /* Selected leaf node */
121896 sqlite3_int64 *piLeaf2 /* Selected leaf node */
121898 int rc; /* Return code */
121899 int iHeight; /* Height of this node in tree */
121901 assert( piLeaf || piLeaf2 );
121903 sqlite3Fts3GetVarint32(zNode, &iHeight);
121904 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
121905 assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
121907 if( rc==SQLITE_OK && iHeight>1 ){
121908 char *zBlob = 0; /* Blob read from %_segments table */
121909 int nBlob; /* Size of zBlob in bytes */
121911 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
121912 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
121913 if( rc==SQLITE_OK ){
121914 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
121916 sqlite3_free(zBlob);
121917 piLeaf = 0;
121918 zBlob = 0;
121921 if( rc==SQLITE_OK ){
121922 rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
121924 if( rc==SQLITE_OK ){
121925 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
121927 sqlite3_free(zBlob);
121930 return rc;
121934 ** This function is used to create delta-encoded serialized lists of FTS3
121935 ** varints. Each call to this function appends a single varint to a list.
121937 static void fts3PutDeltaVarint(
121938 char **pp, /* IN/OUT: Output pointer */
121939 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
121940 sqlite3_int64 iVal /* Write this value to the list */
121942 assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
121943 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
121944 *piPrev = iVal;
121948 ** When this function is called, *ppPoslist is assumed to point to the
121949 ** start of a position-list. After it returns, *ppPoslist points to the
121950 ** first byte after the position-list.
121952 ** A position list is list of positions (delta encoded) and columns for
121953 ** a single document record of a doclist. So, in other words, this
121954 ** routine advances *ppPoslist so that it points to the next docid in
121955 ** the doclist, or to the first byte past the end of the doclist.
121957 ** If pp is not NULL, then the contents of the position list are copied
121958 ** to *pp. *pp is set to point to the first byte past the last byte copied
121959 ** before this function returns.
121961 static void fts3PoslistCopy(char **pp, char **ppPoslist){
121962 char *pEnd = *ppPoslist;
121963 char c = 0;
121965 /* The end of a position list is marked by a zero encoded as an FTS3
121966 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
121967 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
121968 ** of some other, multi-byte, value.
121970 ** The following while-loop moves pEnd to point to the first byte that is not
121971 ** immediately preceded by a byte with the 0x80 bit set. Then increments
121972 ** pEnd once more so that it points to the byte immediately following the
121973 ** last byte in the position-list.
121975 while( *pEnd | c ){
121976 c = *pEnd++ & 0x80;
121977 testcase( c!=0 && (*pEnd)==0 );
121979 pEnd++; /* Advance past the POS_END terminator byte */
121981 if( pp ){
121982 int n = (int)(pEnd - *ppPoslist);
121983 char *p = *pp;
121984 memcpy(p, *ppPoslist, n);
121985 p += n;
121986 *pp = p;
121988 *ppPoslist = pEnd;
121992 ** When this function is called, *ppPoslist is assumed to point to the
121993 ** start of a column-list. After it returns, *ppPoslist points to the
121994 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
121996 ** A column-list is list of delta-encoded positions for a single column
121997 ** within a single document within a doclist.
121999 ** The column-list is terminated either by a POS_COLUMN varint (1) or
122000 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
122001 ** the POS_COLUMN or POS_END that terminates the column-list.
122003 ** If pp is not NULL, then the contents of the column-list are copied
122004 ** to *pp. *pp is set to point to the first byte past the last byte copied
122005 ** before this function returns. The POS_COLUMN or POS_END terminator
122006 ** is not copied into *pp.
122008 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
122009 char *pEnd = *ppPoslist;
122010 char c = 0;
122012 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
122013 ** not part of a multi-byte varint.
122015 while( 0xFE & (*pEnd | c) ){
122016 c = *pEnd++ & 0x80;
122017 testcase( c!=0 && ((*pEnd)&0xfe)==0 );
122019 if( pp ){
122020 int n = (int)(pEnd - *ppPoslist);
122021 char *p = *pp;
122022 memcpy(p, *ppPoslist, n);
122023 p += n;
122024 *pp = p;
122026 *ppPoslist = pEnd;
122030 ** Value used to signify the end of an position-list. This is safe because
122031 ** it is not possible to have a document with 2^31 terms.
122033 #define POSITION_LIST_END 0x7fffffff
122036 ** This function is used to help parse position-lists. When this function is
122037 ** called, *pp may point to the start of the next varint in the position-list
122038 ** being parsed, or it may point to 1 byte past the end of the position-list
122039 ** (in which case **pp will be a terminator bytes POS_END (0) or
122040 ** (1)).
122042 ** If *pp points past the end of the current position-list, set *pi to
122043 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
122044 ** increment the current value of *pi by the value read, and set *pp to
122045 ** point to the next value before returning.
122047 ** Before calling this routine *pi must be initialized to the value of
122048 ** the previous position, or zero if we are reading the first position
122049 ** in the position-list. Because positions are delta-encoded, the value
122050 ** of the previous position is needed in order to compute the value of
122051 ** the next position.
122053 static void fts3ReadNextPos(
122054 char **pp, /* IN/OUT: Pointer into position-list buffer */
122055 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
122057 if( (**pp)&0xFE ){
122058 fts3GetDeltaVarint(pp, pi);
122059 *pi -= 2;
122060 }else{
122061 *pi = POSITION_LIST_END;
122066 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
122067 ** the value of iCol encoded as a varint to *pp. This will start a new
122068 ** column list.
122070 ** Set *pp to point to the byte just after the last byte written before
122071 ** returning (do not modify it if iCol==0). Return the total number of bytes
122072 ** written (0 if iCol==0).
122074 static int fts3PutColNumber(char **pp, int iCol){
122075 int n = 0; /* Number of bytes written */
122076 if( iCol ){
122077 char *p = *pp; /* Output pointer */
122078 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
122079 *p = 0x01;
122080 *pp = &p[n];
122082 return n;
122086 ** Compute the union of two position lists. The output written
122087 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
122088 ** order and with any duplicates removed. All pointers are
122089 ** updated appropriately. The caller is responsible for insuring
122090 ** that there is enough space in *pp to hold the complete output.
122092 static void fts3PoslistMerge(
122093 char **pp, /* Output buffer */
122094 char **pp1, /* Left input list */
122095 char **pp2 /* Right input list */
122097 char *p = *pp;
122098 char *p1 = *pp1;
122099 char *p2 = *pp2;
122101 while( *p1 || *p2 ){
122102 int iCol1; /* The current column index in pp1 */
122103 int iCol2; /* The current column index in pp2 */
122105 if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
122106 else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
122107 else iCol1 = 0;
122109 if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
122110 else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
122111 else iCol2 = 0;
122113 if( iCol1==iCol2 ){
122114 sqlite3_int64 i1 = 0; /* Last position from pp1 */
122115 sqlite3_int64 i2 = 0; /* Last position from pp2 */
122116 sqlite3_int64 iPrev = 0;
122117 int n = fts3PutColNumber(&p, iCol1);
122118 p1 += n;
122119 p2 += n;
122121 /* At this point, both p1 and p2 point to the start of column-lists
122122 ** for the same column (the column with index iCol1 and iCol2).
122123 ** A column-list is a list of non-negative delta-encoded varints, each
122124 ** incremented by 2 before being stored. Each list is terminated by a
122125 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
122126 ** and writes the results to buffer p. p is left pointing to the byte
122127 ** after the list written. No terminator (POS_END or POS_COLUMN) is
122128 ** written to the output.
122130 fts3GetDeltaVarint(&p1, &i1);
122131 fts3GetDeltaVarint(&p2, &i2);
122133 fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
122134 iPrev -= 2;
122135 if( i1==i2 ){
122136 fts3ReadNextPos(&p1, &i1);
122137 fts3ReadNextPos(&p2, &i2);
122138 }else if( i1<i2 ){
122139 fts3ReadNextPos(&p1, &i1);
122140 }else{
122141 fts3ReadNextPos(&p2, &i2);
122143 }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
122144 }else if( iCol1<iCol2 ){
122145 p1 += fts3PutColNumber(&p, iCol1);
122146 fts3ColumnlistCopy(&p, &p1);
122147 }else{
122148 p2 += fts3PutColNumber(&p, iCol2);
122149 fts3ColumnlistCopy(&p, &p2);
122153 *p++ = POS_END;
122154 *pp = p;
122155 *pp1 = p1 + 1;
122156 *pp2 = p2 + 1;
122160 ** This function is used to merge two position lists into one. When it is
122161 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
122162 ** the part of a doclist that follows each document id. For example, if a row
122163 ** contains:
122165 ** 'a b c'|'x y z'|'a b b a'
122167 ** Then the position list for this row for token 'b' would consist of:
122169 ** 0x02 0x01 0x02 0x03 0x03 0x00
122171 ** When this function returns, both *pp1 and *pp2 are left pointing to the
122172 ** byte following the 0x00 terminator of their respective position lists.
122174 ** If isSaveLeft is 0, an entry is added to the output position list for
122175 ** each position in *pp2 for which there exists one or more positions in
122176 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
122177 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
122178 ** slots before it.
122180 ** e.g. nToken==1 searches for adjacent positions.
122182 static int fts3PoslistPhraseMerge(
122183 char **pp, /* IN/OUT: Preallocated output buffer */
122184 int nToken, /* Maximum difference in token positions */
122185 int isSaveLeft, /* Save the left position */
122186 int isExact, /* If *pp1 is exactly nTokens before *pp2 */
122187 char **pp1, /* IN/OUT: Left input list */
122188 char **pp2 /* IN/OUT: Right input list */
122190 char *p = *pp;
122191 char *p1 = *pp1;
122192 char *p2 = *pp2;
122193 int iCol1 = 0;
122194 int iCol2 = 0;
122196 /* Never set both isSaveLeft and isExact for the same invocation. */
122197 assert( isSaveLeft==0 || isExact==0 );
122199 assert( p!=0 && *p1!=0 && *p2!=0 );
122200 if( *p1==POS_COLUMN ){
122201 p1++;
122202 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
122204 if( *p2==POS_COLUMN ){
122205 p2++;
122206 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
122209 while( 1 ){
122210 if( iCol1==iCol2 ){
122211 char *pSave = p;
122212 sqlite3_int64 iPrev = 0;
122213 sqlite3_int64 iPos1 = 0;
122214 sqlite3_int64 iPos2 = 0;
122216 if( iCol1 ){
122217 *p++ = POS_COLUMN;
122218 p += sqlite3Fts3PutVarint(p, iCol1);
122221 assert( *p1!=POS_END && *p1!=POS_COLUMN );
122222 assert( *p2!=POS_END && *p2!=POS_COLUMN );
122223 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
122224 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
122226 while( 1 ){
122227 if( iPos2==iPos1+nToken
122228 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
122230 sqlite3_int64 iSave;
122231 iSave = isSaveLeft ? iPos1 : iPos2;
122232 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
122233 pSave = 0;
122234 assert( p );
122236 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
122237 if( (*p2&0xFE)==0 ) break;
122238 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
122239 }else{
122240 if( (*p1&0xFE)==0 ) break;
122241 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
122245 if( pSave ){
122246 assert( pp && p );
122247 p = pSave;
122250 fts3ColumnlistCopy(0, &p1);
122251 fts3ColumnlistCopy(0, &p2);
122252 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
122253 if( 0==*p1 || 0==*p2 ) break;
122255 p1++;
122256 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
122257 p2++;
122258 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
122261 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
122262 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
122263 ** end of the position list, or the 0x01 that precedes the next
122264 ** column-number in the position list.
122266 else if( iCol1<iCol2 ){
122267 fts3ColumnlistCopy(0, &p1);
122268 if( 0==*p1 ) break;
122269 p1++;
122270 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
122271 }else{
122272 fts3ColumnlistCopy(0, &p2);
122273 if( 0==*p2 ) break;
122274 p2++;
122275 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
122279 fts3PoslistCopy(0, &p2);
122280 fts3PoslistCopy(0, &p1);
122281 *pp1 = p1;
122282 *pp2 = p2;
122283 if( *pp==p ){
122284 return 0;
122286 *p++ = 0x00;
122287 *pp = p;
122288 return 1;
122292 ** Merge two position-lists as required by the NEAR operator. The argument
122293 ** position lists correspond to the left and right phrases of an expression
122294 ** like:
122296 ** "phrase 1" NEAR "phrase number 2"
122298 ** Position list *pp1 corresponds to the left-hand side of the NEAR
122299 ** expression and *pp2 to the right. As usual, the indexes in the position
122300 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
122301 ** in the example above).
122303 ** The output position list - written to *pp - is a copy of *pp2 with those
122304 ** entries that are not sufficiently NEAR entries in *pp1 removed.
122306 static int fts3PoslistNearMerge(
122307 char **pp, /* Output buffer */
122308 char *aTmp, /* Temporary buffer space */
122309 int nRight, /* Maximum difference in token positions */
122310 int nLeft, /* Maximum difference in token positions */
122311 char **pp1, /* IN/OUT: Left input list */
122312 char **pp2 /* IN/OUT: Right input list */
122314 char *p1 = *pp1;
122315 char *p2 = *pp2;
122317 char *pTmp1 = aTmp;
122318 char *pTmp2;
122319 char *aTmp2;
122320 int res = 1;
122322 fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
122323 aTmp2 = pTmp2 = pTmp1;
122324 *pp1 = p1;
122325 *pp2 = p2;
122326 fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
122327 if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
122328 fts3PoslistMerge(pp, &aTmp, &aTmp2);
122329 }else if( pTmp1!=aTmp ){
122330 fts3PoslistCopy(pp, &aTmp);
122331 }else if( pTmp2!=aTmp2 ){
122332 fts3PoslistCopy(pp, &aTmp2);
122333 }else{
122334 res = 0;
122337 return res;
122341 ** An instance of this function is used to merge together the (potentially
122342 ** large number of) doclists for each term that matches a prefix query.
122343 ** See function fts3TermSelectMerge() for details.
122345 typedef struct TermSelect TermSelect;
122346 struct TermSelect {
122347 char *aaOutput[16]; /* Malloc'd output buffers */
122348 int anOutput[16]; /* Size each output buffer in bytes */
122352 ** This function is used to read a single varint from a buffer. Parameter
122353 ** pEnd points 1 byte past the end of the buffer. When this function is
122354 ** called, if *pp points to pEnd or greater, then the end of the buffer
122355 ** has been reached. In this case *pp is set to 0 and the function returns.
122357 ** If *pp does not point to or past pEnd, then a single varint is read
122358 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
122360 ** If bDescIdx is false, the value read is added to *pVal before returning.
122361 ** If it is true, the value read is subtracted from *pVal before this
122362 ** function returns.
122364 static void fts3GetDeltaVarint3(
122365 char **pp, /* IN/OUT: Point to read varint from */
122366 char *pEnd, /* End of buffer */
122367 int bDescIdx, /* True if docids are descending */
122368 sqlite3_int64 *pVal /* IN/OUT: Integer value */
122370 if( *pp>=pEnd ){
122371 *pp = 0;
122372 }else{
122373 sqlite3_int64 iVal;
122374 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
122375 if( bDescIdx ){
122376 *pVal -= iVal;
122377 }else{
122378 *pVal += iVal;
122384 ** This function is used to write a single varint to a buffer. The varint
122385 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
122386 ** end of the value written.
122388 ** If *pbFirst is zero when this function is called, the value written to
122389 ** the buffer is that of parameter iVal.
122391 ** If *pbFirst is non-zero when this function is called, then the value
122392 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
122393 ** (if bDescIdx is non-zero).
122395 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
122396 ** to the value of parameter iVal.
122398 static void fts3PutDeltaVarint3(
122399 char **pp, /* IN/OUT: Output pointer */
122400 int bDescIdx, /* True for descending docids */
122401 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
122402 int *pbFirst, /* IN/OUT: True after first int written */
122403 sqlite3_int64 iVal /* Write this value to the list */
122405 sqlite3_int64 iWrite;
122406 if( bDescIdx==0 || *pbFirst==0 ){
122407 iWrite = iVal - *piPrev;
122408 }else{
122409 iWrite = *piPrev - iVal;
122411 assert( *pbFirst || *piPrev==0 );
122412 assert( *pbFirst==0 || iWrite>0 );
122413 *pp += sqlite3Fts3PutVarint(*pp, iWrite);
122414 *piPrev = iVal;
122415 *pbFirst = 1;
122420 ** This macro is used by various functions that merge doclists. The two
122421 ** arguments are 64-bit docid values. If the value of the stack variable
122422 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
122423 ** Otherwise, (i2-i1).
122425 ** Using this makes it easier to write code that can merge doclists that are
122426 ** sorted in either ascending or descending order.
122428 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
122431 ** This function does an "OR" merge of two doclists (output contains all
122432 ** positions contained in either argument doclist). If the docids in the
122433 ** input doclists are sorted in ascending order, parameter bDescDoclist
122434 ** should be false. If they are sorted in ascending order, it should be
122435 ** passed a non-zero value.
122437 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
122438 ** containing the output doclist and SQLITE_OK is returned. In this case
122439 ** *pnOut is set to the number of bytes in the output doclist.
122441 ** If an error occurs, an SQLite error code is returned. The output values
122442 ** are undefined in this case.
122444 static int fts3DoclistOrMerge(
122445 int bDescDoclist, /* True if arguments are desc */
122446 char *a1, int n1, /* First doclist */
122447 char *a2, int n2, /* Second doclist */
122448 char **paOut, int *pnOut /* OUT: Malloc'd doclist */
122450 sqlite3_int64 i1 = 0;
122451 sqlite3_int64 i2 = 0;
122452 sqlite3_int64 iPrev = 0;
122453 char *pEnd1 = &a1[n1];
122454 char *pEnd2 = &a2[n2];
122455 char *p1 = a1;
122456 char *p2 = a2;
122457 char *p;
122458 char *aOut;
122459 int bFirstOut = 0;
122461 *paOut = 0;
122462 *pnOut = 0;
122464 /* Allocate space for the output. Both the input and output doclists
122465 ** are delta encoded. If they are in ascending order (bDescDoclist==0),
122466 ** then the first docid in each list is simply encoded as a varint. For
122467 ** each subsequent docid, the varint stored is the difference between the
122468 ** current and previous docid (a positive number - since the list is in
122469 ** ascending order).
122471 ** The first docid written to the output is therefore encoded using the
122472 ** same number of bytes as it is in whichever of the input lists it is
122473 ** read from. And each subsequent docid read from the same input list
122474 ** consumes either the same or less bytes as it did in the input (since
122475 ** the difference between it and the previous value in the output must
122476 ** be a positive value less than or equal to the delta value read from
122477 ** the input list). The same argument applies to all but the first docid
122478 ** read from the 'other' list. And to the contents of all position lists
122479 ** that will be copied and merged from the input to the output.
122481 ** However, if the first docid copied to the output is a negative number,
122482 ** then the encoding of the first docid from the 'other' input list may
122483 ** be larger in the output than it was in the input (since the delta value
122484 ** may be a larger positive integer than the actual docid).
122486 ** The space required to store the output is therefore the sum of the
122487 ** sizes of the two inputs, plus enough space for exactly one of the input
122488 ** docids to grow.
122490 ** A symetric argument may be made if the doclists are in descending
122491 ** order.
122493 aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
122494 if( !aOut ) return SQLITE_NOMEM;
122496 p = aOut;
122497 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
122498 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
122499 while( p1 || p2 ){
122500 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
122502 if( p2 && p1 && iDiff==0 ){
122503 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
122504 fts3PoslistMerge(&p, &p1, &p2);
122505 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
122506 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
122507 }else if( !p2 || (p1 && iDiff<0) ){
122508 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
122509 fts3PoslistCopy(&p, &p1);
122510 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
122511 }else{
122512 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
122513 fts3PoslistCopy(&p, &p2);
122514 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
122518 *paOut = aOut;
122519 *pnOut = (int)(p-aOut);
122520 assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
122521 return SQLITE_OK;
122525 ** This function does a "phrase" merge of two doclists. In a phrase merge,
122526 ** the output contains a copy of each position from the right-hand input
122527 ** doclist for which there is a position in the left-hand input doclist
122528 ** exactly nDist tokens before it.
122530 ** If the docids in the input doclists are sorted in ascending order,
122531 ** parameter bDescDoclist should be false. If they are sorted in ascending
122532 ** order, it should be passed a non-zero value.
122534 ** The right-hand input doclist is overwritten by this function.
122536 static void fts3DoclistPhraseMerge(
122537 int bDescDoclist, /* True if arguments are desc */
122538 int nDist, /* Distance from left to right (1=adjacent) */
122539 char *aLeft, int nLeft, /* Left doclist */
122540 char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
122542 sqlite3_int64 i1 = 0;
122543 sqlite3_int64 i2 = 0;
122544 sqlite3_int64 iPrev = 0;
122545 char *pEnd1 = &aLeft[nLeft];
122546 char *pEnd2 = &aRight[*pnRight];
122547 char *p1 = aLeft;
122548 char *p2 = aRight;
122549 char *p;
122550 int bFirstOut = 0;
122551 char *aOut = aRight;
122553 assert( nDist>0 );
122555 p = aOut;
122556 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
122557 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
122559 while( p1 && p2 ){
122560 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
122561 if( iDiff==0 ){
122562 char *pSave = p;
122563 sqlite3_int64 iPrevSave = iPrev;
122564 int bFirstOutSave = bFirstOut;
122566 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
122567 if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
122568 p = pSave;
122569 iPrev = iPrevSave;
122570 bFirstOut = bFirstOutSave;
122572 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
122573 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
122574 }else if( iDiff<0 ){
122575 fts3PoslistCopy(0, &p1);
122576 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
122577 }else{
122578 fts3PoslistCopy(0, &p2);
122579 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
122583 *pnRight = (int)(p - aOut);
122587 ** Argument pList points to a position list nList bytes in size. This
122588 ** function checks to see if the position list contains any entries for
122589 ** a token in position 0 (of any column). If so, it writes argument iDelta
122590 ** to the output buffer pOut, followed by a position list consisting only
122591 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
122592 ** The value returned is the number of bytes written to pOut (if any).
122594 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
122595 sqlite3_int64 iDelta, /* Varint that may be written to pOut */
122596 char *pList, /* Position list (no 0x00 term) */
122597 int nList, /* Size of pList in bytes */
122598 char *pOut /* Write output here */
122600 int nOut = 0;
122601 int bWritten = 0; /* True once iDelta has been written */
122602 char *p = pList;
122603 char *pEnd = &pList[nList];
122605 if( *p!=0x01 ){
122606 if( *p==0x02 ){
122607 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
122608 pOut[nOut++] = 0x02;
122609 bWritten = 1;
122611 fts3ColumnlistCopy(0, &p);
122614 while( p<pEnd && *p==0x01 ){
122615 sqlite3_int64 iCol;
122617 p += sqlite3Fts3GetVarint(p, &iCol);
122618 if( *p==0x02 ){
122619 if( bWritten==0 ){
122620 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
122621 bWritten = 1;
122623 pOut[nOut++] = 0x01;
122624 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
122625 pOut[nOut++] = 0x02;
122627 fts3ColumnlistCopy(0, &p);
122629 if( bWritten ){
122630 pOut[nOut++] = 0x00;
122633 return nOut;
122638 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
122639 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
122640 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
122642 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
122643 ** the responsibility of the caller to free any doclists left in the
122644 ** TermSelect.aaOutput[] array.
122646 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
122647 char *aOut = 0;
122648 int nOut = 0;
122649 int i;
122651 /* Loop through the doclists in the aaOutput[] array. Merge them all
122652 ** into a single doclist.
122654 for(i=0; i<SizeofArray(pTS->aaOutput); i++){
122655 if( pTS->aaOutput[i] ){
122656 if( !aOut ){
122657 aOut = pTS->aaOutput[i];
122658 nOut = pTS->anOutput[i];
122659 pTS->aaOutput[i] = 0;
122660 }else{
122661 int nNew;
122662 char *aNew;
122664 int rc = fts3DoclistOrMerge(p->bDescIdx,
122665 pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
122667 if( rc!=SQLITE_OK ){
122668 sqlite3_free(aOut);
122669 return rc;
122672 sqlite3_free(pTS->aaOutput[i]);
122673 sqlite3_free(aOut);
122674 pTS->aaOutput[i] = 0;
122675 aOut = aNew;
122676 nOut = nNew;
122681 pTS->aaOutput[0] = aOut;
122682 pTS->anOutput[0] = nOut;
122683 return SQLITE_OK;
122687 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
122688 ** as the first argument. The merge is an "OR" merge (see function
122689 ** fts3DoclistOrMerge() for details).
122691 ** This function is called with the doclist for each term that matches
122692 ** a queried prefix. It merges all these doclists into one, the doclist
122693 ** for the specified prefix. Since there can be a very large number of
122694 ** doclists to merge, the merging is done pair-wise using the TermSelect
122695 ** object.
122697 ** This function returns SQLITE_OK if the merge is successful, or an
122698 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
122700 static int fts3TermSelectMerge(
122701 Fts3Table *p, /* FTS table handle */
122702 TermSelect *pTS, /* TermSelect object to merge into */
122703 char *aDoclist, /* Pointer to doclist */
122704 int nDoclist /* Size of aDoclist in bytes */
122706 if( pTS->aaOutput[0]==0 ){
122707 /* If this is the first term selected, copy the doclist to the output
122708 ** buffer using memcpy(). */
122709 pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
122710 pTS->anOutput[0] = nDoclist;
122711 if( pTS->aaOutput[0] ){
122712 memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
122713 }else{
122714 return SQLITE_NOMEM;
122716 }else{
122717 char *aMerge = aDoclist;
122718 int nMerge = nDoclist;
122719 int iOut;
122721 for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
122722 if( pTS->aaOutput[iOut]==0 ){
122723 assert( iOut>0 );
122724 pTS->aaOutput[iOut] = aMerge;
122725 pTS->anOutput[iOut] = nMerge;
122726 break;
122727 }else{
122728 char *aNew;
122729 int nNew;
122731 int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
122732 pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
122734 if( rc!=SQLITE_OK ){
122735 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
122736 return rc;
122739 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
122740 sqlite3_free(pTS->aaOutput[iOut]);
122741 pTS->aaOutput[iOut] = 0;
122743 aMerge = aNew;
122744 nMerge = nNew;
122745 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
122746 pTS->aaOutput[iOut] = aMerge;
122747 pTS->anOutput[iOut] = nMerge;
122752 return SQLITE_OK;
122756 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
122758 static int fts3SegReaderCursorAppend(
122759 Fts3MultiSegReader *pCsr,
122760 Fts3SegReader *pNew
122762 if( (pCsr->nSegment%16)==0 ){
122763 Fts3SegReader **apNew;
122764 int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
122765 apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
122766 if( !apNew ){
122767 sqlite3Fts3SegReaderFree(pNew);
122768 return SQLITE_NOMEM;
122770 pCsr->apSegment = apNew;
122772 pCsr->apSegment[pCsr->nSegment++] = pNew;
122773 return SQLITE_OK;
122777 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
122778 ** 8th argument.
122780 ** This function returns SQLITE_OK if successful, or an SQLite error code
122781 ** otherwise.
122783 static int fts3SegReaderCursor(
122784 Fts3Table *p, /* FTS3 table handle */
122785 int iLangid, /* Language id */
122786 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
122787 int iLevel, /* Level of segments to scan */
122788 const char *zTerm, /* Term to query for */
122789 int nTerm, /* Size of zTerm in bytes */
122790 int isPrefix, /* True for a prefix search */
122791 int isScan, /* True to scan from zTerm to EOF */
122792 Fts3MultiSegReader *pCsr /* Cursor object to populate */
122794 int rc = SQLITE_OK; /* Error code */
122795 sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
122796 int rc2; /* Result of sqlite3_reset() */
122798 /* If iLevel is less than 0 and this is not a scan, include a seg-reader
122799 ** for the pending-terms. If this is a scan, then this call must be being
122800 ** made by an fts4aux module, not an FTS table. In this case calling
122801 ** Fts3SegReaderPending might segfault, as the data structures used by
122802 ** fts4aux are not completely populated. So it's easiest to filter these
122803 ** calls out here. */
122804 if( iLevel<0 && p->aIndex ){
122805 Fts3SegReader *pSeg = 0;
122806 rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
122807 if( rc==SQLITE_OK && pSeg ){
122808 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
122812 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
122813 if( rc==SQLITE_OK ){
122814 rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
122817 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
122818 Fts3SegReader *pSeg = 0;
122820 /* Read the values returned by the SELECT into local variables. */
122821 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
122822 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
122823 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
122824 int nRoot = sqlite3_column_bytes(pStmt, 4);
122825 char const *zRoot = sqlite3_column_blob(pStmt, 4);
122827 /* If zTerm is not NULL, and this segment is not stored entirely on its
122828 ** root node, the range of leaves scanned can be reduced. Do this. */
122829 if( iStartBlock && zTerm ){
122830 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
122831 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
122832 if( rc!=SQLITE_OK ) goto finished;
122833 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
122836 rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
122837 (isPrefix==0 && isScan==0),
122838 iStartBlock, iLeavesEndBlock,
122839 iEndBlock, zRoot, nRoot, &pSeg
122841 if( rc!=SQLITE_OK ) goto finished;
122842 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
122846 finished:
122847 rc2 = sqlite3_reset(pStmt);
122848 if( rc==SQLITE_DONE ) rc = rc2;
122850 return rc;
122854 ** Set up a cursor object for iterating through a full-text index or a
122855 ** single level therein.
122857 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
122858 Fts3Table *p, /* FTS3 table handle */
122859 int iLangid, /* Language-id to search */
122860 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
122861 int iLevel, /* Level of segments to scan */
122862 const char *zTerm, /* Term to query for */
122863 int nTerm, /* Size of zTerm in bytes */
122864 int isPrefix, /* True for a prefix search */
122865 int isScan, /* True to scan from zTerm to EOF */
122866 Fts3MultiSegReader *pCsr /* Cursor object to populate */
122868 assert( iIndex>=0 && iIndex<p->nIndex );
122869 assert( iLevel==FTS3_SEGCURSOR_ALL
122870 || iLevel==FTS3_SEGCURSOR_PENDING
122871 || iLevel>=0
122873 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
122874 assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
122875 assert( isPrefix==0 || isScan==0 );
122877 memset(pCsr, 0, sizeof(Fts3MultiSegReader));
122878 return fts3SegReaderCursor(
122879 p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
122884 ** In addition to its current configuration, have the Fts3MultiSegReader
122885 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
122887 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
122889 static int fts3SegReaderCursorAddZero(
122890 Fts3Table *p, /* FTS virtual table handle */
122891 int iLangid,
122892 const char *zTerm, /* Term to scan doclist of */
122893 int nTerm, /* Number of bytes in zTerm */
122894 Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
122896 return fts3SegReaderCursor(p,
122897 iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
122902 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
122903 ** if isPrefix is true, to scan the doclist for all terms for which
122904 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
122905 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
122906 ** an SQLite error code.
122908 ** It is the responsibility of the caller to free this object by eventually
122909 ** passing it to fts3SegReaderCursorFree()
122911 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
122912 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
122914 static int fts3TermSegReaderCursor(
122915 Fts3Cursor *pCsr, /* Virtual table cursor handle */
122916 const char *zTerm, /* Term to query for */
122917 int nTerm, /* Size of zTerm in bytes */
122918 int isPrefix, /* True for a prefix search */
122919 Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
122921 Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
122922 int rc = SQLITE_NOMEM; /* Return code */
122924 pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
122925 if( pSegcsr ){
122926 int i;
122927 int bFound = 0; /* True once an index has been found */
122928 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
122930 if( isPrefix ){
122931 for(i=1; bFound==0 && i<p->nIndex; i++){
122932 if( p->aIndex[i].nPrefix==nTerm ){
122933 bFound = 1;
122934 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
122935 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
122937 pSegcsr->bLookup = 1;
122941 for(i=1; bFound==0 && i<p->nIndex; i++){
122942 if( p->aIndex[i].nPrefix==nTerm+1 ){
122943 bFound = 1;
122944 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
122945 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
122947 if( rc==SQLITE_OK ){
122948 rc = fts3SegReaderCursorAddZero(
122949 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
122956 if( bFound==0 ){
122957 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
122958 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
122960 pSegcsr->bLookup = !isPrefix;
122964 *ppSegcsr = pSegcsr;
122965 return rc;
122969 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
122971 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
122972 sqlite3Fts3SegReaderFinish(pSegcsr);
122973 sqlite3_free(pSegcsr);
122977 ** This function retrieves the doclist for the specified term (or term
122978 ** prefix) from the database.
122980 static int fts3TermSelect(
122981 Fts3Table *p, /* Virtual table handle */
122982 Fts3PhraseToken *pTok, /* Token to query for */
122983 int iColumn, /* Column to query (or -ve for all columns) */
122984 int *pnOut, /* OUT: Size of buffer at *ppOut */
122985 char **ppOut /* OUT: Malloced result buffer */
122987 int rc; /* Return code */
122988 Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
122989 TermSelect tsc; /* Object for pair-wise doclist merging */
122990 Fts3SegFilter filter; /* Segment term filter configuration */
122992 pSegcsr = pTok->pSegcsr;
122993 memset(&tsc, 0, sizeof(TermSelect));
122995 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
122996 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
122997 | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
122998 | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
122999 filter.iCol = iColumn;
123000 filter.zTerm = pTok->z;
123001 filter.nTerm = pTok->n;
123003 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
123004 while( SQLITE_OK==rc
123005 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
123007 rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
123010 if( rc==SQLITE_OK ){
123011 rc = fts3TermSelectFinishMerge(p, &tsc);
123013 if( rc==SQLITE_OK ){
123014 *ppOut = tsc.aaOutput[0];
123015 *pnOut = tsc.anOutput[0];
123016 }else{
123017 int i;
123018 for(i=0; i<SizeofArray(tsc.aaOutput); i++){
123019 sqlite3_free(tsc.aaOutput[i]);
123023 fts3SegReaderCursorFree(pSegcsr);
123024 pTok->pSegcsr = 0;
123025 return rc;
123029 ** This function counts the total number of docids in the doclist stored
123030 ** in buffer aList[], size nList bytes.
123032 ** If the isPoslist argument is true, then it is assumed that the doclist
123033 ** contains a position-list following each docid. Otherwise, it is assumed
123034 ** that the doclist is simply a list of docids stored as delta encoded
123035 ** varints.
123037 static int fts3DoclistCountDocids(char *aList, int nList){
123038 int nDoc = 0; /* Return value */
123039 if( aList ){
123040 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
123041 char *p = aList; /* Cursor */
123042 while( p<aEnd ){
123043 nDoc++;
123044 while( (*p++)&0x80 ); /* Skip docid varint */
123045 fts3PoslistCopy(0, &p); /* Skip over position list */
123049 return nDoc;
123053 ** Advance the cursor to the next row in the %_content table that
123054 ** matches the search criteria. For a MATCH search, this will be
123055 ** the next row that matches. For a full-table scan, this will be
123056 ** simply the next row in the %_content table. For a docid lookup,
123057 ** this routine simply sets the EOF flag.
123059 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
123060 ** even if we reach end-of-file. The fts3EofMethod() will be called
123061 ** subsequently to determine whether or not an EOF was hit.
123063 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
123064 int rc;
123065 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
123066 if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
123067 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
123068 pCsr->isEof = 1;
123069 rc = sqlite3_reset(pCsr->pStmt);
123070 }else{
123071 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
123072 rc = SQLITE_OK;
123074 }else{
123075 rc = fts3EvalNext((Fts3Cursor *)pCursor);
123077 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
123078 return rc;
123082 ** This is the xFilter interface for the virtual table. See
123083 ** the virtual table xFilter method documentation for additional
123084 ** information.
123086 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
123087 ** the %_content table.
123089 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
123090 ** in the %_content table.
123092 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
123093 ** column on the left-hand side of the MATCH operator is column
123094 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
123095 ** side of the MATCH operator.
123097 static int fts3FilterMethod(
123098 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
123099 int idxNum, /* Strategy index */
123100 const char *idxStr, /* Unused */
123101 int nVal, /* Number of elements in apVal */
123102 sqlite3_value **apVal /* Arguments for the indexing scheme */
123104 int rc;
123105 char *zSql; /* SQL statement used to access %_content */
123106 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
123107 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
123109 UNUSED_PARAMETER(idxStr);
123110 UNUSED_PARAMETER(nVal);
123112 assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
123113 assert( nVal==0 || nVal==1 || nVal==2 );
123114 assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
123115 assert( p->pSegments==0 );
123117 /* In case the cursor has been used before, clear it now. */
123118 sqlite3_finalize(pCsr->pStmt);
123119 sqlite3_free(pCsr->aDoclist);
123120 sqlite3Fts3ExprFree(pCsr->pExpr);
123121 memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
123123 if( idxStr ){
123124 pCsr->bDesc = (idxStr[0]=='D');
123125 }else{
123126 pCsr->bDesc = p->bDescIdx;
123128 pCsr->eSearch = (i16)idxNum;
123130 if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
123131 int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
123132 const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
123134 if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
123135 return SQLITE_NOMEM;
123138 pCsr->iLangid = 0;
123139 if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
123141 assert( p->base.zErrMsg==0 );
123142 rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
123143 p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
123144 &p->base.zErrMsg
123146 if( rc!=SQLITE_OK ){
123147 return rc;
123150 rc = fts3EvalStart(pCsr);
123151 sqlite3Fts3SegmentsClose(p);
123152 if( rc!=SQLITE_OK ) return rc;
123153 pCsr->pNextId = pCsr->aDoclist;
123154 pCsr->iPrevId = 0;
123157 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
123158 ** statement loops through all rows of the %_content table. For a
123159 ** full-text query or docid lookup, the statement retrieves a single
123160 ** row by docid.
123162 if( idxNum==FTS3_FULLSCAN_SEARCH ){
123163 zSql = sqlite3_mprintf(
123164 "SELECT %s ORDER BY rowid %s",
123165 p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
123167 if( zSql ){
123168 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
123169 sqlite3_free(zSql);
123170 }else{
123171 rc = SQLITE_NOMEM;
123173 }else if( idxNum==FTS3_DOCID_SEARCH ){
123174 rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
123175 if( rc==SQLITE_OK ){
123176 rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
123179 if( rc!=SQLITE_OK ) return rc;
123181 return fts3NextMethod(pCursor);
123185 ** This is the xEof method of the virtual table. SQLite calls this
123186 ** routine to find out if it has reached the end of a result set.
123188 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
123189 return ((Fts3Cursor *)pCursor)->isEof;
123193 ** This is the xRowid method. The SQLite core calls this routine to
123194 ** retrieve the rowid for the current row of the result set. fts3
123195 ** exposes %_content.docid as the rowid for the virtual table. The
123196 ** rowid should be written to *pRowid.
123198 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
123199 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
123200 *pRowid = pCsr->iPrevId;
123201 return SQLITE_OK;
123205 ** This is the xColumn method, called by SQLite to request a value from
123206 ** the row that the supplied cursor currently points to.
123208 ** If:
123210 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
123211 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
123212 ** (iCol == p->nColumn+1) -> Docid column
123213 ** (iCol == p->nColumn+2) -> Langid column
123215 static int fts3ColumnMethod(
123216 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
123217 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
123218 int iCol /* Index of column to read value from */
123220 int rc = SQLITE_OK; /* Return Code */
123221 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
123222 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
123224 /* The column value supplied by SQLite must be in range. */
123225 assert( iCol>=0 && iCol<=p->nColumn+2 );
123227 if( iCol==p->nColumn+1 ){
123228 /* This call is a request for the "docid" column. Since "docid" is an
123229 ** alias for "rowid", use the xRowid() method to obtain the value.
123231 sqlite3_result_int64(pCtx, pCsr->iPrevId);
123232 }else if( iCol==p->nColumn ){
123233 /* The extra column whose name is the same as the table.
123234 ** Return a blob which is a pointer to the cursor. */
123235 sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
123236 }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
123237 sqlite3_result_int64(pCtx, pCsr->iLangid);
123238 }else{
123239 /* The requested column is either a user column (one that contains
123240 ** indexed data), or the language-id column. */
123241 rc = fts3CursorSeek(0, pCsr);
123243 if( rc==SQLITE_OK ){
123244 if( iCol==p->nColumn+2 ){
123245 int iLangid = 0;
123246 if( p->zLanguageid ){
123247 iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
123249 sqlite3_result_int(pCtx, iLangid);
123250 }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
123251 sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
123256 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
123257 return rc;
123261 ** This function is the implementation of the xUpdate callback used by
123262 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
123263 ** inserted, updated or deleted.
123265 static int fts3UpdateMethod(
123266 sqlite3_vtab *pVtab, /* Virtual table handle */
123267 int nArg, /* Size of argument array */
123268 sqlite3_value **apVal, /* Array of arguments */
123269 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
123271 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
123275 ** Implementation of xSync() method. Flush the contents of the pending-terms
123276 ** hash-table to the database.
123278 static int fts3SyncMethod(sqlite3_vtab *pVtab){
123280 /* Following an incremental-merge operation, assuming that the input
123281 ** segments are not completely consumed (the usual case), they are updated
123282 ** in place to remove the entries that have already been merged. This
123283 ** involves updating the leaf block that contains the smallest unmerged
123284 ** entry and each block (if any) between the leaf and the root node. So
123285 ** if the height of the input segment b-trees is N, and input segments
123286 ** are merged eight at a time, updating the input segments at the end
123287 ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
123288 ** small - often between 0 and 2. So the overhead of the incremental
123289 ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
123290 ** dwarfing the actual productive work accomplished, the incremental merge
123291 ** is only attempted if it will write at least 64 leaf blocks. Hence
123292 ** nMinMerge.
123294 ** Of course, updating the input segments also involves deleting a bunch
123295 ** of blocks from the segments table. But this is not considered overhead
123296 ** as it would also be required by a crisis-merge that used the same input
123297 ** segments.
123299 const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
123301 Fts3Table *p = (Fts3Table*)pVtab;
123302 int rc = sqlite3Fts3PendingTermsFlush(p);
123304 if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
123305 int mxLevel = 0; /* Maximum relative level value in db */
123306 int A; /* Incr-merge parameter A */
123308 rc = sqlite3Fts3MaxLevel(p, &mxLevel);
123309 assert( rc==SQLITE_OK || mxLevel==0 );
123310 A = p->nLeafAdd * mxLevel;
123311 A += (A/2);
123312 if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
123314 sqlite3Fts3SegmentsClose(p);
123315 return rc;
123319 ** Implementation of xBegin() method. This is a no-op.
123321 static int fts3BeginMethod(sqlite3_vtab *pVtab){
123322 Fts3Table *p = (Fts3Table*)pVtab;
123323 UNUSED_PARAMETER(pVtab);
123324 assert( p->pSegments==0 );
123325 assert( p->nPendingData==0 );
123326 assert( p->inTransaction!=1 );
123327 TESTONLY( p->inTransaction = 1 );
123328 TESTONLY( p->mxSavepoint = -1; );
123329 p->nLeafAdd = 0;
123330 return SQLITE_OK;
123334 ** Implementation of xCommit() method. This is a no-op. The contents of
123335 ** the pending-terms hash-table have already been flushed into the database
123336 ** by fts3SyncMethod().
123338 static int fts3CommitMethod(sqlite3_vtab *pVtab){
123339 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
123340 UNUSED_PARAMETER(pVtab);
123341 assert( p->nPendingData==0 );
123342 assert( p->inTransaction!=0 );
123343 assert( p->pSegments==0 );
123344 TESTONLY( p->inTransaction = 0 );
123345 TESTONLY( p->mxSavepoint = -1; );
123346 return SQLITE_OK;
123350 ** Implementation of xRollback(). Discard the contents of the pending-terms
123351 ** hash-table. Any changes made to the database are reverted by SQLite.
123353 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
123354 Fts3Table *p = (Fts3Table*)pVtab;
123355 sqlite3Fts3PendingTermsClear(p);
123356 assert( p->inTransaction!=0 );
123357 TESTONLY( p->inTransaction = 0 );
123358 TESTONLY( p->mxSavepoint = -1; );
123359 return SQLITE_OK;
123363 ** When called, *ppPoslist must point to the byte immediately following the
123364 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
123365 ** moves *ppPoslist so that it instead points to the first byte of the
123366 ** same position list.
123368 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
123369 char *p = &(*ppPoslist)[-2];
123370 char c = 0;
123372 while( p>pStart && (c=*p--)==0 );
123373 while( p>pStart && (*p & 0x80) | c ){
123374 c = *p--;
123376 if( p>pStart ){ p = &p[2]; }
123377 while( *p++&0x80 );
123378 *ppPoslist = p;
123382 ** Helper function used by the implementation of the overloaded snippet(),
123383 ** offsets() and optimize() SQL functions.
123385 ** If the value passed as the third argument is a blob of size
123386 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
123387 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
123388 ** message is written to context pContext and SQLITE_ERROR returned. The
123389 ** string passed via zFunc is used as part of the error message.
123391 static int fts3FunctionArg(
123392 sqlite3_context *pContext, /* SQL function call context */
123393 const char *zFunc, /* Function name */
123394 sqlite3_value *pVal, /* argv[0] passed to function */
123395 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
123397 Fts3Cursor *pRet;
123398 if( sqlite3_value_type(pVal)!=SQLITE_BLOB
123399 || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
123401 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
123402 sqlite3_result_error(pContext, zErr, -1);
123403 sqlite3_free(zErr);
123404 return SQLITE_ERROR;
123406 memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
123407 *ppCsr = pRet;
123408 return SQLITE_OK;
123412 ** Implementation of the snippet() function for FTS3
123414 static void fts3SnippetFunc(
123415 sqlite3_context *pContext, /* SQLite function call context */
123416 int nVal, /* Size of apVal[] array */
123417 sqlite3_value **apVal /* Array of arguments */
123419 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
123420 const char *zStart = "<b>";
123421 const char *zEnd = "</b>";
123422 const char *zEllipsis = "<b>...</b>";
123423 int iCol = -1;
123424 int nToken = 15; /* Default number of tokens in snippet */
123426 /* There must be at least one argument passed to this function (otherwise
123427 ** the non-overloaded version would have been called instead of this one).
123429 assert( nVal>=1 );
123431 if( nVal>6 ){
123432 sqlite3_result_error(pContext,
123433 "wrong number of arguments to function snippet()", -1);
123434 return;
123436 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
123438 switch( nVal ){
123439 case 6: nToken = sqlite3_value_int(apVal[5]);
123440 case 5: iCol = sqlite3_value_int(apVal[4]);
123441 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
123442 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
123443 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
123445 if( !zEllipsis || !zEnd || !zStart ){
123446 sqlite3_result_error_nomem(pContext);
123447 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
123448 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
123453 ** Implementation of the offsets() function for FTS3
123455 static void fts3OffsetsFunc(
123456 sqlite3_context *pContext, /* SQLite function call context */
123457 int nVal, /* Size of argument array */
123458 sqlite3_value **apVal /* Array of arguments */
123460 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
123462 UNUSED_PARAMETER(nVal);
123464 assert( nVal==1 );
123465 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
123466 assert( pCsr );
123467 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
123468 sqlite3Fts3Offsets(pContext, pCsr);
123473 ** Implementation of the special optimize() function for FTS3. This
123474 ** function merges all segments in the database to a single segment.
123475 ** Example usage is:
123477 ** SELECT optimize(t) FROM t LIMIT 1;
123479 ** where 't' is the name of an FTS3 table.
123481 static void fts3OptimizeFunc(
123482 sqlite3_context *pContext, /* SQLite function call context */
123483 int nVal, /* Size of argument array */
123484 sqlite3_value **apVal /* Array of arguments */
123486 int rc; /* Return code */
123487 Fts3Table *p; /* Virtual table handle */
123488 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
123490 UNUSED_PARAMETER(nVal);
123492 assert( nVal==1 );
123493 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
123494 p = (Fts3Table *)pCursor->base.pVtab;
123495 assert( p );
123497 rc = sqlite3Fts3Optimize(p);
123499 switch( rc ){
123500 case SQLITE_OK:
123501 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
123502 break;
123503 case SQLITE_DONE:
123504 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
123505 break;
123506 default:
123507 sqlite3_result_error_code(pContext, rc);
123508 break;
123513 ** Implementation of the matchinfo() function for FTS3
123515 static void fts3MatchinfoFunc(
123516 sqlite3_context *pContext, /* SQLite function call context */
123517 int nVal, /* Size of argument array */
123518 sqlite3_value **apVal /* Array of arguments */
123520 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
123521 assert( nVal==1 || nVal==2 );
123522 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
123523 const char *zArg = 0;
123524 if( nVal>1 ){
123525 zArg = (const char *)sqlite3_value_text(apVal[1]);
123527 sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
123532 ** This routine implements the xFindFunction method for the FTS3
123533 ** virtual table.
123535 static int fts3FindFunctionMethod(
123536 sqlite3_vtab *pVtab, /* Virtual table handle */
123537 int nArg, /* Number of SQL function arguments */
123538 const char *zName, /* Name of SQL function */
123539 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
123540 void **ppArg /* Unused */
123542 struct Overloaded {
123543 const char *zName;
123544 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
123545 } aOverload[] = {
123546 { "snippet", fts3SnippetFunc },
123547 { "offsets", fts3OffsetsFunc },
123548 { "optimize", fts3OptimizeFunc },
123549 { "matchinfo", fts3MatchinfoFunc },
123551 int i; /* Iterator variable */
123553 UNUSED_PARAMETER(pVtab);
123554 UNUSED_PARAMETER(nArg);
123555 UNUSED_PARAMETER(ppArg);
123557 for(i=0; i<SizeofArray(aOverload); i++){
123558 if( strcmp(zName, aOverload[i].zName)==0 ){
123559 *pxFunc = aOverload[i].xFunc;
123560 return 1;
123564 /* No function of the specified name was found. Return 0. */
123565 return 0;
123569 ** Implementation of FTS3 xRename method. Rename an fts3 table.
123571 static int fts3RenameMethod(
123572 sqlite3_vtab *pVtab, /* Virtual table handle */
123573 const char *zName /* New name of table */
123575 Fts3Table *p = (Fts3Table *)pVtab;
123576 sqlite3 *db = p->db; /* Database connection */
123577 int rc; /* Return Code */
123579 /* As it happens, the pending terms table is always empty here. This is
123580 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
123581 ** always opens a savepoint transaction. And the xSavepoint() method
123582 ** flushes the pending terms table. But leave the (no-op) call to
123583 ** PendingTermsFlush() in in case that changes.
123585 assert( p->nPendingData==0 );
123586 rc = sqlite3Fts3PendingTermsFlush(p);
123588 if( p->zContentTbl==0 ){
123589 fts3DbExec(&rc, db,
123590 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
123591 p->zDb, p->zName, zName
123595 if( p->bHasDocsize ){
123596 fts3DbExec(&rc, db,
123597 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
123598 p->zDb, p->zName, zName
123601 if( p->bHasStat ){
123602 fts3DbExec(&rc, db,
123603 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
123604 p->zDb, p->zName, zName
123607 fts3DbExec(&rc, db,
123608 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
123609 p->zDb, p->zName, zName
123611 fts3DbExec(&rc, db,
123612 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
123613 p->zDb, p->zName, zName
123615 return rc;
123619 ** The xSavepoint() method.
123621 ** Flush the contents of the pending-terms table to disk.
123623 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
123624 int rc = SQLITE_OK;
123625 UNUSED_PARAMETER(iSavepoint);
123626 assert( ((Fts3Table *)pVtab)->inTransaction );
123627 assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
123628 TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
123629 if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
123630 rc = fts3SyncMethod(pVtab);
123632 return rc;
123636 ** The xRelease() method.
123638 ** This is a no-op.
123640 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
123641 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
123642 UNUSED_PARAMETER(iSavepoint);
123643 UNUSED_PARAMETER(pVtab);
123644 assert( p->inTransaction );
123645 assert( p->mxSavepoint >= iSavepoint );
123646 TESTONLY( p->mxSavepoint = iSavepoint-1 );
123647 return SQLITE_OK;
123651 ** The xRollbackTo() method.
123653 ** Discard the contents of the pending terms table.
123655 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
123656 Fts3Table *p = (Fts3Table*)pVtab;
123657 UNUSED_PARAMETER(iSavepoint);
123658 assert( p->inTransaction );
123659 assert( p->mxSavepoint >= iSavepoint );
123660 TESTONLY( p->mxSavepoint = iSavepoint );
123661 sqlite3Fts3PendingTermsClear(p);
123662 return SQLITE_OK;
123665 static const sqlite3_module fts3Module = {
123666 /* iVersion */ 2,
123667 /* xCreate */ fts3CreateMethod,
123668 /* xConnect */ fts3ConnectMethod,
123669 /* xBestIndex */ fts3BestIndexMethod,
123670 /* xDisconnect */ fts3DisconnectMethod,
123671 /* xDestroy */ fts3DestroyMethod,
123672 /* xOpen */ fts3OpenMethod,
123673 /* xClose */ fts3CloseMethod,
123674 /* xFilter */ fts3FilterMethod,
123675 /* xNext */ fts3NextMethod,
123676 /* xEof */ fts3EofMethod,
123677 /* xColumn */ fts3ColumnMethod,
123678 /* xRowid */ fts3RowidMethod,
123679 /* xUpdate */ fts3UpdateMethod,
123680 /* xBegin */ fts3BeginMethod,
123681 /* xSync */ fts3SyncMethod,
123682 /* xCommit */ fts3CommitMethod,
123683 /* xRollback */ fts3RollbackMethod,
123684 /* xFindFunction */ fts3FindFunctionMethod,
123685 /* xRename */ fts3RenameMethod,
123686 /* xSavepoint */ fts3SavepointMethod,
123687 /* xRelease */ fts3ReleaseMethod,
123688 /* xRollbackTo */ fts3RollbackToMethod,
123692 ** This function is registered as the module destructor (called when an
123693 ** FTS3 enabled database connection is closed). It frees the memory
123694 ** allocated for the tokenizer hash table.
123696 static void hashDestroy(void *p){
123697 Fts3Hash *pHash = (Fts3Hash *)p;
123698 sqlite3Fts3HashClear(pHash);
123699 sqlite3_free(pHash);
123703 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
123704 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
123705 ** respectively. The following three forward declarations are for functions
123706 ** declared in these files used to retrieve the respective implementations.
123708 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
123709 ** to by the argument to point to the "simple" tokenizer implementation.
123710 ** And so on.
123712 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
123713 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
123714 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
123715 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
123716 #endif
123717 #ifdef SQLITE_ENABLE_ICU
123718 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
123719 #endif
123722 ** Initialize the fts3 extension. If this extension is built as part
123723 ** of the sqlite library, then this function is called directly by
123724 ** SQLite. If fts3 is built as a dynamically loadable extension, this
123725 ** function is called by the sqlite3_extension_init() entry point.
123727 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
123728 int rc = SQLITE_OK;
123729 Fts3Hash *pHash = 0;
123730 const sqlite3_tokenizer_module *pSimple = 0;
123731 const sqlite3_tokenizer_module *pPorter = 0;
123732 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
123733 const sqlite3_tokenizer_module *pUnicode = 0;
123734 #endif
123736 #ifdef SQLITE_ENABLE_ICU
123737 const sqlite3_tokenizer_module *pIcu = 0;
123738 sqlite3Fts3IcuTokenizerModule(&pIcu);
123739 #endif
123741 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
123742 sqlite3Fts3UnicodeTokenizer(&pUnicode);
123743 #endif
123745 #ifdef SQLITE_TEST
123746 rc = sqlite3Fts3InitTerm(db);
123747 if( rc!=SQLITE_OK ) return rc;
123748 #endif
123750 rc = sqlite3Fts3InitAux(db);
123751 if( rc!=SQLITE_OK ) return rc;
123753 sqlite3Fts3SimpleTokenizerModule(&pSimple);
123754 sqlite3Fts3PorterTokenizerModule(&pPorter);
123756 /* Allocate and initialize the hash-table used to store tokenizers. */
123757 pHash = sqlite3_malloc(sizeof(Fts3Hash));
123758 if( !pHash ){
123759 rc = SQLITE_NOMEM;
123760 }else{
123761 sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
123764 /* Load the built-in tokenizers into the hash table */
123765 if( rc==SQLITE_OK ){
123766 if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
123767 || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
123769 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
123770 || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
123771 #endif
123772 #ifdef SQLITE_ENABLE_ICU
123773 || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
123774 #endif
123776 rc = SQLITE_NOMEM;
123780 #ifdef SQLITE_TEST
123781 if( rc==SQLITE_OK ){
123782 rc = sqlite3Fts3ExprInitTestInterface(db);
123784 #endif
123786 /* Create the virtual table wrapper around the hash-table and overload
123787 ** the two scalar functions. If this is successful, register the
123788 ** module with sqlite.
123790 if( SQLITE_OK==rc
123791 && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
123792 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
123793 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
123794 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
123795 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
123796 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
123798 rc = sqlite3_create_module_v2(
123799 db, "fts3", &fts3Module, (void *)pHash, hashDestroy
123801 if( rc==SQLITE_OK ){
123802 rc = sqlite3_create_module_v2(
123803 db, "fts4", &fts3Module, (void *)pHash, 0
123806 if( rc==SQLITE_OK ){
123807 rc = sqlite3Fts3InitTok(db, (void *)pHash);
123809 return rc;
123813 /* An error has occurred. Delete the hash table and return the error code. */
123814 assert( rc!=SQLITE_OK );
123815 if( pHash ){
123816 sqlite3Fts3HashClear(pHash);
123817 sqlite3_free(pHash);
123819 return rc;
123823 ** Allocate an Fts3MultiSegReader for each token in the expression headed
123824 ** by pExpr.
123826 ** An Fts3SegReader object is a cursor that can seek or scan a range of
123827 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
123828 ** Fts3SegReader objects internally to provide an interface to seek or scan
123829 ** within the union of all segments of a b-tree. Hence the name.
123831 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
123832 ** segment b-tree (if the term is not a prefix or it is a prefix for which
123833 ** there exists prefix b-tree of the right length) then it may be traversed
123834 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
123835 ** doclist and then traversed.
123837 static void fts3EvalAllocateReaders(
123838 Fts3Cursor *pCsr, /* FTS cursor handle */
123839 Fts3Expr *pExpr, /* Allocate readers for this expression */
123840 int *pnToken, /* OUT: Total number of tokens in phrase. */
123841 int *pnOr, /* OUT: Total number of OR nodes in expr. */
123842 int *pRc /* IN/OUT: Error code */
123844 if( pExpr && SQLITE_OK==*pRc ){
123845 if( pExpr->eType==FTSQUERY_PHRASE ){
123846 int i;
123847 int nToken = pExpr->pPhrase->nToken;
123848 *pnToken += nToken;
123849 for(i=0; i<nToken; i++){
123850 Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
123851 int rc = fts3TermSegReaderCursor(pCsr,
123852 pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
123854 if( rc!=SQLITE_OK ){
123855 *pRc = rc;
123856 return;
123859 assert( pExpr->pPhrase->iDoclistToken==0 );
123860 pExpr->pPhrase->iDoclistToken = -1;
123861 }else{
123862 *pnOr += (pExpr->eType==FTSQUERY_OR);
123863 fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
123864 fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
123870 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
123871 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
123873 ** This function assumes that pList points to a buffer allocated using
123874 ** sqlite3_malloc(). This function takes responsibility for eventually
123875 ** freeing the buffer.
123877 static void fts3EvalPhraseMergeToken(
123878 Fts3Table *pTab, /* FTS Table pointer */
123879 Fts3Phrase *p, /* Phrase to merge pList/nList into */
123880 int iToken, /* Token pList/nList corresponds to */
123881 char *pList, /* Pointer to doclist */
123882 int nList /* Number of bytes in pList */
123884 assert( iToken!=p->iDoclistToken );
123886 if( pList==0 ){
123887 sqlite3_free(p->doclist.aAll);
123888 p->doclist.aAll = 0;
123889 p->doclist.nAll = 0;
123892 else if( p->iDoclistToken<0 ){
123893 p->doclist.aAll = pList;
123894 p->doclist.nAll = nList;
123897 else if( p->doclist.aAll==0 ){
123898 sqlite3_free(pList);
123901 else {
123902 char *pLeft;
123903 char *pRight;
123904 int nLeft;
123905 int nRight;
123906 int nDiff;
123908 if( p->iDoclistToken<iToken ){
123909 pLeft = p->doclist.aAll;
123910 nLeft = p->doclist.nAll;
123911 pRight = pList;
123912 nRight = nList;
123913 nDiff = iToken - p->iDoclistToken;
123914 }else{
123915 pRight = p->doclist.aAll;
123916 nRight = p->doclist.nAll;
123917 pLeft = pList;
123918 nLeft = nList;
123919 nDiff = p->iDoclistToken - iToken;
123922 fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
123923 sqlite3_free(pLeft);
123924 p->doclist.aAll = pRight;
123925 p->doclist.nAll = nRight;
123928 if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
123932 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
123933 ** does not take deferred tokens into account.
123935 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
123937 static int fts3EvalPhraseLoad(
123938 Fts3Cursor *pCsr, /* FTS Cursor handle */
123939 Fts3Phrase *p /* Phrase object */
123941 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123942 int iToken;
123943 int rc = SQLITE_OK;
123945 for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
123946 Fts3PhraseToken *pToken = &p->aToken[iToken];
123947 assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
123949 if( pToken->pSegcsr ){
123950 int nThis = 0;
123951 char *pThis = 0;
123952 rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
123953 if( rc==SQLITE_OK ){
123954 fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
123957 assert( pToken->pSegcsr==0 );
123960 return rc;
123964 ** This function is called on each phrase after the position lists for
123965 ** any deferred tokens have been loaded into memory. It updates the phrases
123966 ** current position list to include only those positions that are really
123967 ** instances of the phrase (after considering deferred tokens). If this
123968 ** means that the phrase does not appear in the current row, doclist.pList
123969 ** and doclist.nList are both zeroed.
123971 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
123973 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
123974 int iToken; /* Used to iterate through phrase tokens */
123975 char *aPoslist = 0; /* Position list for deferred tokens */
123976 int nPoslist = 0; /* Number of bytes in aPoslist */
123977 int iPrev = -1; /* Token number of previous deferred token */
123979 assert( pPhrase->doclist.bFreeList==0 );
123981 for(iToken=0; iToken<pPhrase->nToken; iToken++){
123982 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
123983 Fts3DeferredToken *pDeferred = pToken->pDeferred;
123985 if( pDeferred ){
123986 char *pList;
123987 int nList;
123988 int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
123989 if( rc!=SQLITE_OK ) return rc;
123991 if( pList==0 ){
123992 sqlite3_free(aPoslist);
123993 pPhrase->doclist.pList = 0;
123994 pPhrase->doclist.nList = 0;
123995 return SQLITE_OK;
123997 }else if( aPoslist==0 ){
123998 aPoslist = pList;
123999 nPoslist = nList;
124001 }else{
124002 char *aOut = pList;
124003 char *p1 = aPoslist;
124004 char *p2 = aOut;
124006 assert( iPrev>=0 );
124007 fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
124008 sqlite3_free(aPoslist);
124009 aPoslist = pList;
124010 nPoslist = (int)(aOut - aPoslist);
124011 if( nPoslist==0 ){
124012 sqlite3_free(aPoslist);
124013 pPhrase->doclist.pList = 0;
124014 pPhrase->doclist.nList = 0;
124015 return SQLITE_OK;
124018 iPrev = iToken;
124022 if( iPrev>=0 ){
124023 int nMaxUndeferred = pPhrase->iDoclistToken;
124024 if( nMaxUndeferred<0 ){
124025 pPhrase->doclist.pList = aPoslist;
124026 pPhrase->doclist.nList = nPoslist;
124027 pPhrase->doclist.iDocid = pCsr->iPrevId;
124028 pPhrase->doclist.bFreeList = 1;
124029 }else{
124030 int nDistance;
124031 char *p1;
124032 char *p2;
124033 char *aOut;
124035 if( nMaxUndeferred>iPrev ){
124036 p1 = aPoslist;
124037 p2 = pPhrase->doclist.pList;
124038 nDistance = nMaxUndeferred - iPrev;
124039 }else{
124040 p1 = pPhrase->doclist.pList;
124041 p2 = aPoslist;
124042 nDistance = iPrev - nMaxUndeferred;
124045 aOut = (char *)sqlite3_malloc(nPoslist+8);
124046 if( !aOut ){
124047 sqlite3_free(aPoslist);
124048 return SQLITE_NOMEM;
124051 pPhrase->doclist.pList = aOut;
124052 if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
124053 pPhrase->doclist.bFreeList = 1;
124054 pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
124055 }else{
124056 sqlite3_free(aOut);
124057 pPhrase->doclist.pList = 0;
124058 pPhrase->doclist.nList = 0;
124060 sqlite3_free(aPoslist);
124064 return SQLITE_OK;
124068 ** This function is called for each Fts3Phrase in a full-text query
124069 ** expression to initialize the mechanism for returning rows. Once this
124070 ** function has been called successfully on an Fts3Phrase, it may be
124071 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
124073 ** If parameter bOptOk is true, then the phrase may (or may not) use the
124074 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
124075 ** memory within this call.
124077 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
124079 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
124080 int rc; /* Error code */
124081 Fts3PhraseToken *pFirst = &p->aToken[0];
124082 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124084 if( pCsr->bDesc==pTab->bDescIdx
124085 && bOptOk==1
124086 && p->nToken==1
124087 && pFirst->pSegcsr
124088 && pFirst->pSegcsr->bLookup
124089 && pFirst->bFirst==0
124091 /* Use the incremental approach. */
124092 int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
124093 rc = sqlite3Fts3MsrIncrStart(
124094 pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
124095 p->bIncr = 1;
124097 }else{
124098 /* Load the full doclist for the phrase into memory. */
124099 rc = fts3EvalPhraseLoad(pCsr, p);
124100 p->bIncr = 0;
124103 assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
124104 return rc;
124108 ** This function is used to iterate backwards (from the end to start)
124109 ** through doclists. It is used by this module to iterate through phrase
124110 ** doclists in reverse and by the fts3_write.c module to iterate through
124111 ** pending-terms lists when writing to databases with "order=desc".
124113 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
124114 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
124115 ** function iterates from the end of the doclist to the beginning.
124117 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
124118 int bDescIdx, /* True if the doclist is desc */
124119 char *aDoclist, /* Pointer to entire doclist */
124120 int nDoclist, /* Length of aDoclist in bytes */
124121 char **ppIter, /* IN/OUT: Iterator pointer */
124122 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
124123 int *pnList, /* OUT: List length pointer */
124124 u8 *pbEof /* OUT: End-of-file flag */
124126 char *p = *ppIter;
124128 assert( nDoclist>0 );
124129 assert( *pbEof==0 );
124130 assert( p || *piDocid==0 );
124131 assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
124133 if( p==0 ){
124134 sqlite3_int64 iDocid = 0;
124135 char *pNext = 0;
124136 char *pDocid = aDoclist;
124137 char *pEnd = &aDoclist[nDoclist];
124138 int iMul = 1;
124140 while( pDocid<pEnd ){
124141 sqlite3_int64 iDelta;
124142 pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
124143 iDocid += (iMul * iDelta);
124144 pNext = pDocid;
124145 fts3PoslistCopy(0, &pDocid);
124146 while( pDocid<pEnd && *pDocid==0 ) pDocid++;
124147 iMul = (bDescIdx ? -1 : 1);
124150 *pnList = (int)(pEnd - pNext);
124151 *ppIter = pNext;
124152 *piDocid = iDocid;
124153 }else{
124154 int iMul = (bDescIdx ? -1 : 1);
124155 sqlite3_int64 iDelta;
124156 fts3GetReverseVarint(&p, aDoclist, &iDelta);
124157 *piDocid -= (iMul * iDelta);
124159 if( p==aDoclist ){
124160 *pbEof = 1;
124161 }else{
124162 char *pSave = p;
124163 fts3ReversePoslist(aDoclist, &p);
124164 *pnList = (int)(pSave - p);
124166 *ppIter = p;
124171 ** Iterate forwards through a doclist.
124173 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
124174 int bDescIdx, /* True if the doclist is desc */
124175 char *aDoclist, /* Pointer to entire doclist */
124176 int nDoclist, /* Length of aDoclist in bytes */
124177 char **ppIter, /* IN/OUT: Iterator pointer */
124178 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
124179 u8 *pbEof /* OUT: End-of-file flag */
124181 char *p = *ppIter;
124183 assert( nDoclist>0 );
124184 assert( *pbEof==0 );
124185 assert( p || *piDocid==0 );
124186 assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
124188 if( p==0 ){
124189 p = aDoclist;
124190 p += sqlite3Fts3GetVarint(p, piDocid);
124191 }else{
124192 fts3PoslistCopy(0, &p);
124193 if( p>=&aDoclist[nDoclist] ){
124194 *pbEof = 1;
124195 }else{
124196 sqlite3_int64 iVar;
124197 p += sqlite3Fts3GetVarint(p, &iVar);
124198 *piDocid += ((bDescIdx ? -1 : 1) * iVar);
124202 *ppIter = p;
124206 ** Attempt to move the phrase iterator to point to the next matching docid.
124207 ** If an error occurs, return an SQLite error code. Otherwise, return
124208 ** SQLITE_OK.
124210 ** If there is no "next" entry and no error occurs, then *pbEof is set to
124211 ** 1 before returning. Otherwise, if no error occurs and the iterator is
124212 ** successfully advanced, *pbEof is set to 0.
124214 static int fts3EvalPhraseNext(
124215 Fts3Cursor *pCsr, /* FTS Cursor handle */
124216 Fts3Phrase *p, /* Phrase object to advance to next docid */
124217 u8 *pbEof /* OUT: Set to 1 if EOF */
124219 int rc = SQLITE_OK;
124220 Fts3Doclist *pDL = &p->doclist;
124221 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124223 if( p->bIncr ){
124224 assert( p->nToken==1 );
124225 assert( pDL->pNextDocid==0 );
124226 rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
124227 &pDL->iDocid, &pDL->pList, &pDL->nList
124229 if( rc==SQLITE_OK && !pDL->pList ){
124230 *pbEof = 1;
124232 }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
124233 sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
124234 &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
124236 pDL->pList = pDL->pNextDocid;
124237 }else{
124238 char *pIter; /* Used to iterate through aAll */
124239 char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
124240 if( pDL->pNextDocid ){
124241 pIter = pDL->pNextDocid;
124242 }else{
124243 pIter = pDL->aAll;
124246 if( pIter>=pEnd ){
124247 /* We have already reached the end of this doclist. EOF. */
124248 *pbEof = 1;
124249 }else{
124250 sqlite3_int64 iDelta;
124251 pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
124252 if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
124253 pDL->iDocid += iDelta;
124254 }else{
124255 pDL->iDocid -= iDelta;
124257 pDL->pList = pIter;
124258 fts3PoslistCopy(0, &pIter);
124259 pDL->nList = (int)(pIter - pDL->pList);
124261 /* pIter now points just past the 0x00 that terminates the position-
124262 ** list for document pDL->iDocid. However, if this position-list was
124263 ** edited in place by fts3EvalNearTrim(), then pIter may not actually
124264 ** point to the start of the next docid value. The following line deals
124265 ** with this case by advancing pIter past the zero-padding added by
124266 ** fts3EvalNearTrim(). */
124267 while( pIter<pEnd && *pIter==0 ) pIter++;
124269 pDL->pNextDocid = pIter;
124270 assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
124271 *pbEof = 0;
124275 return rc;
124280 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
124281 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
124282 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
124283 ** expressions for which all descendent tokens are deferred.
124285 ** If parameter bOptOk is zero, then it is guaranteed that the
124286 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
124287 ** each phrase in the expression (subject to deferred token processing).
124288 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
124289 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
124291 ** If an error occurs within this function, *pRc is set to an SQLite error
124292 ** code before returning.
124294 static void fts3EvalStartReaders(
124295 Fts3Cursor *pCsr, /* FTS Cursor handle */
124296 Fts3Expr *pExpr, /* Expression to initialize phrases in */
124297 int bOptOk, /* True to enable incremental loading */
124298 int *pRc /* IN/OUT: Error code */
124300 if( pExpr && SQLITE_OK==*pRc ){
124301 if( pExpr->eType==FTSQUERY_PHRASE ){
124302 int i;
124303 int nToken = pExpr->pPhrase->nToken;
124304 for(i=0; i<nToken; i++){
124305 if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
124307 pExpr->bDeferred = (i==nToken);
124308 *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
124309 }else{
124310 fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
124311 fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
124312 pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
124318 ** An array of the following structures is assembled as part of the process
124319 ** of selecting tokens to defer before the query starts executing (as part
124320 ** of the xFilter() method). There is one element in the array for each
124321 ** token in the FTS expression.
124323 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
124324 ** to phrases that are connected only by AND and NEAR operators (not OR or
124325 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
124326 ** separately. The root of a tokens AND/NEAR cluster is stored in
124327 ** Fts3TokenAndCost.pRoot.
124329 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
124330 struct Fts3TokenAndCost {
124331 Fts3Phrase *pPhrase; /* The phrase the token belongs to */
124332 int iToken; /* Position of token in phrase */
124333 Fts3PhraseToken *pToken; /* The token itself */
124334 Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
124335 int nOvfl; /* Number of overflow pages to load doclist */
124336 int iCol; /* The column the token must match */
124340 ** This function is used to populate an allocated Fts3TokenAndCost array.
124342 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
124343 ** Otherwise, if an error occurs during execution, *pRc is set to an
124344 ** SQLite error code.
124346 static void fts3EvalTokenCosts(
124347 Fts3Cursor *pCsr, /* FTS Cursor handle */
124348 Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
124349 Fts3Expr *pExpr, /* Expression to consider */
124350 Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
124351 Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
124352 int *pRc /* IN/OUT: Error code */
124354 if( *pRc==SQLITE_OK ){
124355 if( pExpr->eType==FTSQUERY_PHRASE ){
124356 Fts3Phrase *pPhrase = pExpr->pPhrase;
124357 int i;
124358 for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
124359 Fts3TokenAndCost *pTC = (*ppTC)++;
124360 pTC->pPhrase = pPhrase;
124361 pTC->iToken = i;
124362 pTC->pRoot = pRoot;
124363 pTC->pToken = &pPhrase->aToken[i];
124364 pTC->iCol = pPhrase->iColumn;
124365 *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
124367 }else if( pExpr->eType!=FTSQUERY_NOT ){
124368 assert( pExpr->eType==FTSQUERY_OR
124369 || pExpr->eType==FTSQUERY_AND
124370 || pExpr->eType==FTSQUERY_NEAR
124372 assert( pExpr->pLeft && pExpr->pRight );
124373 if( pExpr->eType==FTSQUERY_OR ){
124374 pRoot = pExpr->pLeft;
124375 **ppOr = pRoot;
124376 (*ppOr)++;
124378 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
124379 if( pExpr->eType==FTSQUERY_OR ){
124380 pRoot = pExpr->pRight;
124381 **ppOr = pRoot;
124382 (*ppOr)++;
124384 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
124390 ** Determine the average document (row) size in pages. If successful,
124391 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
124392 ** an SQLite error code.
124394 ** The average document size in pages is calculated by first calculating
124395 ** determining the average size in bytes, B. If B is less than the amount
124396 ** of data that will fit on a single leaf page of an intkey table in
124397 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
124398 ** the number of overflow pages consumed by a record B bytes in size.
124400 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
124401 if( pCsr->nRowAvg==0 ){
124402 /* The average document size, which is required to calculate the cost
124403 ** of each doclist, has not yet been determined. Read the required
124404 ** data from the %_stat table to calculate it.
124406 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
124407 ** varints, where nCol is the number of columns in the FTS3 table.
124408 ** The first varint is the number of documents currently stored in
124409 ** the table. The following nCol varints contain the total amount of
124410 ** data stored in all rows of each column of the table, from left
124411 ** to right.
124413 int rc;
124414 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
124415 sqlite3_stmt *pStmt;
124416 sqlite3_int64 nDoc = 0;
124417 sqlite3_int64 nByte = 0;
124418 const char *pEnd;
124419 const char *a;
124421 rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
124422 if( rc!=SQLITE_OK ) return rc;
124423 a = sqlite3_column_blob(pStmt, 0);
124424 assert( a );
124426 pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
124427 a += sqlite3Fts3GetVarint(a, &nDoc);
124428 while( a<pEnd ){
124429 a += sqlite3Fts3GetVarint(a, &nByte);
124431 if( nDoc==0 || nByte==0 ){
124432 sqlite3_reset(pStmt);
124433 return FTS_CORRUPT_VTAB;
124436 pCsr->nDoc = nDoc;
124437 pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
124438 assert( pCsr->nRowAvg>0 );
124439 rc = sqlite3_reset(pStmt);
124440 if( rc!=SQLITE_OK ) return rc;
124443 *pnPage = pCsr->nRowAvg;
124444 return SQLITE_OK;
124448 ** This function is called to select the tokens (if any) that will be
124449 ** deferred. The array aTC[] has already been populated when this is
124450 ** called.
124452 ** This function is called once for each AND/NEAR cluster in the
124453 ** expression. Each invocation determines which tokens to defer within
124454 ** the cluster with root node pRoot. See comments above the definition
124455 ** of struct Fts3TokenAndCost for more details.
124457 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
124458 ** called on each token to defer. Otherwise, an SQLite error code is
124459 ** returned.
124461 static int fts3EvalSelectDeferred(
124462 Fts3Cursor *pCsr, /* FTS Cursor handle */
124463 Fts3Expr *pRoot, /* Consider tokens with this root node */
124464 Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
124465 int nTC /* Number of entries in aTC[] */
124467 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124468 int nDocSize = 0; /* Number of pages per doc loaded */
124469 int rc = SQLITE_OK; /* Return code */
124470 int ii; /* Iterator variable for various purposes */
124471 int nOvfl = 0; /* Total overflow pages used by doclists */
124472 int nToken = 0; /* Total number of tokens in cluster */
124474 int nMinEst = 0; /* The minimum count for any phrase so far. */
124475 int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
124477 /* Tokens are never deferred for FTS tables created using the content=xxx
124478 ** option. The reason being that it is not guaranteed that the content
124479 ** table actually contains the same data as the index. To prevent this from
124480 ** causing any problems, the deferred token optimization is completely
124481 ** disabled for content=xxx tables. */
124482 if( pTab->zContentTbl ){
124483 return SQLITE_OK;
124486 /* Count the tokens in this AND/NEAR cluster. If none of the doclists
124487 ** associated with the tokens spill onto overflow pages, or if there is
124488 ** only 1 token, exit early. No tokens to defer in this case. */
124489 for(ii=0; ii<nTC; ii++){
124490 if( aTC[ii].pRoot==pRoot ){
124491 nOvfl += aTC[ii].nOvfl;
124492 nToken++;
124495 if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
124497 /* Obtain the average docsize (in pages). */
124498 rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
124499 assert( rc!=SQLITE_OK || nDocSize>0 );
124502 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
124503 ** of the number of overflow pages that will be loaded by the pager layer
124504 ** to retrieve the entire doclist for the token from the full-text index.
124505 ** Load the doclists for tokens that are either:
124507 ** a. The cheapest token in the entire query (i.e. the one visited by the
124508 ** first iteration of this loop), or
124510 ** b. Part of a multi-token phrase.
124512 ** After each token doclist is loaded, merge it with the others from the
124513 ** same phrase and count the number of documents that the merged doclist
124514 ** contains. Set variable "nMinEst" to the smallest number of documents in
124515 ** any phrase doclist for which 1 or more token doclists have been loaded.
124516 ** Let nOther be the number of other phrases for which it is certain that
124517 ** one or more tokens will not be deferred.
124519 ** Then, for each token, defer it if loading the doclist would result in
124520 ** loading N or more overflow pages into memory, where N is computed as:
124522 ** (nMinEst + 4^nOther - 1) / (4^nOther)
124524 for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
124525 int iTC; /* Used to iterate through aTC[] array. */
124526 Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
124528 /* Set pTC to point to the cheapest remaining token. */
124529 for(iTC=0; iTC<nTC; iTC++){
124530 if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
124531 && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
124533 pTC = &aTC[iTC];
124536 assert( pTC );
124538 if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
124539 /* The number of overflow pages to load for this (and therefore all
124540 ** subsequent) tokens is greater than the estimated number of pages
124541 ** that will be loaded if all subsequent tokens are deferred.
124543 Fts3PhraseToken *pToken = pTC->pToken;
124544 rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
124545 fts3SegReaderCursorFree(pToken->pSegcsr);
124546 pToken->pSegcsr = 0;
124547 }else{
124548 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
124549 ** for-loop. Except, limit the value to 2^24 to prevent it from
124550 ** overflowing the 32-bit integer it is stored in. */
124551 if( ii<12 ) nLoad4 = nLoad4*4;
124553 if( ii==0 || pTC->pPhrase->nToken>1 ){
124554 /* Either this is the cheapest token in the entire query, or it is
124555 ** part of a multi-token phrase. Either way, the entire doclist will
124556 ** (eventually) be loaded into memory. It may as well be now. */
124557 Fts3PhraseToken *pToken = pTC->pToken;
124558 int nList = 0;
124559 char *pList = 0;
124560 rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
124561 assert( rc==SQLITE_OK || pList==0 );
124562 if( rc==SQLITE_OK ){
124563 int nCount;
124564 fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
124565 nCount = fts3DoclistCountDocids(
124566 pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
124568 if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
124572 pTC->pToken = 0;
124575 return rc;
124579 ** This function is called from within the xFilter method. It initializes
124580 ** the full-text query currently stored in pCsr->pExpr. To iterate through
124581 ** the results of a query, the caller does:
124583 ** fts3EvalStart(pCsr);
124584 ** while( 1 ){
124585 ** fts3EvalNext(pCsr);
124586 ** if( pCsr->bEof ) break;
124587 ** ... return row pCsr->iPrevId to the caller ...
124590 static int fts3EvalStart(Fts3Cursor *pCsr){
124591 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124592 int rc = SQLITE_OK;
124593 int nToken = 0;
124594 int nOr = 0;
124596 /* Allocate a MultiSegReader for each token in the expression. */
124597 fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
124599 /* Determine which, if any, tokens in the expression should be deferred. */
124600 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
124601 if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
124602 Fts3TokenAndCost *aTC;
124603 Fts3Expr **apOr;
124604 aTC = (Fts3TokenAndCost *)sqlite3_malloc(
124605 sizeof(Fts3TokenAndCost) * nToken
124606 + sizeof(Fts3Expr *) * nOr * 2
124608 apOr = (Fts3Expr **)&aTC[nToken];
124610 if( !aTC ){
124611 rc = SQLITE_NOMEM;
124612 }else{
124613 int ii;
124614 Fts3TokenAndCost *pTC = aTC;
124615 Fts3Expr **ppOr = apOr;
124617 fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
124618 nToken = (int)(pTC-aTC);
124619 nOr = (int)(ppOr-apOr);
124621 if( rc==SQLITE_OK ){
124622 rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
124623 for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
124624 rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
124628 sqlite3_free(aTC);
124631 #endif
124633 fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
124634 return rc;
124638 ** Invalidate the current position list for phrase pPhrase.
124640 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
124641 if( pPhrase->doclist.bFreeList ){
124642 sqlite3_free(pPhrase->doclist.pList);
124644 pPhrase->doclist.pList = 0;
124645 pPhrase->doclist.nList = 0;
124646 pPhrase->doclist.bFreeList = 0;
124650 ** This function is called to edit the position list associated with
124651 ** the phrase object passed as the fifth argument according to a NEAR
124652 ** condition. For example:
124654 ** abc NEAR/5 "def ghi"
124656 ** Parameter nNear is passed the NEAR distance of the expression (5 in
124657 ** the example above). When this function is called, *paPoslist points to
124658 ** the position list, and *pnToken is the number of phrase tokens in, the
124659 ** phrase on the other side of the NEAR operator to pPhrase. For example,
124660 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
124661 ** the position list associated with phrase "abc".
124663 ** All positions in the pPhrase position list that are not sufficiently
124664 ** close to a position in the *paPoslist position list are removed. If this
124665 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
124667 ** Before returning, *paPoslist is set to point to the position lsit
124668 ** associated with pPhrase. And *pnToken is set to the number of tokens in
124669 ** pPhrase.
124671 static int fts3EvalNearTrim(
124672 int nNear, /* NEAR distance. As in "NEAR/nNear". */
124673 char *aTmp, /* Temporary space to use */
124674 char **paPoslist, /* IN/OUT: Position list */
124675 int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
124676 Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
124678 int nParam1 = nNear + pPhrase->nToken;
124679 int nParam2 = nNear + *pnToken;
124680 int nNew;
124681 char *p2;
124682 char *pOut;
124683 int res;
124685 assert( pPhrase->doclist.pList );
124687 p2 = pOut = pPhrase->doclist.pList;
124688 res = fts3PoslistNearMerge(
124689 &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
124691 if( res ){
124692 nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
124693 assert( pPhrase->doclist.pList[nNew]=='\0' );
124694 assert( nNew<=pPhrase->doclist.nList && nNew>0 );
124695 memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
124696 pPhrase->doclist.nList = nNew;
124697 *paPoslist = pPhrase->doclist.pList;
124698 *pnToken = pPhrase->nToken;
124701 return res;
124705 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
124706 ** Otherwise, it advances the expression passed as the second argument to
124707 ** point to the next matching row in the database. Expressions iterate through
124708 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
124709 ** or descending if it is non-zero.
124711 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
124712 ** successful, the following variables in pExpr are set:
124714 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
124715 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
124717 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
124718 ** at EOF, then the following variables are populated with the position list
124719 ** for the phrase for the visited row:
124721 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
124722 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
124724 ** It says above that this function advances the expression to the next
124725 ** matching row. This is usually true, but there are the following exceptions:
124727 ** 1. Deferred tokens are not taken into account. If a phrase consists
124728 ** entirely of deferred tokens, it is assumed to match every row in
124729 ** the db. In this case the position-list is not populated at all.
124731 ** Or, if a phrase contains one or more deferred tokens and one or
124732 ** more non-deferred tokens, then the expression is advanced to the
124733 ** next possible match, considering only non-deferred tokens. In other
124734 ** words, if the phrase is "A B C", and "B" is deferred, the expression
124735 ** is advanced to the next row that contains an instance of "A * C",
124736 ** where "*" may match any single token. The position list in this case
124737 ** is populated as for "A * C" before returning.
124739 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
124740 ** advanced to point to the next row that matches "x AND y".
124742 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
124743 ** really a match, taking into account deferred tokens and NEAR operators.
124745 static void fts3EvalNextRow(
124746 Fts3Cursor *pCsr, /* FTS Cursor handle */
124747 Fts3Expr *pExpr, /* Expr. to advance to next matching row */
124748 int *pRc /* IN/OUT: Error code */
124750 if( *pRc==SQLITE_OK ){
124751 int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
124752 assert( pExpr->bEof==0 );
124753 pExpr->bStart = 1;
124755 switch( pExpr->eType ){
124756 case FTSQUERY_NEAR:
124757 case FTSQUERY_AND: {
124758 Fts3Expr *pLeft = pExpr->pLeft;
124759 Fts3Expr *pRight = pExpr->pRight;
124760 assert( !pLeft->bDeferred || !pRight->bDeferred );
124762 if( pLeft->bDeferred ){
124763 /* LHS is entirely deferred. So we assume it matches every row.
124764 ** Advance the RHS iterator to find the next row visited. */
124765 fts3EvalNextRow(pCsr, pRight, pRc);
124766 pExpr->iDocid = pRight->iDocid;
124767 pExpr->bEof = pRight->bEof;
124768 }else if( pRight->bDeferred ){
124769 /* RHS is entirely deferred. So we assume it matches every row.
124770 ** Advance the LHS iterator to find the next row visited. */
124771 fts3EvalNextRow(pCsr, pLeft, pRc);
124772 pExpr->iDocid = pLeft->iDocid;
124773 pExpr->bEof = pLeft->bEof;
124774 }else{
124775 /* Neither the RHS or LHS are deferred. */
124776 fts3EvalNextRow(pCsr, pLeft, pRc);
124777 fts3EvalNextRow(pCsr, pRight, pRc);
124778 while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
124779 sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
124780 if( iDiff==0 ) break;
124781 if( iDiff<0 ){
124782 fts3EvalNextRow(pCsr, pLeft, pRc);
124783 }else{
124784 fts3EvalNextRow(pCsr, pRight, pRc);
124787 pExpr->iDocid = pLeft->iDocid;
124788 pExpr->bEof = (pLeft->bEof || pRight->bEof);
124790 break;
124793 case FTSQUERY_OR: {
124794 Fts3Expr *pLeft = pExpr->pLeft;
124795 Fts3Expr *pRight = pExpr->pRight;
124796 sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
124798 assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
124799 assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
124801 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
124802 fts3EvalNextRow(pCsr, pLeft, pRc);
124803 }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
124804 fts3EvalNextRow(pCsr, pRight, pRc);
124805 }else{
124806 fts3EvalNextRow(pCsr, pLeft, pRc);
124807 fts3EvalNextRow(pCsr, pRight, pRc);
124810 pExpr->bEof = (pLeft->bEof && pRight->bEof);
124811 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
124812 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
124813 pExpr->iDocid = pLeft->iDocid;
124814 }else{
124815 pExpr->iDocid = pRight->iDocid;
124818 break;
124821 case FTSQUERY_NOT: {
124822 Fts3Expr *pLeft = pExpr->pLeft;
124823 Fts3Expr *pRight = pExpr->pRight;
124825 if( pRight->bStart==0 ){
124826 fts3EvalNextRow(pCsr, pRight, pRc);
124827 assert( *pRc!=SQLITE_OK || pRight->bStart );
124830 fts3EvalNextRow(pCsr, pLeft, pRc);
124831 if( pLeft->bEof==0 ){
124832 while( !*pRc
124833 && !pRight->bEof
124834 && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
124836 fts3EvalNextRow(pCsr, pRight, pRc);
124839 pExpr->iDocid = pLeft->iDocid;
124840 pExpr->bEof = pLeft->bEof;
124841 break;
124844 default: {
124845 Fts3Phrase *pPhrase = pExpr->pPhrase;
124846 fts3EvalInvalidatePoslist(pPhrase);
124847 *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
124848 pExpr->iDocid = pPhrase->doclist.iDocid;
124849 break;
124856 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
124857 ** cluster, then this function returns 1 immediately.
124859 ** Otherwise, it checks if the current row really does match the NEAR
124860 ** expression, using the data currently stored in the position lists
124861 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
124863 ** If the current row is a match, the position list associated with each
124864 ** phrase in the NEAR expression is edited in place to contain only those
124865 ** phrase instances sufficiently close to their peers to satisfy all NEAR
124866 ** constraints. In this case it returns 1. If the NEAR expression does not
124867 ** match the current row, 0 is returned. The position lists may or may not
124868 ** be edited if 0 is returned.
124870 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
124871 int res = 1;
124873 /* The following block runs if pExpr is the root of a NEAR query.
124874 ** For example, the query:
124876 ** "w" NEAR "x" NEAR "y" NEAR "z"
124878 ** which is represented in tree form as:
124881 ** +--NEAR--+ <-- root of NEAR query
124882 ** | |
124883 ** +--NEAR--+ "z"
124884 ** | |
124885 ** +--NEAR--+ "y"
124886 ** | |
124887 ** "w" "x"
124889 ** The right-hand child of a NEAR node is always a phrase. The
124890 ** left-hand child may be either a phrase or a NEAR node. There are
124891 ** no exceptions to this - it's the way the parser in fts3_expr.c works.
124893 if( *pRc==SQLITE_OK
124894 && pExpr->eType==FTSQUERY_NEAR
124895 && pExpr->bEof==0
124896 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
124898 Fts3Expr *p;
124899 int nTmp = 0; /* Bytes of temp space */
124900 char *aTmp; /* Temp space for PoslistNearMerge() */
124902 /* Allocate temporary working space. */
124903 for(p=pExpr; p->pLeft; p=p->pLeft){
124904 nTmp += p->pRight->pPhrase->doclist.nList;
124906 nTmp += p->pPhrase->doclist.nList;
124907 if( nTmp==0 ){
124908 res = 0;
124909 }else{
124910 aTmp = sqlite3_malloc(nTmp*2);
124911 if( !aTmp ){
124912 *pRc = SQLITE_NOMEM;
124913 res = 0;
124914 }else{
124915 char *aPoslist = p->pPhrase->doclist.pList;
124916 int nToken = p->pPhrase->nToken;
124918 for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
124919 Fts3Phrase *pPhrase = p->pRight->pPhrase;
124920 int nNear = p->nNear;
124921 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
124924 aPoslist = pExpr->pRight->pPhrase->doclist.pList;
124925 nToken = pExpr->pRight->pPhrase->nToken;
124926 for(p=pExpr->pLeft; p && res; p=p->pLeft){
124927 int nNear;
124928 Fts3Phrase *pPhrase;
124929 assert( p->pParent && p->pParent->pLeft==p );
124930 nNear = p->pParent->nNear;
124931 pPhrase = (
124932 p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
124934 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
124938 sqlite3_free(aTmp);
124942 return res;
124946 ** This function is a helper function for fts3EvalTestDeferredAndNear().
124947 ** Assuming no error occurs or has occurred, It returns non-zero if the
124948 ** expression passed as the second argument matches the row that pCsr
124949 ** currently points to, or zero if it does not.
124951 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
124952 ** If an error occurs during execution of this function, *pRc is set to
124953 ** the appropriate SQLite error code. In this case the returned value is
124954 ** undefined.
124956 static int fts3EvalTestExpr(
124957 Fts3Cursor *pCsr, /* FTS cursor handle */
124958 Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
124959 int *pRc /* IN/OUT: Error code */
124961 int bHit = 1; /* Return value */
124962 if( *pRc==SQLITE_OK ){
124963 switch( pExpr->eType ){
124964 case FTSQUERY_NEAR:
124965 case FTSQUERY_AND:
124966 bHit = (
124967 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
124968 && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
124969 && fts3EvalNearTest(pExpr, pRc)
124972 /* If the NEAR expression does not match any rows, zero the doclist for
124973 ** all phrases involved in the NEAR. This is because the snippet(),
124974 ** offsets() and matchinfo() functions are not supposed to recognize
124975 ** any instances of phrases that are part of unmatched NEAR queries.
124976 ** For example if this expression:
124978 ** ... MATCH 'a OR (b NEAR c)'
124980 ** is matched against a row containing:
124982 ** 'a b d e'
124984 ** then any snippet() should ony highlight the "a" term, not the "b"
124985 ** (as "b" is part of a non-matching NEAR clause).
124987 if( bHit==0
124988 && pExpr->eType==FTSQUERY_NEAR
124989 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
124991 Fts3Expr *p;
124992 for(p=pExpr; p->pPhrase==0; p=p->pLeft){
124993 if( p->pRight->iDocid==pCsr->iPrevId ){
124994 fts3EvalInvalidatePoslist(p->pRight->pPhrase);
124997 if( p->iDocid==pCsr->iPrevId ){
124998 fts3EvalInvalidatePoslist(p->pPhrase);
125002 break;
125004 case FTSQUERY_OR: {
125005 int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
125006 int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
125007 bHit = bHit1 || bHit2;
125008 break;
125011 case FTSQUERY_NOT:
125012 bHit = (
125013 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
125014 && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
125016 break;
125018 default: {
125019 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
125020 if( pCsr->pDeferred
125021 && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
125023 Fts3Phrase *pPhrase = pExpr->pPhrase;
125024 assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
125025 if( pExpr->bDeferred ){
125026 fts3EvalInvalidatePoslist(pPhrase);
125028 *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
125029 bHit = (pPhrase->doclist.pList!=0);
125030 pExpr->iDocid = pCsr->iPrevId;
125031 }else
125032 #endif
125034 bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
125036 break;
125040 return bHit;
125044 ** This function is called as the second part of each xNext operation when
125045 ** iterating through the results of a full-text query. At this point the
125046 ** cursor points to a row that matches the query expression, with the
125047 ** following caveats:
125049 ** * Up until this point, "NEAR" operators in the expression have been
125050 ** treated as "AND".
125052 ** * Deferred tokens have not yet been considered.
125054 ** If *pRc is not SQLITE_OK when this function is called, it immediately
125055 ** returns 0. Otherwise, it tests whether or not after considering NEAR
125056 ** operators and deferred tokens the current row is still a match for the
125057 ** expression. It returns 1 if both of the following are true:
125059 ** 1. *pRc is SQLITE_OK when this function returns, and
125061 ** 2. After scanning the current FTS table row for the deferred tokens,
125062 ** it is determined that the row does *not* match the query.
125064 ** Or, if no error occurs and it seems the current row does match the FTS
125065 ** query, return 0.
125067 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
125068 int rc = *pRc;
125069 int bMiss = 0;
125070 if( rc==SQLITE_OK ){
125072 /* If there are one or more deferred tokens, load the current row into
125073 ** memory and scan it to determine the position list for each deferred
125074 ** token. Then, see if this row is really a match, considering deferred
125075 ** tokens and NEAR operators (neither of which were taken into account
125076 ** earlier, by fts3EvalNextRow()).
125078 if( pCsr->pDeferred ){
125079 rc = fts3CursorSeek(0, pCsr);
125080 if( rc==SQLITE_OK ){
125081 rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
125084 bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
125086 /* Free the position-lists accumulated for each deferred token above. */
125087 sqlite3Fts3FreeDeferredDoclists(pCsr);
125088 *pRc = rc;
125090 return (rc==SQLITE_OK && bMiss);
125094 ** Advance to the next document that matches the FTS expression in
125095 ** Fts3Cursor.pExpr.
125097 static int fts3EvalNext(Fts3Cursor *pCsr){
125098 int rc = SQLITE_OK; /* Return Code */
125099 Fts3Expr *pExpr = pCsr->pExpr;
125100 assert( pCsr->isEof==0 );
125101 if( pExpr==0 ){
125102 pCsr->isEof = 1;
125103 }else{
125105 if( pCsr->isRequireSeek==0 ){
125106 sqlite3_reset(pCsr->pStmt);
125108 assert( sqlite3_data_count(pCsr->pStmt)==0 );
125109 fts3EvalNextRow(pCsr, pExpr, &rc);
125110 pCsr->isEof = pExpr->bEof;
125111 pCsr->isRequireSeek = 1;
125112 pCsr->isMatchinfoNeeded = 1;
125113 pCsr->iPrevId = pExpr->iDocid;
125114 }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
125116 return rc;
125120 ** Restart interation for expression pExpr so that the next call to
125121 ** fts3EvalNext() visits the first row. Do not allow incremental
125122 ** loading or merging of phrase doclists for this iteration.
125124 ** If *pRc is other than SQLITE_OK when this function is called, it is
125125 ** a no-op. If an error occurs within this function, *pRc is set to an
125126 ** SQLite error code before returning.
125128 static void fts3EvalRestart(
125129 Fts3Cursor *pCsr,
125130 Fts3Expr *pExpr,
125131 int *pRc
125133 if( pExpr && *pRc==SQLITE_OK ){
125134 Fts3Phrase *pPhrase = pExpr->pPhrase;
125136 if( pPhrase ){
125137 fts3EvalInvalidatePoslist(pPhrase);
125138 if( pPhrase->bIncr ){
125139 assert( pPhrase->nToken==1 );
125140 assert( pPhrase->aToken[0].pSegcsr );
125141 sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
125142 *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
125145 pPhrase->doclist.pNextDocid = 0;
125146 pPhrase->doclist.iDocid = 0;
125149 pExpr->iDocid = 0;
125150 pExpr->bEof = 0;
125151 pExpr->bStart = 0;
125153 fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
125154 fts3EvalRestart(pCsr, pExpr->pRight, pRc);
125159 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
125160 ** expression rooted at pExpr, the cursor iterates through all rows matched
125161 ** by pExpr, calling this function for each row. This function increments
125162 ** the values in Fts3Expr.aMI[] according to the position-list currently
125163 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
125164 ** expression nodes.
125166 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
125167 if( pExpr ){
125168 Fts3Phrase *pPhrase = pExpr->pPhrase;
125169 if( pPhrase && pPhrase->doclist.pList ){
125170 int iCol = 0;
125171 char *p = pPhrase->doclist.pList;
125173 assert( *p );
125174 while( 1 ){
125175 u8 c = 0;
125176 int iCnt = 0;
125177 while( 0xFE & (*p | c) ){
125178 if( (c&0x80)==0 ) iCnt++;
125179 c = *p++ & 0x80;
125182 /* aMI[iCol*3 + 1] = Number of occurrences
125183 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
125185 pExpr->aMI[iCol*3 + 1] += iCnt;
125186 pExpr->aMI[iCol*3 + 2] += (iCnt>0);
125187 if( *p==0x00 ) break;
125189 p += sqlite3Fts3GetVarint32(p, &iCol);
125193 fts3EvalUpdateCounts(pExpr->pLeft);
125194 fts3EvalUpdateCounts(pExpr->pRight);
125199 ** Expression pExpr must be of type FTSQUERY_PHRASE.
125201 ** If it is not already allocated and populated, this function allocates and
125202 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
125203 ** of a NEAR expression, then it also allocates and populates the same array
125204 ** for all other phrases that are part of the NEAR expression.
125206 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
125207 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
125209 static int fts3EvalGatherStats(
125210 Fts3Cursor *pCsr, /* Cursor object */
125211 Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
125213 int rc = SQLITE_OK; /* Return code */
125215 assert( pExpr->eType==FTSQUERY_PHRASE );
125216 if( pExpr->aMI==0 ){
125217 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
125218 Fts3Expr *pRoot; /* Root of NEAR expression */
125219 Fts3Expr *p; /* Iterator used for several purposes */
125221 sqlite3_int64 iPrevId = pCsr->iPrevId;
125222 sqlite3_int64 iDocid;
125223 u8 bEof;
125225 /* Find the root of the NEAR expression */
125226 pRoot = pExpr;
125227 while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
125228 pRoot = pRoot->pParent;
125230 iDocid = pRoot->iDocid;
125231 bEof = pRoot->bEof;
125232 assert( pRoot->bStart );
125234 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
125235 for(p=pRoot; p; p=p->pLeft){
125236 Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
125237 assert( pE->aMI==0 );
125238 pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
125239 if( !pE->aMI ) return SQLITE_NOMEM;
125240 memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
125243 fts3EvalRestart(pCsr, pRoot, &rc);
125245 while( pCsr->isEof==0 && rc==SQLITE_OK ){
125248 /* Ensure the %_content statement is reset. */
125249 if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
125250 assert( sqlite3_data_count(pCsr->pStmt)==0 );
125252 /* Advance to the next document */
125253 fts3EvalNextRow(pCsr, pRoot, &rc);
125254 pCsr->isEof = pRoot->bEof;
125255 pCsr->isRequireSeek = 1;
125256 pCsr->isMatchinfoNeeded = 1;
125257 pCsr->iPrevId = pRoot->iDocid;
125258 }while( pCsr->isEof==0
125259 && pRoot->eType==FTSQUERY_NEAR
125260 && fts3EvalTestDeferredAndNear(pCsr, &rc)
125263 if( rc==SQLITE_OK && pCsr->isEof==0 ){
125264 fts3EvalUpdateCounts(pRoot);
125268 pCsr->isEof = 0;
125269 pCsr->iPrevId = iPrevId;
125271 if( bEof ){
125272 pRoot->bEof = bEof;
125273 }else{
125274 /* Caution: pRoot may iterate through docids in ascending or descending
125275 ** order. For this reason, even though it seems more defensive, the
125276 ** do loop can not be written:
125278 ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
125280 fts3EvalRestart(pCsr, pRoot, &rc);
125282 fts3EvalNextRow(pCsr, pRoot, &rc);
125283 assert( pRoot->bEof==0 );
125284 }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
125285 fts3EvalTestDeferredAndNear(pCsr, &rc);
125288 return rc;
125292 ** This function is used by the matchinfo() module to query a phrase
125293 ** expression node for the following information:
125295 ** 1. The total number of occurrences of the phrase in each column of
125296 ** the FTS table (considering all rows), and
125298 ** 2. For each column, the number of rows in the table for which the
125299 ** column contains at least one instance of the phrase.
125301 ** If no error occurs, SQLITE_OK is returned and the values for each column
125302 ** written into the array aiOut as follows:
125304 ** aiOut[iCol*3 + 1] = Number of occurrences
125305 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
125307 ** Caveats:
125309 ** * If a phrase consists entirely of deferred tokens, then all output
125310 ** values are set to the number of documents in the table. In other
125311 ** words we assume that very common tokens occur exactly once in each
125312 ** column of each row of the table.
125314 ** * If a phrase contains some deferred tokens (and some non-deferred
125315 ** tokens), count the potential occurrence identified by considering
125316 ** the non-deferred tokens instead of actual phrase occurrences.
125318 ** * If the phrase is part of a NEAR expression, then only phrase instances
125319 ** that meet the NEAR constraint are included in the counts.
125321 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
125322 Fts3Cursor *pCsr, /* FTS cursor handle */
125323 Fts3Expr *pExpr, /* Phrase expression */
125324 u32 *aiOut /* Array to write results into (see above) */
125326 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
125327 int rc = SQLITE_OK;
125328 int iCol;
125330 if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
125331 assert( pCsr->nDoc>0 );
125332 for(iCol=0; iCol<pTab->nColumn; iCol++){
125333 aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
125334 aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
125336 }else{
125337 rc = fts3EvalGatherStats(pCsr, pExpr);
125338 if( rc==SQLITE_OK ){
125339 assert( pExpr->aMI );
125340 for(iCol=0; iCol<pTab->nColumn; iCol++){
125341 aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
125342 aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
125347 return rc;
125351 ** The expression pExpr passed as the second argument to this function
125352 ** must be of type FTSQUERY_PHRASE.
125354 ** The returned value is either NULL or a pointer to a buffer containing
125355 ** a position-list indicating the occurrences of the phrase in column iCol
125356 ** of the current row.
125358 ** More specifically, the returned buffer contains 1 varint for each
125359 ** occurrence of the phrase in the column, stored using the normal (delta+2)
125360 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
125361 ** if the requested column contains "a b X c d X X" and the position-list
125362 ** for 'X' is requested, the buffer returned may contain:
125364 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
125366 ** This function works regardless of whether or not the phrase is deferred,
125367 ** incremental, or neither.
125369 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
125370 Fts3Cursor *pCsr, /* FTS3 cursor object */
125371 Fts3Expr *pExpr, /* Phrase to return doclist for */
125372 int iCol, /* Column to return position list for */
125373 char **ppOut /* OUT: Pointer to position list */
125375 Fts3Phrase *pPhrase = pExpr->pPhrase;
125376 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
125377 char *pIter;
125378 int iThis;
125379 sqlite3_int64 iDocid;
125381 /* If this phrase is applies specifically to some column other than
125382 ** column iCol, return a NULL pointer. */
125383 *ppOut = 0;
125384 assert( iCol>=0 && iCol<pTab->nColumn );
125385 if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
125386 return SQLITE_OK;
125389 iDocid = pExpr->iDocid;
125390 pIter = pPhrase->doclist.pList;
125391 if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
125392 int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
125393 int bOr = 0;
125394 u8 bEof = 0;
125395 Fts3Expr *p;
125397 /* Check if this phrase descends from an OR expression node. If not,
125398 ** return NULL. Otherwise, the entry that corresponds to docid
125399 ** pCsr->iPrevId may lie earlier in the doclist buffer. */
125400 for(p=pExpr->pParent; p; p=p->pParent){
125401 if( p->eType==FTSQUERY_OR ) bOr = 1;
125403 if( bOr==0 ) return SQLITE_OK;
125405 /* This is the descendent of an OR node. In this case we cannot use
125406 ** an incremental phrase. Load the entire doclist for the phrase
125407 ** into memory in this case. */
125408 if( pPhrase->bIncr ){
125409 int rc = SQLITE_OK;
125410 int bEofSave = pExpr->bEof;
125411 fts3EvalRestart(pCsr, pExpr, &rc);
125412 while( rc==SQLITE_OK && !pExpr->bEof ){
125413 fts3EvalNextRow(pCsr, pExpr, &rc);
125414 if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
125416 pIter = pPhrase->doclist.pList;
125417 assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
125418 if( rc!=SQLITE_OK ) return rc;
125421 if( pExpr->bEof ){
125422 pIter = 0;
125423 iDocid = 0;
125425 bEof = (pPhrase->doclist.nAll==0);
125426 assert( bDescDoclist==0 || bDescDoclist==1 );
125427 assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
125429 if( pCsr->bDesc==bDescDoclist ){
125430 int dummy;
125431 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
125432 sqlite3Fts3DoclistPrev(
125433 bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
125434 &pIter, &iDocid, &dummy, &bEof
125437 }else{
125438 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
125439 sqlite3Fts3DoclistNext(
125440 bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
125441 &pIter, &iDocid, &bEof
125446 if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
125448 if( pIter==0 ) return SQLITE_OK;
125450 if( *pIter==0x01 ){
125451 pIter++;
125452 pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
125453 }else{
125454 iThis = 0;
125456 while( iThis<iCol ){
125457 fts3ColumnlistCopy(0, &pIter);
125458 if( *pIter==0x00 ) return 0;
125459 pIter++;
125460 pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
125463 *ppOut = ((iCol==iThis)?pIter:0);
125464 return SQLITE_OK;
125468 ** Free all components of the Fts3Phrase structure that were allocated by
125469 ** the eval module. Specifically, this means to free:
125471 ** * the contents of pPhrase->doclist, and
125472 ** * any Fts3MultiSegReader objects held by phrase tokens.
125474 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
125475 if( pPhrase ){
125476 int i;
125477 sqlite3_free(pPhrase->doclist.aAll);
125478 fts3EvalInvalidatePoslist(pPhrase);
125479 memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
125480 for(i=0; i<pPhrase->nToken; i++){
125481 fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
125482 pPhrase->aToken[i].pSegcsr = 0;
125489 ** Return SQLITE_CORRUPT_VTAB.
125491 #ifdef SQLITE_DEBUG
125492 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
125493 return SQLITE_CORRUPT_VTAB;
125495 #endif
125497 #if !SQLITE_CORE
125499 ** Initialize API pointer table, if required.
125501 #ifdef _WIN32
125502 __declspec(dllexport)
125503 #endif
125504 SQLITE_API int sqlite3_fts3_init(
125505 sqlite3 *db,
125506 char **pzErrMsg,
125507 const sqlite3_api_routines *pApi
125509 SQLITE_EXTENSION_INIT2(pApi)
125510 return sqlite3Fts3Init(db);
125512 #endif
125514 #endif
125516 /************** End of fts3.c ************************************************/
125517 /************** Begin file fts3_aux.c ****************************************/
125519 ** 2011 Jan 27
125521 ** The author disclaims copyright to this source code. In place of
125522 ** a legal notice, here is a blessing:
125524 ** May you do good and not evil.
125525 ** May you find forgiveness for yourself and forgive others.
125526 ** May you share freely, never taking more than you give.
125528 ******************************************************************************
125531 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125533 /* #include <string.h> */
125534 /* #include <assert.h> */
125536 typedef struct Fts3auxTable Fts3auxTable;
125537 typedef struct Fts3auxCursor Fts3auxCursor;
125539 struct Fts3auxTable {
125540 sqlite3_vtab base; /* Base class used by SQLite core */
125541 Fts3Table *pFts3Tab;
125544 struct Fts3auxCursor {
125545 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
125546 Fts3MultiSegReader csr; /* Must be right after "base" */
125547 Fts3SegFilter filter;
125548 char *zStop;
125549 int nStop; /* Byte-length of string zStop */
125550 int isEof; /* True if cursor is at EOF */
125551 sqlite3_int64 iRowid; /* Current rowid */
125553 int iCol; /* Current value of 'col' column */
125554 int nStat; /* Size of aStat[] array */
125555 struct Fts3auxColstats {
125556 sqlite3_int64 nDoc; /* 'documents' values for current csr row */
125557 sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
125558 } *aStat;
125562 ** Schema of the terms table.
125564 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
125567 ** This function does all the work for both the xConnect and xCreate methods.
125568 ** These tables have no persistent representation of their own, so xConnect
125569 ** and xCreate are identical operations.
125571 static int fts3auxConnectMethod(
125572 sqlite3 *db, /* Database connection */
125573 void *pUnused, /* Unused */
125574 int argc, /* Number of elements in argv array */
125575 const char * const *argv, /* xCreate/xConnect argument array */
125576 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
125577 char **pzErr /* OUT: sqlite3_malloc'd error message */
125579 char const *zDb; /* Name of database (e.g. "main") */
125580 char const *zFts3; /* Name of fts3 table */
125581 int nDb; /* Result of strlen(zDb) */
125582 int nFts3; /* Result of strlen(zFts3) */
125583 int nByte; /* Bytes of space to allocate here */
125584 int rc; /* value returned by declare_vtab() */
125585 Fts3auxTable *p; /* Virtual table object to return */
125587 UNUSED_PARAMETER(pUnused);
125589 /* The user should invoke this in one of two forms:
125591 ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
125592 ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
125594 if( argc!=4 && argc!=5 ) goto bad_args;
125596 zDb = argv[1];
125597 nDb = (int)strlen(zDb);
125598 if( argc==5 ){
125599 if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
125600 zDb = argv[3];
125601 nDb = (int)strlen(zDb);
125602 zFts3 = argv[4];
125603 }else{
125604 goto bad_args;
125606 }else{
125607 zFts3 = argv[3];
125609 nFts3 = (int)strlen(zFts3);
125611 rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
125612 if( rc!=SQLITE_OK ) return rc;
125614 nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
125615 p = (Fts3auxTable *)sqlite3_malloc(nByte);
125616 if( !p ) return SQLITE_NOMEM;
125617 memset(p, 0, nByte);
125619 p->pFts3Tab = (Fts3Table *)&p[1];
125620 p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
125621 p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
125622 p->pFts3Tab->db = db;
125623 p->pFts3Tab->nIndex = 1;
125625 memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
125626 memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
125627 sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
125629 *ppVtab = (sqlite3_vtab *)p;
125630 return SQLITE_OK;
125632 bad_args:
125633 *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
125634 return SQLITE_ERROR;
125638 ** This function does the work for both the xDisconnect and xDestroy methods.
125639 ** These tables have no persistent representation of their own, so xDisconnect
125640 ** and xDestroy are identical operations.
125642 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
125643 Fts3auxTable *p = (Fts3auxTable *)pVtab;
125644 Fts3Table *pFts3 = p->pFts3Tab;
125645 int i;
125647 /* Free any prepared statements held */
125648 for(i=0; i<SizeofArray(pFts3->aStmt); i++){
125649 sqlite3_finalize(pFts3->aStmt[i]);
125651 sqlite3_free(pFts3->zSegmentsTbl);
125652 sqlite3_free(p);
125653 return SQLITE_OK;
125656 #define FTS4AUX_EQ_CONSTRAINT 1
125657 #define FTS4AUX_GE_CONSTRAINT 2
125658 #define FTS4AUX_LE_CONSTRAINT 4
125661 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
125663 static int fts3auxBestIndexMethod(
125664 sqlite3_vtab *pVTab,
125665 sqlite3_index_info *pInfo
125667 int i;
125668 int iEq = -1;
125669 int iGe = -1;
125670 int iLe = -1;
125672 UNUSED_PARAMETER(pVTab);
125674 /* This vtab delivers always results in "ORDER BY term ASC" order. */
125675 if( pInfo->nOrderBy==1
125676 && pInfo->aOrderBy[0].iColumn==0
125677 && pInfo->aOrderBy[0].desc==0
125679 pInfo->orderByConsumed = 1;
125682 /* Search for equality and range constraints on the "term" column. */
125683 for(i=0; i<pInfo->nConstraint; i++){
125684 if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
125685 int op = pInfo->aConstraint[i].op;
125686 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
125687 if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
125688 if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
125689 if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
125690 if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
125694 if( iEq>=0 ){
125695 pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
125696 pInfo->aConstraintUsage[iEq].argvIndex = 1;
125697 pInfo->estimatedCost = 5;
125698 }else{
125699 pInfo->idxNum = 0;
125700 pInfo->estimatedCost = 20000;
125701 if( iGe>=0 ){
125702 pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
125703 pInfo->aConstraintUsage[iGe].argvIndex = 1;
125704 pInfo->estimatedCost /= 2;
125706 if( iLe>=0 ){
125707 pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
125708 pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
125709 pInfo->estimatedCost /= 2;
125713 return SQLITE_OK;
125717 ** xOpen - Open a cursor.
125719 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
125720 Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
125722 UNUSED_PARAMETER(pVTab);
125724 pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
125725 if( !pCsr ) return SQLITE_NOMEM;
125726 memset(pCsr, 0, sizeof(Fts3auxCursor));
125728 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
125729 return SQLITE_OK;
125733 ** xClose - Close a cursor.
125735 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
125736 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
125737 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125739 sqlite3Fts3SegmentsClose(pFts3);
125740 sqlite3Fts3SegReaderFinish(&pCsr->csr);
125741 sqlite3_free((void *)pCsr->filter.zTerm);
125742 sqlite3_free(pCsr->zStop);
125743 sqlite3_free(pCsr->aStat);
125744 sqlite3_free(pCsr);
125745 return SQLITE_OK;
125748 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
125749 if( nSize>pCsr->nStat ){
125750 struct Fts3auxColstats *aNew;
125751 aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
125752 sizeof(struct Fts3auxColstats) * nSize
125754 if( aNew==0 ) return SQLITE_NOMEM;
125755 memset(&aNew[pCsr->nStat], 0,
125756 sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
125758 pCsr->aStat = aNew;
125759 pCsr->nStat = nSize;
125761 return SQLITE_OK;
125765 ** xNext - Advance the cursor to the next row, if any.
125767 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
125768 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125769 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
125770 int rc;
125772 /* Increment our pretend rowid value. */
125773 pCsr->iRowid++;
125775 for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
125776 if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
125779 rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
125780 if( rc==SQLITE_ROW ){
125781 int i = 0;
125782 int nDoclist = pCsr->csr.nDoclist;
125783 char *aDoclist = pCsr->csr.aDoclist;
125784 int iCol;
125786 int eState = 0;
125788 if( pCsr->zStop ){
125789 int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
125790 int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
125791 if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
125792 pCsr->isEof = 1;
125793 return SQLITE_OK;
125797 if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
125798 memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
125799 iCol = 0;
125801 while( i<nDoclist ){
125802 sqlite3_int64 v = 0;
125804 i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
125805 switch( eState ){
125806 /* State 0. In this state the integer just read was a docid. */
125807 case 0:
125808 pCsr->aStat[0].nDoc++;
125809 eState = 1;
125810 iCol = 0;
125811 break;
125813 /* State 1. In this state we are expecting either a 1, indicating
125814 ** that the following integer will be a column number, or the
125815 ** start of a position list for column 0.
125817 ** The only difference between state 1 and state 2 is that if the
125818 ** integer encountered in state 1 is not 0 or 1, then we need to
125819 ** increment the column 0 "nDoc" count for this term.
125821 case 1:
125822 assert( iCol==0 );
125823 if( v>1 ){
125824 pCsr->aStat[1].nDoc++;
125826 eState = 2;
125827 /* fall through */
125829 case 2:
125830 if( v==0 ){ /* 0x00. Next integer will be a docid. */
125831 eState = 0;
125832 }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
125833 eState = 3;
125834 }else{ /* 2 or greater. A position. */
125835 pCsr->aStat[iCol+1].nOcc++;
125836 pCsr->aStat[0].nOcc++;
125838 break;
125840 /* State 3. The integer just read is a column number. */
125841 default: assert( eState==3 );
125842 iCol = (int)v;
125843 if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
125844 pCsr->aStat[iCol+1].nDoc++;
125845 eState = 2;
125846 break;
125850 pCsr->iCol = 0;
125851 rc = SQLITE_OK;
125852 }else{
125853 pCsr->isEof = 1;
125855 return rc;
125859 ** xFilter - Initialize a cursor to point at the start of its data.
125861 static int fts3auxFilterMethod(
125862 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
125863 int idxNum, /* Strategy index */
125864 const char *idxStr, /* Unused */
125865 int nVal, /* Number of elements in apVal */
125866 sqlite3_value **apVal /* Arguments for the indexing scheme */
125868 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125869 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
125870 int rc;
125871 int isScan;
125873 UNUSED_PARAMETER(nVal);
125874 UNUSED_PARAMETER(idxStr);
125876 assert( idxStr==0 );
125877 assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
125878 || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
125879 || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
125881 isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
125883 /* In case this cursor is being reused, close and zero it. */
125884 testcase(pCsr->filter.zTerm);
125885 sqlite3Fts3SegReaderFinish(&pCsr->csr);
125886 sqlite3_free((void *)pCsr->filter.zTerm);
125887 sqlite3_free(pCsr->aStat);
125888 memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
125890 pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
125891 if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
125893 if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
125894 const unsigned char *zStr = sqlite3_value_text(apVal[0]);
125895 if( zStr ){
125896 pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
125897 pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
125898 if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
125901 if( idxNum&FTS4AUX_LE_CONSTRAINT ){
125902 int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
125903 pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
125904 pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
125905 if( pCsr->zStop==0 ) return SQLITE_NOMEM;
125908 rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
125909 pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
125911 if( rc==SQLITE_OK ){
125912 rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
125915 if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
125916 return rc;
125920 ** xEof - Return true if the cursor is at EOF, or false otherwise.
125922 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
125923 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125924 return pCsr->isEof;
125928 ** xColumn - Return a column value.
125930 static int fts3auxColumnMethod(
125931 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
125932 sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
125933 int iCol /* Index of column to read value from */
125935 Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
125937 assert( p->isEof==0 );
125938 if( iCol==0 ){ /* Column "term" */
125939 sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
125940 }else if( iCol==1 ){ /* Column "col" */
125941 if( p->iCol ){
125942 sqlite3_result_int(pContext, p->iCol-1);
125943 }else{
125944 sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
125946 }else if( iCol==2 ){ /* Column "documents" */
125947 sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
125948 }else{ /* Column "occurrences" */
125949 sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
125952 return SQLITE_OK;
125956 ** xRowid - Return the current rowid for the cursor.
125958 static int fts3auxRowidMethod(
125959 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
125960 sqlite_int64 *pRowid /* OUT: Rowid value */
125962 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125963 *pRowid = pCsr->iRowid;
125964 return SQLITE_OK;
125968 ** Register the fts3aux module with database connection db. Return SQLITE_OK
125969 ** if successful or an error code if sqlite3_create_module() fails.
125971 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
125972 static const sqlite3_module fts3aux_module = {
125973 0, /* iVersion */
125974 fts3auxConnectMethod, /* xCreate */
125975 fts3auxConnectMethod, /* xConnect */
125976 fts3auxBestIndexMethod, /* xBestIndex */
125977 fts3auxDisconnectMethod, /* xDisconnect */
125978 fts3auxDisconnectMethod, /* xDestroy */
125979 fts3auxOpenMethod, /* xOpen */
125980 fts3auxCloseMethod, /* xClose */
125981 fts3auxFilterMethod, /* xFilter */
125982 fts3auxNextMethod, /* xNext */
125983 fts3auxEofMethod, /* xEof */
125984 fts3auxColumnMethod, /* xColumn */
125985 fts3auxRowidMethod, /* xRowid */
125986 0, /* xUpdate */
125987 0, /* xBegin */
125988 0, /* xSync */
125989 0, /* xCommit */
125990 0, /* xRollback */
125991 0, /* xFindFunction */
125992 0, /* xRename */
125993 0, /* xSavepoint */
125994 0, /* xRelease */
125995 0 /* xRollbackTo */
125997 int rc; /* Return code */
125999 rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
126000 return rc;
126003 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126005 /************** End of fts3_aux.c ********************************************/
126006 /************** Begin file fts3_expr.c ***************************************/
126008 ** 2008 Nov 28
126010 ** The author disclaims copyright to this source code. In place of
126011 ** a legal notice, here is a blessing:
126013 ** May you do good and not evil.
126014 ** May you find forgiveness for yourself and forgive others.
126015 ** May you share freely, never taking more than you give.
126017 ******************************************************************************
126019 ** This module contains code that implements a parser for fts3 query strings
126020 ** (the right-hand argument to the MATCH operator). Because the supported
126021 ** syntax is relatively simple, the whole tokenizer/parser system is
126022 ** hand-coded.
126024 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126027 ** By default, this module parses the legacy syntax that has been
126028 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
126029 ** is defined, then it uses the new syntax. The differences between
126030 ** the new and the old syntaxes are:
126032 ** a) The new syntax supports parenthesis. The old does not.
126034 ** b) The new syntax supports the AND and NOT operators. The old does not.
126036 ** c) The old syntax supports the "-" token qualifier. This is not
126037 ** supported by the new syntax (it is replaced by the NOT operator).
126039 ** d) When using the old syntax, the OR operator has a greater precedence
126040 ** than an implicit AND. When using the new, both implicity and explicit
126041 ** AND operators have a higher precedence than OR.
126043 ** If compiled with SQLITE_TEST defined, then this module exports the
126044 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
126045 ** to zero causes the module to use the old syntax. If it is set to
126046 ** non-zero the new syntax is activated. This is so both syntaxes can
126047 ** be tested using a single build of testfixture.
126049 ** The following describes the syntax supported by the fts3 MATCH
126050 ** operator in a similar format to that used by the lemon parser
126051 ** generator. This module does not use actually lemon, it uses a
126052 ** custom parser.
126054 ** query ::= andexpr (OR andexpr)*.
126056 ** andexpr ::= notexpr (AND? notexpr)*.
126058 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
126059 ** notexpr ::= LP query RP.
126061 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
126063 ** distance_opt ::= .
126064 ** distance_opt ::= / INTEGER.
126066 ** phrase ::= TOKEN.
126067 ** phrase ::= COLUMN:TOKEN.
126068 ** phrase ::= "TOKEN TOKEN TOKEN...".
126071 #ifdef SQLITE_TEST
126072 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
126073 #else
126074 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
126075 # define sqlite3_fts3_enable_parentheses 1
126076 # else
126077 # define sqlite3_fts3_enable_parentheses 0
126078 # endif
126079 #endif
126082 ** Default span for NEAR operators.
126084 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
126086 /* #include <string.h> */
126087 /* #include <assert.h> */
126090 ** isNot:
126091 ** This variable is used by function getNextNode(). When getNextNode() is
126092 ** called, it sets ParseContext.isNot to true if the 'next node' is a
126093 ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
126094 ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
126095 ** zero.
126097 typedef struct ParseContext ParseContext;
126098 struct ParseContext {
126099 sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
126100 int iLangid; /* Language id used with tokenizer */
126101 const char **azCol; /* Array of column names for fts3 table */
126102 int bFts4; /* True to allow FTS4-only syntax */
126103 int nCol; /* Number of entries in azCol[] */
126104 int iDefaultCol; /* Default column to query */
126105 int isNot; /* True if getNextNode() sees a unary - */
126106 sqlite3_context *pCtx; /* Write error message here */
126107 int nNest; /* Number of nested brackets */
126111 ** This function is equivalent to the standard isspace() function.
126113 ** The standard isspace() can be awkward to use safely, because although it
126114 ** is defined to accept an argument of type int, its behavior when passed
126115 ** an integer that falls outside of the range of the unsigned char type
126116 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
126117 ** is defined to accept an argument of type char, and always returns 0 for
126118 ** any values that fall outside of the range of the unsigned char type (i.e.
126119 ** negative values).
126121 static int fts3isspace(char c){
126122 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
126126 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
126127 ** zero the memory before returning a pointer to it. If unsuccessful,
126128 ** return NULL.
126130 static void *fts3MallocZero(int nByte){
126131 void *pRet = sqlite3_malloc(nByte);
126132 if( pRet ) memset(pRet, 0, nByte);
126133 return pRet;
126136 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
126137 sqlite3_tokenizer *pTokenizer,
126138 int iLangid,
126139 const char *z,
126140 int n,
126141 sqlite3_tokenizer_cursor **ppCsr
126143 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
126144 sqlite3_tokenizer_cursor *pCsr = 0;
126145 int rc;
126147 rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
126148 assert( rc==SQLITE_OK || pCsr==0 );
126149 if( rc==SQLITE_OK ){
126150 pCsr->pTokenizer = pTokenizer;
126151 if( pModule->iVersion>=1 ){
126152 rc = pModule->xLanguageid(pCsr, iLangid);
126153 if( rc!=SQLITE_OK ){
126154 pModule->xClose(pCsr);
126155 pCsr = 0;
126159 *ppCsr = pCsr;
126160 return rc;
126165 ** Extract the next token from buffer z (length n) using the tokenizer
126166 ** and other information (column names etc.) in pParse. Create an Fts3Expr
126167 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
126168 ** single token and set *ppExpr to point to it. If the end of the buffer is
126169 ** reached before a token is found, set *ppExpr to zero. It is the
126170 ** responsibility of the caller to eventually deallocate the allocated
126171 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
126173 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
126174 ** fails.
126176 static int getNextToken(
126177 ParseContext *pParse, /* fts3 query parse context */
126178 int iCol, /* Value for Fts3Phrase.iColumn */
126179 const char *z, int n, /* Input string */
126180 Fts3Expr **ppExpr, /* OUT: expression */
126181 int *pnConsumed /* OUT: Number of bytes consumed */
126183 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
126184 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
126185 int rc;
126186 sqlite3_tokenizer_cursor *pCursor;
126187 Fts3Expr *pRet = 0;
126188 int nConsumed = 0;
126190 rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
126191 if( rc==SQLITE_OK ){
126192 const char *zToken;
126193 int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
126194 int nByte; /* total space to allocate */
126196 rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
126197 if( rc==SQLITE_OK ){
126198 nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
126199 pRet = (Fts3Expr *)fts3MallocZero(nByte);
126200 if( !pRet ){
126201 rc = SQLITE_NOMEM;
126202 }else{
126203 pRet->eType = FTSQUERY_PHRASE;
126204 pRet->pPhrase = (Fts3Phrase *)&pRet[1];
126205 pRet->pPhrase->nToken = 1;
126206 pRet->pPhrase->iColumn = iCol;
126207 pRet->pPhrase->aToken[0].n = nToken;
126208 pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
126209 memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
126211 if( iEnd<n && z[iEnd]=='*' ){
126212 pRet->pPhrase->aToken[0].isPrefix = 1;
126213 iEnd++;
126216 while( 1 ){
126217 if( !sqlite3_fts3_enable_parentheses
126218 && iStart>0 && z[iStart-1]=='-'
126220 pParse->isNot = 1;
126221 iStart--;
126222 }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
126223 pRet->pPhrase->aToken[0].bFirst = 1;
126224 iStart--;
126225 }else{
126226 break;
126231 nConsumed = iEnd;
126234 pModule->xClose(pCursor);
126237 *pnConsumed = nConsumed;
126238 *ppExpr = pRet;
126239 return rc;
126244 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
126245 ** then free the old allocation.
126247 static void *fts3ReallocOrFree(void *pOrig, int nNew){
126248 void *pRet = sqlite3_realloc(pOrig, nNew);
126249 if( !pRet ){
126250 sqlite3_free(pOrig);
126252 return pRet;
126256 ** Buffer zInput, length nInput, contains the contents of a quoted string
126257 ** that appeared as part of an fts3 query expression. Neither quote character
126258 ** is included in the buffer. This function attempts to tokenize the entire
126259 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
126260 ** containing the results.
126262 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
126263 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
126264 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
126265 ** to 0.
126267 static int getNextString(
126268 ParseContext *pParse, /* fts3 query parse context */
126269 const char *zInput, int nInput, /* Input string */
126270 Fts3Expr **ppExpr /* OUT: expression */
126272 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
126273 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
126274 int rc;
126275 Fts3Expr *p = 0;
126276 sqlite3_tokenizer_cursor *pCursor = 0;
126277 char *zTemp = 0;
126278 int nTemp = 0;
126280 const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
126281 int nToken = 0;
126283 /* The final Fts3Expr data structure, including the Fts3Phrase,
126284 ** Fts3PhraseToken structures token buffers are all stored as a single
126285 ** allocation so that the expression can be freed with a single call to
126286 ** sqlite3_free(). Setting this up requires a two pass approach.
126288 ** The first pass, in the block below, uses a tokenizer cursor to iterate
126289 ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
126290 ** to assemble data in two dynamic buffers:
126292 ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
126293 ** structure, followed by the array of Fts3PhraseToken
126294 ** structures. This pass only populates the Fts3PhraseToken array.
126296 ** Buffer zTemp: Contains copies of all tokens.
126298 ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
126299 ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
126300 ** structures.
126302 rc = sqlite3Fts3OpenTokenizer(
126303 pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
126304 if( rc==SQLITE_OK ){
126305 int ii;
126306 for(ii=0; rc==SQLITE_OK; ii++){
126307 const char *zByte;
126308 int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
126309 rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
126310 if( rc==SQLITE_OK ){
126311 Fts3PhraseToken *pToken;
126313 p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
126314 if( !p ) goto no_mem;
126316 zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
126317 if( !zTemp ) goto no_mem;
126319 assert( nToken==ii );
126320 pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
126321 memset(pToken, 0, sizeof(Fts3PhraseToken));
126323 memcpy(&zTemp[nTemp], zByte, nByte);
126324 nTemp += nByte;
126326 pToken->n = nByte;
126327 pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
126328 pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
126329 nToken = ii+1;
126333 pModule->xClose(pCursor);
126334 pCursor = 0;
126337 if( rc==SQLITE_DONE ){
126338 int jj;
126339 char *zBuf = 0;
126341 p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
126342 if( !p ) goto no_mem;
126343 memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
126344 p->eType = FTSQUERY_PHRASE;
126345 p->pPhrase = (Fts3Phrase *)&p[1];
126346 p->pPhrase->iColumn = pParse->iDefaultCol;
126347 p->pPhrase->nToken = nToken;
126349 zBuf = (char *)&p->pPhrase->aToken[nToken];
126350 if( zTemp ){
126351 memcpy(zBuf, zTemp, nTemp);
126352 sqlite3_free(zTemp);
126353 }else{
126354 assert( nTemp==0 );
126357 for(jj=0; jj<p->pPhrase->nToken; jj++){
126358 p->pPhrase->aToken[jj].z = zBuf;
126359 zBuf += p->pPhrase->aToken[jj].n;
126361 rc = SQLITE_OK;
126364 *ppExpr = p;
126365 return rc;
126366 no_mem:
126368 if( pCursor ){
126369 pModule->xClose(pCursor);
126371 sqlite3_free(zTemp);
126372 sqlite3_free(p);
126373 *ppExpr = 0;
126374 return SQLITE_NOMEM;
126378 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
126379 ** call fts3ExprParse(). So this forward declaration is required.
126381 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
126384 ** The output variable *ppExpr is populated with an allocated Fts3Expr
126385 ** structure, or set to 0 if the end of the input buffer is reached.
126387 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
126388 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
126389 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
126391 static int getNextNode(
126392 ParseContext *pParse, /* fts3 query parse context */
126393 const char *z, int n, /* Input string */
126394 Fts3Expr **ppExpr, /* OUT: expression */
126395 int *pnConsumed /* OUT: Number of bytes consumed */
126397 static const struct Fts3Keyword {
126398 char *z; /* Keyword text */
126399 unsigned char n; /* Length of the keyword */
126400 unsigned char parenOnly; /* Only valid in paren mode */
126401 unsigned char eType; /* Keyword code */
126402 } aKeyword[] = {
126403 { "OR" , 2, 0, FTSQUERY_OR },
126404 { "AND", 3, 1, FTSQUERY_AND },
126405 { "NOT", 3, 1, FTSQUERY_NOT },
126406 { "NEAR", 4, 0, FTSQUERY_NEAR }
126408 int ii;
126409 int iCol;
126410 int iColLen;
126411 int rc;
126412 Fts3Expr *pRet = 0;
126414 const char *zInput = z;
126415 int nInput = n;
126417 pParse->isNot = 0;
126419 /* Skip over any whitespace before checking for a keyword, an open or
126420 ** close bracket, or a quoted string.
126422 while( nInput>0 && fts3isspace(*zInput) ){
126423 nInput--;
126424 zInput++;
126426 if( nInput==0 ){
126427 return SQLITE_DONE;
126430 /* See if we are dealing with a keyword. */
126431 for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
126432 const struct Fts3Keyword *pKey = &aKeyword[ii];
126434 if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
126435 continue;
126438 if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
126439 int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
126440 int nKey = pKey->n;
126441 char cNext;
126443 /* If this is a "NEAR" keyword, check for an explicit nearness. */
126444 if( pKey->eType==FTSQUERY_NEAR ){
126445 assert( nKey==4 );
126446 if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
126447 nNear = 0;
126448 for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
126449 nNear = nNear * 10 + (zInput[nKey] - '0');
126454 /* At this point this is probably a keyword. But for that to be true,
126455 ** the next byte must contain either whitespace, an open or close
126456 ** parenthesis, a quote character, or EOF.
126458 cNext = zInput[nKey];
126459 if( fts3isspace(cNext)
126460 || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
126462 pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
126463 if( !pRet ){
126464 return SQLITE_NOMEM;
126466 pRet->eType = pKey->eType;
126467 pRet->nNear = nNear;
126468 *ppExpr = pRet;
126469 *pnConsumed = (int)((zInput - z) + nKey);
126470 return SQLITE_OK;
126473 /* Turns out that wasn't a keyword after all. This happens if the
126474 ** user has supplied a token such as "ORacle". Continue.
126479 /* Check for an open bracket. */
126480 if( sqlite3_fts3_enable_parentheses ){
126481 if( *zInput=='(' ){
126482 int nConsumed;
126483 pParse->nNest++;
126484 rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
126485 if( rc==SQLITE_OK && !*ppExpr ){
126486 rc = SQLITE_DONE;
126488 *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
126489 return rc;
126492 /* Check for a close bracket. */
126493 if( *zInput==')' ){
126494 pParse->nNest--;
126495 *pnConsumed = (int)((zInput - z) + 1);
126496 return SQLITE_DONE;
126500 /* See if we are dealing with a quoted phrase. If this is the case, then
126501 ** search for the closing quote and pass the whole string to getNextString()
126502 ** for processing. This is easy to do, as fts3 has no syntax for escaping
126503 ** a quote character embedded in a string.
126505 if( *zInput=='"' ){
126506 for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
126507 *pnConsumed = (int)((zInput - z) + ii + 1);
126508 if( ii==nInput ){
126509 return SQLITE_ERROR;
126511 return getNextString(pParse, &zInput[1], ii-1, ppExpr);
126515 /* If control flows to this point, this must be a regular token, or
126516 ** the end of the input. Read a regular token using the sqlite3_tokenizer
126517 ** interface. Before doing so, figure out if there is an explicit
126518 ** column specifier for the token.
126520 ** TODO: Strangely, it is not possible to associate a column specifier
126521 ** with a quoted phrase, only with a single token. Not sure if this was
126522 ** an implementation artifact or an intentional decision when fts3 was
126523 ** first implemented. Whichever it was, this module duplicates the
126524 ** limitation.
126526 iCol = pParse->iDefaultCol;
126527 iColLen = 0;
126528 for(ii=0; ii<pParse->nCol; ii++){
126529 const char *zStr = pParse->azCol[ii];
126530 int nStr = (int)strlen(zStr);
126531 if( nInput>nStr && zInput[nStr]==':'
126532 && sqlite3_strnicmp(zStr, zInput, nStr)==0
126534 iCol = ii;
126535 iColLen = (int)((zInput - z) + nStr + 1);
126536 break;
126539 rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
126540 *pnConsumed += iColLen;
126541 return rc;
126545 ** The argument is an Fts3Expr structure for a binary operator (any type
126546 ** except an FTSQUERY_PHRASE). Return an integer value representing the
126547 ** precedence of the operator. Lower values have a higher precedence (i.e.
126548 ** group more tightly). For example, in the C language, the == operator
126549 ** groups more tightly than ||, and would therefore have a higher precedence.
126551 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
126552 ** is defined), the order of the operators in precedence from highest to
126553 ** lowest is:
126555 ** NEAR
126556 ** NOT
126557 ** AND (including implicit ANDs)
126558 ** OR
126560 ** Note that when using the old query syntax, the OR operator has a higher
126561 ** precedence than the AND operator.
126563 static int opPrecedence(Fts3Expr *p){
126564 assert( p->eType!=FTSQUERY_PHRASE );
126565 if( sqlite3_fts3_enable_parentheses ){
126566 return p->eType;
126567 }else if( p->eType==FTSQUERY_NEAR ){
126568 return 1;
126569 }else if( p->eType==FTSQUERY_OR ){
126570 return 2;
126572 assert( p->eType==FTSQUERY_AND );
126573 return 3;
126577 ** Argument ppHead contains a pointer to the current head of a query
126578 ** expression tree being parsed. pPrev is the expression node most recently
126579 ** inserted into the tree. This function adds pNew, which is always a binary
126580 ** operator node, into the expression tree based on the relative precedence
126581 ** of pNew and the existing nodes of the tree. This may result in the head
126582 ** of the tree changing, in which case *ppHead is set to the new root node.
126584 static void insertBinaryOperator(
126585 Fts3Expr **ppHead, /* Pointer to the root node of a tree */
126586 Fts3Expr *pPrev, /* Node most recently inserted into the tree */
126587 Fts3Expr *pNew /* New binary node to insert into expression tree */
126589 Fts3Expr *pSplit = pPrev;
126590 while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
126591 pSplit = pSplit->pParent;
126594 if( pSplit->pParent ){
126595 assert( pSplit->pParent->pRight==pSplit );
126596 pSplit->pParent->pRight = pNew;
126597 pNew->pParent = pSplit->pParent;
126598 }else{
126599 *ppHead = pNew;
126601 pNew->pLeft = pSplit;
126602 pSplit->pParent = pNew;
126606 ** Parse the fts3 query expression found in buffer z, length n. This function
126607 ** returns either when the end of the buffer is reached or an unmatched
126608 ** closing bracket - ')' - is encountered.
126610 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
126611 ** parsed form of the expression and *pnConsumed is set to the number of
126612 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
126613 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
126615 static int fts3ExprParse(
126616 ParseContext *pParse, /* fts3 query parse context */
126617 const char *z, int n, /* Text of MATCH query */
126618 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
126619 int *pnConsumed /* OUT: Number of bytes consumed */
126621 Fts3Expr *pRet = 0;
126622 Fts3Expr *pPrev = 0;
126623 Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
126624 int nIn = n;
126625 const char *zIn = z;
126626 int rc = SQLITE_OK;
126627 int isRequirePhrase = 1;
126629 while( rc==SQLITE_OK ){
126630 Fts3Expr *p = 0;
126631 int nByte = 0;
126632 rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
126633 if( rc==SQLITE_OK ){
126634 int isPhrase;
126636 if( !sqlite3_fts3_enable_parentheses
126637 && p->eType==FTSQUERY_PHRASE && pParse->isNot
126639 /* Create an implicit NOT operator. */
126640 Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
126641 if( !pNot ){
126642 sqlite3Fts3ExprFree(p);
126643 rc = SQLITE_NOMEM;
126644 goto exprparse_out;
126646 pNot->eType = FTSQUERY_NOT;
126647 pNot->pRight = p;
126648 p->pParent = pNot;
126649 if( pNotBranch ){
126650 pNot->pLeft = pNotBranch;
126651 pNotBranch->pParent = pNot;
126653 pNotBranch = pNot;
126654 p = pPrev;
126655 }else{
126656 int eType = p->eType;
126657 isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
126659 /* The isRequirePhrase variable is set to true if a phrase or
126660 ** an expression contained in parenthesis is required. If a
126661 ** binary operator (AND, OR, NOT or NEAR) is encounted when
126662 ** isRequirePhrase is set, this is a syntax error.
126664 if( !isPhrase && isRequirePhrase ){
126665 sqlite3Fts3ExprFree(p);
126666 rc = SQLITE_ERROR;
126667 goto exprparse_out;
126670 if( isPhrase && !isRequirePhrase ){
126671 /* Insert an implicit AND operator. */
126672 Fts3Expr *pAnd;
126673 assert( pRet && pPrev );
126674 pAnd = fts3MallocZero(sizeof(Fts3Expr));
126675 if( !pAnd ){
126676 sqlite3Fts3ExprFree(p);
126677 rc = SQLITE_NOMEM;
126678 goto exprparse_out;
126680 pAnd->eType = FTSQUERY_AND;
126681 insertBinaryOperator(&pRet, pPrev, pAnd);
126682 pPrev = pAnd;
126685 /* This test catches attempts to make either operand of a NEAR
126686 ** operator something other than a phrase. For example, either of
126687 ** the following:
126689 ** (bracketed expression) NEAR phrase
126690 ** phrase NEAR (bracketed expression)
126692 ** Return an error in either case.
126694 if( pPrev && (
126695 (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
126696 || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
126698 sqlite3Fts3ExprFree(p);
126699 rc = SQLITE_ERROR;
126700 goto exprparse_out;
126703 if( isPhrase ){
126704 if( pRet ){
126705 assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
126706 pPrev->pRight = p;
126707 p->pParent = pPrev;
126708 }else{
126709 pRet = p;
126711 }else{
126712 insertBinaryOperator(&pRet, pPrev, p);
126714 isRequirePhrase = !isPhrase;
126716 assert( nByte>0 );
126718 assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
126719 nIn -= nByte;
126720 zIn += nByte;
126721 pPrev = p;
126724 if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
126725 rc = SQLITE_ERROR;
126728 if( rc==SQLITE_DONE ){
126729 rc = SQLITE_OK;
126730 if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
126731 if( !pRet ){
126732 rc = SQLITE_ERROR;
126733 }else{
126734 Fts3Expr *pIter = pNotBranch;
126735 while( pIter->pLeft ){
126736 pIter = pIter->pLeft;
126738 pIter->pLeft = pRet;
126739 pRet->pParent = pIter;
126740 pRet = pNotBranch;
126744 *pnConsumed = n - nIn;
126746 exprparse_out:
126747 if( rc!=SQLITE_OK ){
126748 sqlite3Fts3ExprFree(pRet);
126749 sqlite3Fts3ExprFree(pNotBranch);
126750 pRet = 0;
126752 *ppExpr = pRet;
126753 return rc;
126757 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
126758 ** as the only argument is more than nMaxDepth.
126760 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
126761 int rc = SQLITE_OK;
126762 if( p ){
126763 if( nMaxDepth<0 ){
126764 rc = SQLITE_TOOBIG;
126765 }else{
126766 rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
126767 if( rc==SQLITE_OK ){
126768 rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
126772 return rc;
126776 ** This function attempts to transform the expression tree at (*pp) to
126777 ** an equivalent but more balanced form. The tree is modified in place.
126778 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
126779 ** new root expression node.
126781 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
126783 ** Otherwise, if an error occurs, an SQLite error code is returned and
126784 ** expression (*pp) freed.
126786 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
126787 int rc = SQLITE_OK; /* Return code */
126788 Fts3Expr *pRoot = *pp; /* Initial root node */
126789 Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
126790 int eType = pRoot->eType; /* Type of node in this tree */
126792 if( nMaxDepth==0 ){
126793 rc = SQLITE_ERROR;
126796 if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
126797 Fts3Expr **apLeaf;
126798 apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
126799 if( 0==apLeaf ){
126800 rc = SQLITE_NOMEM;
126801 }else{
126802 memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
126805 if( rc==SQLITE_OK ){
126806 int i;
126807 Fts3Expr *p;
126809 /* Set $p to point to the left-most leaf in the tree of eType nodes. */
126810 for(p=pRoot; p->eType==eType; p=p->pLeft){
126811 assert( p->pParent==0 || p->pParent->pLeft==p );
126812 assert( p->pLeft && p->pRight );
126815 /* This loop runs once for each leaf in the tree of eType nodes. */
126816 while( 1 ){
126817 int iLvl;
126818 Fts3Expr *pParent = p->pParent; /* Current parent of p */
126820 assert( pParent==0 || pParent->pLeft==p );
126821 p->pParent = 0;
126822 if( pParent ){
126823 pParent->pLeft = 0;
126824 }else{
126825 pRoot = 0;
126827 rc = fts3ExprBalance(&p, nMaxDepth-1);
126828 if( rc!=SQLITE_OK ) break;
126830 for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
126831 if( apLeaf[iLvl]==0 ){
126832 apLeaf[iLvl] = p;
126833 p = 0;
126834 }else{
126835 assert( pFree );
126836 pFree->pLeft = apLeaf[iLvl];
126837 pFree->pRight = p;
126838 pFree->pLeft->pParent = pFree;
126839 pFree->pRight->pParent = pFree;
126841 p = pFree;
126842 pFree = pFree->pParent;
126843 p->pParent = 0;
126844 apLeaf[iLvl] = 0;
126847 if( p ){
126848 sqlite3Fts3ExprFree(p);
126849 rc = SQLITE_TOOBIG;
126850 break;
126853 /* If that was the last leaf node, break out of the loop */
126854 if( pParent==0 ) break;
126856 /* Set $p to point to the next leaf in the tree of eType nodes */
126857 for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
126859 /* Remove pParent from the original tree. */
126860 assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
126861 pParent->pRight->pParent = pParent->pParent;
126862 if( pParent->pParent ){
126863 pParent->pParent->pLeft = pParent->pRight;
126864 }else{
126865 assert( pParent==pRoot );
126866 pRoot = pParent->pRight;
126869 /* Link pParent into the free node list. It will be used as an
126870 ** internal node of the new tree. */
126871 pParent->pParent = pFree;
126872 pFree = pParent;
126875 if( rc==SQLITE_OK ){
126876 p = 0;
126877 for(i=0; i<nMaxDepth; i++){
126878 if( apLeaf[i] ){
126879 if( p==0 ){
126880 p = apLeaf[i];
126881 p->pParent = 0;
126882 }else{
126883 assert( pFree!=0 );
126884 pFree->pRight = p;
126885 pFree->pLeft = apLeaf[i];
126886 pFree->pLeft->pParent = pFree;
126887 pFree->pRight->pParent = pFree;
126889 p = pFree;
126890 pFree = pFree->pParent;
126891 p->pParent = 0;
126895 pRoot = p;
126896 }else{
126897 /* An error occurred. Delete the contents of the apLeaf[] array
126898 ** and pFree list. Everything else is cleaned up by the call to
126899 ** sqlite3Fts3ExprFree(pRoot) below. */
126900 Fts3Expr *pDel;
126901 for(i=0; i<nMaxDepth; i++){
126902 sqlite3Fts3ExprFree(apLeaf[i]);
126904 while( (pDel=pFree)!=0 ){
126905 pFree = pDel->pParent;
126906 sqlite3_free(pDel);
126910 assert( pFree==0 );
126911 sqlite3_free( apLeaf );
126915 if( rc!=SQLITE_OK ){
126916 sqlite3Fts3ExprFree(pRoot);
126917 pRoot = 0;
126919 *pp = pRoot;
126920 return rc;
126924 ** This function is similar to sqlite3Fts3ExprParse(), with the following
126925 ** differences:
126927 ** 1. It does not do expression rebalancing.
126928 ** 2. It does not check that the expression does not exceed the
126929 ** maximum allowable depth.
126930 ** 3. Even if it fails, *ppExpr may still be set to point to an
126931 ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
126932 ** in this case.
126934 static int fts3ExprParseUnbalanced(
126935 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
126936 int iLangid, /* Language id for tokenizer */
126937 char **azCol, /* Array of column names for fts3 table */
126938 int bFts4, /* True to allow FTS4-only syntax */
126939 int nCol, /* Number of entries in azCol[] */
126940 int iDefaultCol, /* Default column to query */
126941 const char *z, int n, /* Text of MATCH query */
126942 Fts3Expr **ppExpr /* OUT: Parsed query structure */
126944 int nParsed;
126945 int rc;
126946 ParseContext sParse;
126948 memset(&sParse, 0, sizeof(ParseContext));
126949 sParse.pTokenizer = pTokenizer;
126950 sParse.iLangid = iLangid;
126951 sParse.azCol = (const char **)azCol;
126952 sParse.nCol = nCol;
126953 sParse.iDefaultCol = iDefaultCol;
126954 sParse.bFts4 = bFts4;
126955 if( z==0 ){
126956 *ppExpr = 0;
126957 return SQLITE_OK;
126959 if( n<0 ){
126960 n = (int)strlen(z);
126962 rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
126963 assert( rc==SQLITE_OK || *ppExpr==0 );
126965 /* Check for mismatched parenthesis */
126966 if( rc==SQLITE_OK && sParse.nNest ){
126967 rc = SQLITE_ERROR;
126970 return rc;
126974 ** Parameters z and n contain a pointer to and length of a buffer containing
126975 ** an fts3 query expression, respectively. This function attempts to parse the
126976 ** query expression and create a tree of Fts3Expr structures representing the
126977 ** parsed expression. If successful, *ppExpr is set to point to the head
126978 ** of the parsed expression tree and SQLITE_OK is returned. If an error
126979 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
126980 ** error) is returned and *ppExpr is set to 0.
126982 ** If parameter n is a negative number, then z is assumed to point to a
126983 ** nul-terminated string and the length is determined using strlen().
126985 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
126986 ** use to normalize query tokens while parsing the expression. The azCol[]
126987 ** array, which is assumed to contain nCol entries, should contain the names
126988 ** of each column in the target fts3 table, in order from left to right.
126989 ** Column names must be nul-terminated strings.
126991 ** The iDefaultCol parameter should be passed the index of the table column
126992 ** that appears on the left-hand-side of the MATCH operator (the default
126993 ** column to match against for tokens for which a column name is not explicitly
126994 ** specified as part of the query string), or -1 if tokens may by default
126995 ** match any table column.
126997 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
126998 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
126999 int iLangid, /* Language id for tokenizer */
127000 char **azCol, /* Array of column names for fts3 table */
127001 int bFts4, /* True to allow FTS4-only syntax */
127002 int nCol, /* Number of entries in azCol[] */
127003 int iDefaultCol, /* Default column to query */
127004 const char *z, int n, /* Text of MATCH query */
127005 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
127006 char **pzErr /* OUT: Error message (sqlite3_malloc) */
127008 int rc = fts3ExprParseUnbalanced(
127009 pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
127012 /* Rebalance the expression. And check that its depth does not exceed
127013 ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
127014 if( rc==SQLITE_OK && *ppExpr ){
127015 rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
127016 if( rc==SQLITE_OK ){
127017 rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
127021 if( rc!=SQLITE_OK ){
127022 sqlite3Fts3ExprFree(*ppExpr);
127023 *ppExpr = 0;
127024 if( rc==SQLITE_TOOBIG ){
127025 *pzErr = sqlite3_mprintf(
127026 "FTS expression tree is too large (maximum depth %d)",
127027 SQLITE_FTS3_MAX_EXPR_DEPTH
127029 rc = SQLITE_ERROR;
127030 }else if( rc==SQLITE_ERROR ){
127031 *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
127035 return rc;
127039 ** Free a single node of an expression tree.
127041 static void fts3FreeExprNode(Fts3Expr *p){
127042 assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
127043 sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
127044 sqlite3_free(p->aMI);
127045 sqlite3_free(p);
127049 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
127051 ** This function would be simpler if it recursively called itself. But
127052 ** that would mean passing a sufficiently large expression to ExprParse()
127053 ** could cause a stack overflow.
127055 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
127056 Fts3Expr *p;
127057 assert( pDel==0 || pDel->pParent==0 );
127058 for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
127059 assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
127061 while( p ){
127062 Fts3Expr *pParent = p->pParent;
127063 fts3FreeExprNode(p);
127064 if( pParent && p==pParent->pLeft && pParent->pRight ){
127065 p = pParent->pRight;
127066 while( p && (p->pLeft || p->pRight) ){
127067 assert( p==p->pParent->pRight || p==p->pParent->pLeft );
127068 p = (p->pLeft ? p->pLeft : p->pRight);
127070 }else{
127071 p = pParent;
127076 /****************************************************************************
127077 *****************************************************************************
127078 ** Everything after this point is just test code.
127081 #ifdef SQLITE_TEST
127083 /* #include <stdio.h> */
127086 ** Function to query the hash-table of tokenizers (see README.tokenizers).
127088 static int queryTestTokenizer(
127089 sqlite3 *db,
127090 const char *zName,
127091 const sqlite3_tokenizer_module **pp
127093 int rc;
127094 sqlite3_stmt *pStmt;
127095 const char zSql[] = "SELECT fts3_tokenizer(?)";
127097 *pp = 0;
127098 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
127099 if( rc!=SQLITE_OK ){
127100 return rc;
127103 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
127104 if( SQLITE_ROW==sqlite3_step(pStmt) ){
127105 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
127106 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
127110 return sqlite3_finalize(pStmt);
127114 ** Return a pointer to a buffer containing a text representation of the
127115 ** expression passed as the first argument. The buffer is obtained from
127116 ** sqlite3_malloc(). It is the responsibility of the caller to use
127117 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
127118 ** NULL is returned.
127120 ** If the second argument is not NULL, then its contents are prepended to
127121 ** the returned expression text and then freed using sqlite3_free().
127123 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
127124 if( pExpr==0 ){
127125 return sqlite3_mprintf("");
127127 switch( pExpr->eType ){
127128 case FTSQUERY_PHRASE: {
127129 Fts3Phrase *pPhrase = pExpr->pPhrase;
127130 int i;
127131 zBuf = sqlite3_mprintf(
127132 "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
127133 for(i=0; zBuf && i<pPhrase->nToken; i++){
127134 zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
127135 pPhrase->aToken[i].n, pPhrase->aToken[i].z,
127136 (pPhrase->aToken[i].isPrefix?"+":"")
127139 return zBuf;
127142 case FTSQUERY_NEAR:
127143 zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
127144 break;
127145 case FTSQUERY_NOT:
127146 zBuf = sqlite3_mprintf("%zNOT ", zBuf);
127147 break;
127148 case FTSQUERY_AND:
127149 zBuf = sqlite3_mprintf("%zAND ", zBuf);
127150 break;
127151 case FTSQUERY_OR:
127152 zBuf = sqlite3_mprintf("%zOR ", zBuf);
127153 break;
127156 if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
127157 if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
127158 if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
127160 if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
127161 if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
127163 return zBuf;
127167 ** This is the implementation of a scalar SQL function used to test the
127168 ** expression parser. It should be called as follows:
127170 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
127172 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
127173 ** to parse the query expression (see README.tokenizers). The second argument
127174 ** is the query expression to parse. Each subsequent argument is the name
127175 ** of a column of the fts3 table that the query expression may refer to.
127176 ** For example:
127178 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
127180 static void fts3ExprTest(
127181 sqlite3_context *context,
127182 int argc,
127183 sqlite3_value **argv
127185 sqlite3_tokenizer_module const *pModule = 0;
127186 sqlite3_tokenizer *pTokenizer = 0;
127187 int rc;
127188 char **azCol = 0;
127189 const char *zExpr;
127190 int nExpr;
127191 int nCol;
127192 int ii;
127193 Fts3Expr *pExpr;
127194 char *zBuf = 0;
127195 sqlite3 *db = sqlite3_context_db_handle(context);
127197 if( argc<3 ){
127198 sqlite3_result_error(context,
127199 "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
127201 return;
127204 rc = queryTestTokenizer(db,
127205 (const char *)sqlite3_value_text(argv[0]), &pModule);
127206 if( rc==SQLITE_NOMEM ){
127207 sqlite3_result_error_nomem(context);
127208 goto exprtest_out;
127209 }else if( !pModule ){
127210 sqlite3_result_error(context, "No such tokenizer module", -1);
127211 goto exprtest_out;
127214 rc = pModule->xCreate(0, 0, &pTokenizer);
127215 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
127216 if( rc==SQLITE_NOMEM ){
127217 sqlite3_result_error_nomem(context);
127218 goto exprtest_out;
127220 pTokenizer->pModule = pModule;
127222 zExpr = (const char *)sqlite3_value_text(argv[1]);
127223 nExpr = sqlite3_value_bytes(argv[1]);
127224 nCol = argc-2;
127225 azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
127226 if( !azCol ){
127227 sqlite3_result_error_nomem(context);
127228 goto exprtest_out;
127230 for(ii=0; ii<nCol; ii++){
127231 azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
127234 if( sqlite3_user_data(context) ){
127235 char *zDummy = 0;
127236 rc = sqlite3Fts3ExprParse(
127237 pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
127239 assert( rc==SQLITE_OK || pExpr==0 );
127240 sqlite3_free(zDummy);
127241 }else{
127242 rc = fts3ExprParseUnbalanced(
127243 pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
127247 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
127248 sqlite3Fts3ExprFree(pExpr);
127249 sqlite3_result_error(context, "Error parsing expression", -1);
127250 }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
127251 sqlite3_result_error_nomem(context);
127252 }else{
127253 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
127254 sqlite3_free(zBuf);
127257 sqlite3Fts3ExprFree(pExpr);
127259 exprtest_out:
127260 if( pModule && pTokenizer ){
127261 rc = pModule->xDestroy(pTokenizer);
127263 sqlite3_free(azCol);
127267 ** Register the query expression parser test function fts3_exprtest()
127268 ** with database connection db.
127270 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
127271 int rc = sqlite3_create_function(
127272 db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
127274 if( rc==SQLITE_OK ){
127275 rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
127276 -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
127279 return rc;
127282 #endif
127283 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
127285 /************** End of fts3_expr.c *******************************************/
127286 /************** Begin file fts3_hash.c ***************************************/
127288 ** 2001 September 22
127290 ** The author disclaims copyright to this source code. In place of
127291 ** a legal notice, here is a blessing:
127293 ** May you do good and not evil.
127294 ** May you find forgiveness for yourself and forgive others.
127295 ** May you share freely, never taking more than you give.
127297 *************************************************************************
127298 ** This is the implementation of generic hash-tables used in SQLite.
127299 ** We've modified it slightly to serve as a standalone hash table
127300 ** implementation for the full-text indexing module.
127304 ** The code in this file is only compiled if:
127306 ** * The FTS3 module is being built as an extension
127307 ** (in which case SQLITE_CORE is not defined), or
127309 ** * The FTS3 module is being built into the core of
127310 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
127312 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
127314 /* #include <assert.h> */
127315 /* #include <stdlib.h> */
127316 /* #include <string.h> */
127320 ** Malloc and Free functions
127322 static void *fts3HashMalloc(int n){
127323 void *p = sqlite3_malloc(n);
127324 if( p ){
127325 memset(p, 0, n);
127327 return p;
127329 static void fts3HashFree(void *p){
127330 sqlite3_free(p);
127333 /* Turn bulk memory into a hash table object by initializing the
127334 ** fields of the Hash structure.
127336 ** "pNew" is a pointer to the hash table that is to be initialized.
127337 ** keyClass is one of the constants
127338 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
127339 ** determines what kind of key the hash table will use. "copyKey" is
127340 ** true if the hash table should make its own private copy of keys and
127341 ** false if it should just use the supplied pointer.
127343 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
127344 assert( pNew!=0 );
127345 assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
127346 pNew->keyClass = keyClass;
127347 pNew->copyKey = copyKey;
127348 pNew->first = 0;
127349 pNew->count = 0;
127350 pNew->htsize = 0;
127351 pNew->ht = 0;
127354 /* Remove all entries from a hash table. Reclaim all memory.
127355 ** Call this routine to delete a hash table or to reset a hash table
127356 ** to the empty state.
127358 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
127359 Fts3HashElem *elem; /* For looping over all elements of the table */
127361 assert( pH!=0 );
127362 elem = pH->first;
127363 pH->first = 0;
127364 fts3HashFree(pH->ht);
127365 pH->ht = 0;
127366 pH->htsize = 0;
127367 while( elem ){
127368 Fts3HashElem *next_elem = elem->next;
127369 if( pH->copyKey && elem->pKey ){
127370 fts3HashFree(elem->pKey);
127372 fts3HashFree(elem);
127373 elem = next_elem;
127375 pH->count = 0;
127379 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
127381 static int fts3StrHash(const void *pKey, int nKey){
127382 const char *z = (const char *)pKey;
127383 int h = 0;
127384 if( nKey<=0 ) nKey = (int) strlen(z);
127385 while( nKey > 0 ){
127386 h = (h<<3) ^ h ^ *z++;
127387 nKey--;
127389 return h & 0x7fffffff;
127391 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
127392 if( n1!=n2 ) return 1;
127393 return strncmp((const char*)pKey1,(const char*)pKey2,n1);
127397 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
127399 static int fts3BinHash(const void *pKey, int nKey){
127400 int h = 0;
127401 const char *z = (const char *)pKey;
127402 while( nKey-- > 0 ){
127403 h = (h<<3) ^ h ^ *(z++);
127405 return h & 0x7fffffff;
127407 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
127408 if( n1!=n2 ) return 1;
127409 return memcmp(pKey1,pKey2,n1);
127413 ** Return a pointer to the appropriate hash function given the key class.
127415 ** The C syntax in this function definition may be unfamilar to some
127416 ** programmers, so we provide the following additional explanation:
127418 ** The name of the function is "ftsHashFunction". The function takes a
127419 ** single parameter "keyClass". The return value of ftsHashFunction()
127420 ** is a pointer to another function. Specifically, the return value
127421 ** of ftsHashFunction() is a pointer to a function that takes two parameters
127422 ** with types "const void*" and "int" and returns an "int".
127424 static int (*ftsHashFunction(int keyClass))(const void*,int){
127425 if( keyClass==FTS3_HASH_STRING ){
127426 return &fts3StrHash;
127427 }else{
127428 assert( keyClass==FTS3_HASH_BINARY );
127429 return &fts3BinHash;
127434 ** Return a pointer to the appropriate hash function given the key class.
127436 ** For help in interpreted the obscure C code in the function definition,
127437 ** see the header comment on the previous function.
127439 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
127440 if( keyClass==FTS3_HASH_STRING ){
127441 return &fts3StrCompare;
127442 }else{
127443 assert( keyClass==FTS3_HASH_BINARY );
127444 return &fts3BinCompare;
127448 /* Link an element into the hash table
127450 static void fts3HashInsertElement(
127451 Fts3Hash *pH, /* The complete hash table */
127452 struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
127453 Fts3HashElem *pNew /* The element to be inserted */
127455 Fts3HashElem *pHead; /* First element already in pEntry */
127456 pHead = pEntry->chain;
127457 if( pHead ){
127458 pNew->next = pHead;
127459 pNew->prev = pHead->prev;
127460 if( pHead->prev ){ pHead->prev->next = pNew; }
127461 else { pH->first = pNew; }
127462 pHead->prev = pNew;
127463 }else{
127464 pNew->next = pH->first;
127465 if( pH->first ){ pH->first->prev = pNew; }
127466 pNew->prev = 0;
127467 pH->first = pNew;
127469 pEntry->count++;
127470 pEntry->chain = pNew;
127474 /* Resize the hash table so that it cantains "new_size" buckets.
127475 ** "new_size" must be a power of 2. The hash table might fail
127476 ** to resize if sqliteMalloc() fails.
127478 ** Return non-zero if a memory allocation error occurs.
127480 static int fts3Rehash(Fts3Hash *pH, int new_size){
127481 struct _fts3ht *new_ht; /* The new hash table */
127482 Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
127483 int (*xHash)(const void*,int); /* The hash function */
127485 assert( (new_size & (new_size-1))==0 );
127486 new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
127487 if( new_ht==0 ) return 1;
127488 fts3HashFree(pH->ht);
127489 pH->ht = new_ht;
127490 pH->htsize = new_size;
127491 xHash = ftsHashFunction(pH->keyClass);
127492 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
127493 int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
127494 next_elem = elem->next;
127495 fts3HashInsertElement(pH, &new_ht[h], elem);
127497 return 0;
127500 /* This function (for internal use only) locates an element in an
127501 ** hash table that matches the given key. The hash for this key has
127502 ** already been computed and is passed as the 4th parameter.
127504 static Fts3HashElem *fts3FindElementByHash(
127505 const Fts3Hash *pH, /* The pH to be searched */
127506 const void *pKey, /* The key we are searching for */
127507 int nKey,
127508 int h /* The hash for this key. */
127510 Fts3HashElem *elem; /* Used to loop thru the element list */
127511 int count; /* Number of elements left to test */
127512 int (*xCompare)(const void*,int,const void*,int); /* comparison function */
127514 if( pH->ht ){
127515 struct _fts3ht *pEntry = &pH->ht[h];
127516 elem = pEntry->chain;
127517 count = pEntry->count;
127518 xCompare = ftsCompareFunction(pH->keyClass);
127519 while( count-- && elem ){
127520 if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
127521 return elem;
127523 elem = elem->next;
127526 return 0;
127529 /* Remove a single entry from the hash table given a pointer to that
127530 ** element and a hash on the element's key.
127532 static void fts3RemoveElementByHash(
127533 Fts3Hash *pH, /* The pH containing "elem" */
127534 Fts3HashElem* elem, /* The element to be removed from the pH */
127535 int h /* Hash value for the element */
127537 struct _fts3ht *pEntry;
127538 if( elem->prev ){
127539 elem->prev->next = elem->next;
127540 }else{
127541 pH->first = elem->next;
127543 if( elem->next ){
127544 elem->next->prev = elem->prev;
127546 pEntry = &pH->ht[h];
127547 if( pEntry->chain==elem ){
127548 pEntry->chain = elem->next;
127550 pEntry->count--;
127551 if( pEntry->count<=0 ){
127552 pEntry->chain = 0;
127554 if( pH->copyKey && elem->pKey ){
127555 fts3HashFree(elem->pKey);
127557 fts3HashFree( elem );
127558 pH->count--;
127559 if( pH->count<=0 ){
127560 assert( pH->first==0 );
127561 assert( pH->count==0 );
127562 fts3HashClear(pH);
127566 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
127567 const Fts3Hash *pH,
127568 const void *pKey,
127569 int nKey
127571 int h; /* A hash on key */
127572 int (*xHash)(const void*,int); /* The hash function */
127574 if( pH==0 || pH->ht==0 ) return 0;
127575 xHash = ftsHashFunction(pH->keyClass);
127576 assert( xHash!=0 );
127577 h = (*xHash)(pKey,nKey);
127578 assert( (pH->htsize & (pH->htsize-1))==0 );
127579 return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
127583 ** Attempt to locate an element of the hash table pH with a key
127584 ** that matches pKey,nKey. Return the data for this element if it is
127585 ** found, or NULL if there is no match.
127587 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
127588 Fts3HashElem *pElem; /* The element that matches key (if any) */
127590 pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
127591 return pElem ? pElem->data : 0;
127594 /* Insert an element into the hash table pH. The key is pKey,nKey
127595 ** and the data is "data".
127597 ** If no element exists with a matching key, then a new
127598 ** element is created. A copy of the key is made if the copyKey
127599 ** flag is set. NULL is returned.
127601 ** If another element already exists with the same key, then the
127602 ** new data replaces the old data and the old data is returned.
127603 ** The key is not copied in this instance. If a malloc fails, then
127604 ** the new data is returned and the hash table is unchanged.
127606 ** If the "data" parameter to this function is NULL, then the
127607 ** element corresponding to "key" is removed from the hash table.
127609 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
127610 Fts3Hash *pH, /* The hash table to insert into */
127611 const void *pKey, /* The key */
127612 int nKey, /* Number of bytes in the key */
127613 void *data /* The data */
127615 int hraw; /* Raw hash value of the key */
127616 int h; /* the hash of the key modulo hash table size */
127617 Fts3HashElem *elem; /* Used to loop thru the element list */
127618 Fts3HashElem *new_elem; /* New element added to the pH */
127619 int (*xHash)(const void*,int); /* The hash function */
127621 assert( pH!=0 );
127622 xHash = ftsHashFunction(pH->keyClass);
127623 assert( xHash!=0 );
127624 hraw = (*xHash)(pKey, nKey);
127625 assert( (pH->htsize & (pH->htsize-1))==0 );
127626 h = hraw & (pH->htsize-1);
127627 elem = fts3FindElementByHash(pH,pKey,nKey,h);
127628 if( elem ){
127629 void *old_data = elem->data;
127630 if( data==0 ){
127631 fts3RemoveElementByHash(pH,elem,h);
127632 }else{
127633 elem->data = data;
127635 return old_data;
127637 if( data==0 ) return 0;
127638 if( (pH->htsize==0 && fts3Rehash(pH,8))
127639 || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
127641 pH->count = 0;
127642 return data;
127644 assert( pH->htsize>0 );
127645 new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
127646 if( new_elem==0 ) return data;
127647 if( pH->copyKey && pKey!=0 ){
127648 new_elem->pKey = fts3HashMalloc( nKey );
127649 if( new_elem->pKey==0 ){
127650 fts3HashFree(new_elem);
127651 return data;
127653 memcpy((void*)new_elem->pKey, pKey, nKey);
127654 }else{
127655 new_elem->pKey = (void*)pKey;
127657 new_elem->nKey = nKey;
127658 pH->count++;
127659 assert( pH->htsize>0 );
127660 assert( (pH->htsize & (pH->htsize-1))==0 );
127661 h = hraw & (pH->htsize-1);
127662 fts3HashInsertElement(pH, &pH->ht[h], new_elem);
127663 new_elem->data = data;
127664 return 0;
127667 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
127669 /************** End of fts3_hash.c *******************************************/
127670 /************** Begin file fts3_porter.c *************************************/
127672 ** 2006 September 30
127674 ** The author disclaims copyright to this source code. In place of
127675 ** a legal notice, here is a blessing:
127677 ** May you do good and not evil.
127678 ** May you find forgiveness for yourself and forgive others.
127679 ** May you share freely, never taking more than you give.
127681 *************************************************************************
127682 ** Implementation of the full-text-search tokenizer that implements
127683 ** a Porter stemmer.
127687 ** The code in this file is only compiled if:
127689 ** * The FTS3 module is being built as an extension
127690 ** (in which case SQLITE_CORE is not defined), or
127692 ** * The FTS3 module is being built into the core of
127693 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
127695 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
127697 /* #include <assert.h> */
127698 /* #include <stdlib.h> */
127699 /* #include <stdio.h> */
127700 /* #include <string.h> */
127704 ** Class derived from sqlite3_tokenizer
127706 typedef struct porter_tokenizer {
127707 sqlite3_tokenizer base; /* Base class */
127708 } porter_tokenizer;
127711 ** Class derived from sqlite3_tokenizer_cursor
127713 typedef struct porter_tokenizer_cursor {
127714 sqlite3_tokenizer_cursor base;
127715 const char *zInput; /* input we are tokenizing */
127716 int nInput; /* size of the input */
127717 int iOffset; /* current position in zInput */
127718 int iToken; /* index of next token to be returned */
127719 char *zToken; /* storage for current token */
127720 int nAllocated; /* space allocated to zToken buffer */
127721 } porter_tokenizer_cursor;
127725 ** Create a new tokenizer instance.
127727 static int porterCreate(
127728 int argc, const char * const *argv,
127729 sqlite3_tokenizer **ppTokenizer
127731 porter_tokenizer *t;
127733 UNUSED_PARAMETER(argc);
127734 UNUSED_PARAMETER(argv);
127736 t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
127737 if( t==NULL ) return SQLITE_NOMEM;
127738 memset(t, 0, sizeof(*t));
127739 *ppTokenizer = &t->base;
127740 return SQLITE_OK;
127744 ** Destroy a tokenizer
127746 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
127747 sqlite3_free(pTokenizer);
127748 return SQLITE_OK;
127752 ** Prepare to begin tokenizing a particular string. The input
127753 ** string to be tokenized is zInput[0..nInput-1]. A cursor
127754 ** used to incrementally tokenize this string is returned in
127755 ** *ppCursor.
127757 static int porterOpen(
127758 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
127759 const char *zInput, int nInput, /* String to be tokenized */
127760 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
127762 porter_tokenizer_cursor *c;
127764 UNUSED_PARAMETER(pTokenizer);
127766 c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
127767 if( c==NULL ) return SQLITE_NOMEM;
127769 c->zInput = zInput;
127770 if( zInput==0 ){
127771 c->nInput = 0;
127772 }else if( nInput<0 ){
127773 c->nInput = (int)strlen(zInput);
127774 }else{
127775 c->nInput = nInput;
127777 c->iOffset = 0; /* start tokenizing at the beginning */
127778 c->iToken = 0;
127779 c->zToken = NULL; /* no space allocated, yet. */
127780 c->nAllocated = 0;
127782 *ppCursor = &c->base;
127783 return SQLITE_OK;
127787 ** Close a tokenization cursor previously opened by a call to
127788 ** porterOpen() above.
127790 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
127791 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
127792 sqlite3_free(c->zToken);
127793 sqlite3_free(c);
127794 return SQLITE_OK;
127797 ** Vowel or consonant
127799 static const char cType[] = {
127800 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
127801 1, 1, 1, 2, 1
127805 ** isConsonant() and isVowel() determine if their first character in
127806 ** the string they point to is a consonant or a vowel, according
127807 ** to Porter ruls.
127809 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
127810 ** 'Y' is a consonant unless it follows another consonant,
127811 ** in which case it is a vowel.
127813 ** In these routine, the letters are in reverse order. So the 'y' rule
127814 ** is that 'y' is a consonant unless it is followed by another
127815 ** consonent.
127817 static int isVowel(const char*);
127818 static int isConsonant(const char *z){
127819 int j;
127820 char x = *z;
127821 if( x==0 ) return 0;
127822 assert( x>='a' && x<='z' );
127823 j = cType[x-'a'];
127824 if( j<2 ) return j;
127825 return z[1]==0 || isVowel(z + 1);
127827 static int isVowel(const char *z){
127828 int j;
127829 char x = *z;
127830 if( x==0 ) return 0;
127831 assert( x>='a' && x<='z' );
127832 j = cType[x-'a'];
127833 if( j<2 ) return 1-j;
127834 return isConsonant(z + 1);
127838 ** Let any sequence of one or more vowels be represented by V and let
127839 ** C be sequence of one or more consonants. Then every word can be
127840 ** represented as:
127842 ** [C] (VC){m} [V]
127844 ** In prose: A word is an optional consonant followed by zero or
127845 ** vowel-consonant pairs followed by an optional vowel. "m" is the
127846 ** number of vowel consonant pairs. This routine computes the value
127847 ** of m for the first i bytes of a word.
127849 ** Return true if the m-value for z is 1 or more. In other words,
127850 ** return true if z contains at least one vowel that is followed
127851 ** by a consonant.
127853 ** In this routine z[] is in reverse order. So we are really looking
127854 ** for an instance of of a consonant followed by a vowel.
127856 static int m_gt_0(const char *z){
127857 while( isVowel(z) ){ z++; }
127858 if( *z==0 ) return 0;
127859 while( isConsonant(z) ){ z++; }
127860 return *z!=0;
127863 /* Like mgt0 above except we are looking for a value of m which is
127864 ** exactly 1
127866 static int m_eq_1(const char *z){
127867 while( isVowel(z) ){ z++; }
127868 if( *z==0 ) return 0;
127869 while( isConsonant(z) ){ z++; }
127870 if( *z==0 ) return 0;
127871 while( isVowel(z) ){ z++; }
127872 if( *z==0 ) return 1;
127873 while( isConsonant(z) ){ z++; }
127874 return *z==0;
127877 /* Like mgt0 above except we are looking for a value of m>1 instead
127878 ** or m>0
127880 static int m_gt_1(const char *z){
127881 while( isVowel(z) ){ z++; }
127882 if( *z==0 ) return 0;
127883 while( isConsonant(z) ){ z++; }
127884 if( *z==0 ) return 0;
127885 while( isVowel(z) ){ z++; }
127886 if( *z==0 ) return 0;
127887 while( isConsonant(z) ){ z++; }
127888 return *z!=0;
127892 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
127894 static int hasVowel(const char *z){
127895 while( isConsonant(z) ){ z++; }
127896 return *z!=0;
127900 ** Return TRUE if the word ends in a double consonant.
127902 ** The text is reversed here. So we are really looking at
127903 ** the first two characters of z[].
127905 static int doubleConsonant(const char *z){
127906 return isConsonant(z) && z[0]==z[1];
127910 ** Return TRUE if the word ends with three letters which
127911 ** are consonant-vowel-consonent and where the final consonant
127912 ** is not 'w', 'x', or 'y'.
127914 ** The word is reversed here. So we are really checking the
127915 ** first three letters and the first one cannot be in [wxy].
127917 static int star_oh(const char *z){
127918 return
127919 isConsonant(z) &&
127920 z[0]!='w' && z[0]!='x' && z[0]!='y' &&
127921 isVowel(z+1) &&
127922 isConsonant(z+2);
127926 ** If the word ends with zFrom and xCond() is true for the stem
127927 ** of the word that preceeds the zFrom ending, then change the
127928 ** ending to zTo.
127930 ** The input word *pz and zFrom are both in reverse order. zTo
127931 ** is in normal order.
127933 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
127934 ** match. Not that TRUE is returned even if xCond() fails and
127935 ** no substitution occurs.
127937 static int stem(
127938 char **pz, /* The word being stemmed (Reversed) */
127939 const char *zFrom, /* If the ending matches this... (Reversed) */
127940 const char *zTo, /* ... change the ending to this (not reversed) */
127941 int (*xCond)(const char*) /* Condition that must be true */
127943 char *z = *pz;
127944 while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
127945 if( *zFrom!=0 ) return 0;
127946 if( xCond && !xCond(z) ) return 1;
127947 while( *zTo ){
127948 *(--z) = *(zTo++);
127950 *pz = z;
127951 return 1;
127955 ** This is the fallback stemmer used when the porter stemmer is
127956 ** inappropriate. The input word is copied into the output with
127957 ** US-ASCII case folding. If the input word is too long (more
127958 ** than 20 bytes if it contains no digits or more than 6 bytes if
127959 ** it contains digits) then word is truncated to 20 or 6 bytes
127960 ** by taking 10 or 3 bytes from the beginning and end.
127962 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
127963 int i, mx, j;
127964 int hasDigit = 0;
127965 for(i=0; i<nIn; i++){
127966 char c = zIn[i];
127967 if( c>='A' && c<='Z' ){
127968 zOut[i] = c - 'A' + 'a';
127969 }else{
127970 if( c>='0' && c<='9' ) hasDigit = 1;
127971 zOut[i] = c;
127974 mx = hasDigit ? 3 : 10;
127975 if( nIn>mx*2 ){
127976 for(j=mx, i=nIn-mx; i<nIn; i++, j++){
127977 zOut[j] = zOut[i];
127979 i = j;
127981 zOut[i] = 0;
127982 *pnOut = i;
127987 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
127988 ** zOut is at least big enough to hold nIn bytes. Write the actual
127989 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
127991 ** Any upper-case characters in the US-ASCII character set ([A-Z])
127992 ** are converted to lower case. Upper-case UTF characters are
127993 ** unchanged.
127995 ** Words that are longer than about 20 bytes are stemmed by retaining
127996 ** a few bytes from the beginning and the end of the word. If the
127997 ** word contains digits, 3 bytes are taken from the beginning and
127998 ** 3 bytes from the end. For long words without digits, 10 bytes
127999 ** are taken from each end. US-ASCII case folding still applies.
128001 ** If the input word contains not digits but does characters not
128002 ** in [a-zA-Z] then no stemming is attempted and this routine just
128003 ** copies the input into the input into the output with US-ASCII
128004 ** case folding.
128006 ** Stemming never increases the length of the word. So there is
128007 ** no chance of overflowing the zOut buffer.
128009 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
128010 int i, j;
128011 char zReverse[28];
128012 char *z, *z2;
128013 if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
128014 /* The word is too big or too small for the porter stemmer.
128015 ** Fallback to the copy stemmer */
128016 copy_stemmer(zIn, nIn, zOut, pnOut);
128017 return;
128019 for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
128020 char c = zIn[i];
128021 if( c>='A' && c<='Z' ){
128022 zReverse[j] = c + 'a' - 'A';
128023 }else if( c>='a' && c<='z' ){
128024 zReverse[j] = c;
128025 }else{
128026 /* The use of a character not in [a-zA-Z] means that we fallback
128027 ** to the copy stemmer */
128028 copy_stemmer(zIn, nIn, zOut, pnOut);
128029 return;
128032 memset(&zReverse[sizeof(zReverse)-5], 0, 5);
128033 z = &zReverse[j+1];
128036 /* Step 1a */
128037 if( z[0]=='s' ){
128039 !stem(&z, "sess", "ss", 0) &&
128040 !stem(&z, "sei", "i", 0) &&
128041 !stem(&z, "ss", "ss", 0)
128047 /* Step 1b */
128048 z2 = z;
128049 if( stem(&z, "dee", "ee", m_gt_0) ){
128050 /* Do nothing. The work was all in the test */
128051 }else if(
128052 (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
128053 && z!=z2
128055 if( stem(&z, "ta", "ate", 0) ||
128056 stem(&z, "lb", "ble", 0) ||
128057 stem(&z, "zi", "ize", 0) ){
128058 /* Do nothing. The work was all in the test */
128059 }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
128061 }else if( m_eq_1(z) && star_oh(z) ){
128062 *(--z) = 'e';
128066 /* Step 1c */
128067 if( z[0]=='y' && hasVowel(z+1) ){
128068 z[0] = 'i';
128071 /* Step 2 */
128072 switch( z[1] ){
128073 case 'a':
128074 stem(&z, "lanoita", "ate", m_gt_0) ||
128075 stem(&z, "lanoit", "tion", m_gt_0);
128076 break;
128077 case 'c':
128078 stem(&z, "icne", "ence", m_gt_0) ||
128079 stem(&z, "icna", "ance", m_gt_0);
128080 break;
128081 case 'e':
128082 stem(&z, "rezi", "ize", m_gt_0);
128083 break;
128084 case 'g':
128085 stem(&z, "igol", "log", m_gt_0);
128086 break;
128087 case 'l':
128088 stem(&z, "ilb", "ble", m_gt_0) ||
128089 stem(&z, "illa", "al", m_gt_0) ||
128090 stem(&z, "iltne", "ent", m_gt_0) ||
128091 stem(&z, "ile", "e", m_gt_0) ||
128092 stem(&z, "ilsuo", "ous", m_gt_0);
128093 break;
128094 case 'o':
128095 stem(&z, "noitazi", "ize", m_gt_0) ||
128096 stem(&z, "noita", "ate", m_gt_0) ||
128097 stem(&z, "rota", "ate", m_gt_0);
128098 break;
128099 case 's':
128100 stem(&z, "msila", "al", m_gt_0) ||
128101 stem(&z, "ssenevi", "ive", m_gt_0) ||
128102 stem(&z, "ssenluf", "ful", m_gt_0) ||
128103 stem(&z, "ssensuo", "ous", m_gt_0);
128104 break;
128105 case 't':
128106 stem(&z, "itila", "al", m_gt_0) ||
128107 stem(&z, "itivi", "ive", m_gt_0) ||
128108 stem(&z, "itilib", "ble", m_gt_0);
128109 break;
128112 /* Step 3 */
128113 switch( z[0] ){
128114 case 'e':
128115 stem(&z, "etaci", "ic", m_gt_0) ||
128116 stem(&z, "evita", "", m_gt_0) ||
128117 stem(&z, "ezila", "al", m_gt_0);
128118 break;
128119 case 'i':
128120 stem(&z, "itici", "ic", m_gt_0);
128121 break;
128122 case 'l':
128123 stem(&z, "laci", "ic", m_gt_0) ||
128124 stem(&z, "luf", "", m_gt_0);
128125 break;
128126 case 's':
128127 stem(&z, "ssen", "", m_gt_0);
128128 break;
128131 /* Step 4 */
128132 switch( z[1] ){
128133 case 'a':
128134 if( z[0]=='l' && m_gt_1(z+2) ){
128135 z += 2;
128137 break;
128138 case 'c':
128139 if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
128140 z += 4;
128142 break;
128143 case 'e':
128144 if( z[0]=='r' && m_gt_1(z+2) ){
128145 z += 2;
128147 break;
128148 case 'i':
128149 if( z[0]=='c' && m_gt_1(z+2) ){
128150 z += 2;
128152 break;
128153 case 'l':
128154 if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
128155 z += 4;
128157 break;
128158 case 'n':
128159 if( z[0]=='t' ){
128160 if( z[2]=='a' ){
128161 if( m_gt_1(z+3) ){
128162 z += 3;
128164 }else if( z[2]=='e' ){
128165 stem(&z, "tneme", "", m_gt_1) ||
128166 stem(&z, "tnem", "", m_gt_1) ||
128167 stem(&z, "tne", "", m_gt_1);
128170 break;
128171 case 'o':
128172 if( z[0]=='u' ){
128173 if( m_gt_1(z+2) ){
128174 z += 2;
128176 }else if( z[3]=='s' || z[3]=='t' ){
128177 stem(&z, "noi", "", m_gt_1);
128179 break;
128180 case 's':
128181 if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
128182 z += 3;
128184 break;
128185 case 't':
128186 stem(&z, "eta", "", m_gt_1) ||
128187 stem(&z, "iti", "", m_gt_1);
128188 break;
128189 case 'u':
128190 if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
128191 z += 3;
128193 break;
128194 case 'v':
128195 case 'z':
128196 if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
128197 z += 3;
128199 break;
128202 /* Step 5a */
128203 if( z[0]=='e' ){
128204 if( m_gt_1(z+1) ){
128206 }else if( m_eq_1(z+1) && !star_oh(z+1) ){
128211 /* Step 5b */
128212 if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
128216 /* z[] is now the stemmed word in reverse order. Flip it back
128217 ** around into forward order and return.
128219 *pnOut = i = (int)strlen(z);
128220 zOut[i] = 0;
128221 while( *z ){
128222 zOut[--i] = *(z++);
128227 ** Characters that can be part of a token. We assume any character
128228 ** whose value is greater than 0x80 (any UTF character) can be
128229 ** part of a token. In other words, delimiters all must have
128230 ** values of 0x7f or lower.
128232 static const char porterIdChar[] = {
128233 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
128234 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
128235 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
128236 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
128237 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
128238 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
128240 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
128243 ** Extract the next token from a tokenization cursor. The cursor must
128244 ** have been opened by a prior call to porterOpen().
128246 static int porterNext(
128247 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
128248 const char **pzToken, /* OUT: *pzToken is the token text */
128249 int *pnBytes, /* OUT: Number of bytes in token */
128250 int *piStartOffset, /* OUT: Starting offset of token */
128251 int *piEndOffset, /* OUT: Ending offset of token */
128252 int *piPosition /* OUT: Position integer of token */
128254 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
128255 const char *z = c->zInput;
128257 while( c->iOffset<c->nInput ){
128258 int iStartOffset, ch;
128260 /* Scan past delimiter characters */
128261 while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
128262 c->iOffset++;
128265 /* Count non-delimiter characters. */
128266 iStartOffset = c->iOffset;
128267 while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
128268 c->iOffset++;
128271 if( c->iOffset>iStartOffset ){
128272 int n = c->iOffset-iStartOffset;
128273 if( n>c->nAllocated ){
128274 char *pNew;
128275 c->nAllocated = n+20;
128276 pNew = sqlite3_realloc(c->zToken, c->nAllocated);
128277 if( !pNew ) return SQLITE_NOMEM;
128278 c->zToken = pNew;
128280 porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
128281 *pzToken = c->zToken;
128282 *piStartOffset = iStartOffset;
128283 *piEndOffset = c->iOffset;
128284 *piPosition = c->iToken++;
128285 return SQLITE_OK;
128288 return SQLITE_DONE;
128292 ** The set of routines that implement the porter-stemmer tokenizer
128294 static const sqlite3_tokenizer_module porterTokenizerModule = {
128296 porterCreate,
128297 porterDestroy,
128298 porterOpen,
128299 porterClose,
128300 porterNext,
128305 ** Allocate a new porter tokenizer. Return a pointer to the new
128306 ** tokenizer in *ppModule
128308 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
128309 sqlite3_tokenizer_module const**ppModule
128311 *ppModule = &porterTokenizerModule;
128314 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
128316 /************** End of fts3_porter.c *****************************************/
128317 /************** Begin file fts3_tokenizer.c **********************************/
128319 ** 2007 June 22
128321 ** The author disclaims copyright to this source code. In place of
128322 ** a legal notice, here is a blessing:
128324 ** May you do good and not evil.
128325 ** May you find forgiveness for yourself and forgive others.
128326 ** May you share freely, never taking more than you give.
128328 ******************************************************************************
128330 ** This is part of an SQLite module implementing full-text search.
128331 ** This particular file implements the generic tokenizer interface.
128335 ** The code in this file is only compiled if:
128337 ** * The FTS3 module is being built as an extension
128338 ** (in which case SQLITE_CORE is not defined), or
128340 ** * The FTS3 module is being built into the core of
128341 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
128343 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128345 /* #include <assert.h> */
128346 /* #include <string.h> */
128349 ** Implementation of the SQL scalar function for accessing the underlying
128350 ** hash table. This function may be called as follows:
128352 ** SELECT <function-name>(<key-name>);
128353 ** SELECT <function-name>(<key-name>, <pointer>);
128355 ** where <function-name> is the name passed as the second argument
128356 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
128358 ** If the <pointer> argument is specified, it must be a blob value
128359 ** containing a pointer to be stored as the hash data corresponding
128360 ** to the string <key-name>. If <pointer> is not specified, then
128361 ** the string <key-name> must already exist in the has table. Otherwise,
128362 ** an error is returned.
128364 ** Whether or not the <pointer> argument is specified, the value returned
128365 ** is a blob containing the pointer stored as the hash data corresponding
128366 ** to string <key-name> (after the hash-table is updated, if applicable).
128368 static void scalarFunc(
128369 sqlite3_context *context,
128370 int argc,
128371 sqlite3_value **argv
128373 Fts3Hash *pHash;
128374 void *pPtr = 0;
128375 const unsigned char *zName;
128376 int nName;
128378 assert( argc==1 || argc==2 );
128380 pHash = (Fts3Hash *)sqlite3_user_data(context);
128382 zName = sqlite3_value_text(argv[0]);
128383 nName = sqlite3_value_bytes(argv[0])+1;
128385 if( argc==2 ){
128386 void *pOld;
128387 int n = sqlite3_value_bytes(argv[1]);
128388 if( n!=sizeof(pPtr) ){
128389 sqlite3_result_error(context, "argument type mismatch", -1);
128390 return;
128392 pPtr = *(void **)sqlite3_value_blob(argv[1]);
128393 pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
128394 if( pOld==pPtr ){
128395 sqlite3_result_error(context, "out of memory", -1);
128396 return;
128398 }else{
128399 pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
128400 if( !pPtr ){
128401 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
128402 sqlite3_result_error(context, zErr, -1);
128403 sqlite3_free(zErr);
128404 return;
128408 sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
128411 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
128412 static const char isFtsIdChar[] = {
128413 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
128414 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
128415 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
128416 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
128417 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
128418 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
128419 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
128420 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
128422 return (c&0x80 || isFtsIdChar[(int)(c)]);
128425 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
128426 const char *z1;
128427 const char *z2 = 0;
128429 /* Find the start of the next token. */
128430 z1 = zStr;
128431 while( z2==0 ){
128432 char c = *z1;
128433 switch( c ){
128434 case '\0': return 0; /* No more tokens here */
128435 case '\'':
128436 case '"':
128437 case '`': {
128438 z2 = z1;
128439 while( *++z2 && (*z2!=c || *++z2==c) );
128440 break;
128442 case '[':
128443 z2 = &z1[1];
128444 while( *z2 && z2[0]!=']' ) z2++;
128445 if( *z2 ) z2++;
128446 break;
128448 default:
128449 if( sqlite3Fts3IsIdChar(*z1) ){
128450 z2 = &z1[1];
128451 while( sqlite3Fts3IsIdChar(*z2) ) z2++;
128452 }else{
128453 z1++;
128458 *pn = (int)(z2-z1);
128459 return z1;
128462 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
128463 Fts3Hash *pHash, /* Tokenizer hash table */
128464 const char *zArg, /* Tokenizer name */
128465 sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
128466 char **pzErr /* OUT: Set to malloced error message */
128468 int rc;
128469 char *z = (char *)zArg;
128470 int n = 0;
128471 char *zCopy;
128472 char *zEnd; /* Pointer to nul-term of zCopy */
128473 sqlite3_tokenizer_module *m;
128475 zCopy = sqlite3_mprintf("%s", zArg);
128476 if( !zCopy ) return SQLITE_NOMEM;
128477 zEnd = &zCopy[strlen(zCopy)];
128479 z = (char *)sqlite3Fts3NextToken(zCopy, &n);
128480 z[n] = '\0';
128481 sqlite3Fts3Dequote(z);
128483 m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
128484 if( !m ){
128485 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
128486 rc = SQLITE_ERROR;
128487 }else{
128488 char const **aArg = 0;
128489 int iArg = 0;
128490 z = &z[n+1];
128491 while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
128492 int nNew = sizeof(char *)*(iArg+1);
128493 char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
128494 if( !aNew ){
128495 sqlite3_free(zCopy);
128496 sqlite3_free((void *)aArg);
128497 return SQLITE_NOMEM;
128499 aArg = aNew;
128500 aArg[iArg++] = z;
128501 z[n] = '\0';
128502 sqlite3Fts3Dequote(z);
128503 z = &z[n+1];
128505 rc = m->xCreate(iArg, aArg, ppTok);
128506 assert( rc!=SQLITE_OK || *ppTok );
128507 if( rc!=SQLITE_OK ){
128508 *pzErr = sqlite3_mprintf("unknown tokenizer");
128509 }else{
128510 (*ppTok)->pModule = m;
128512 sqlite3_free((void *)aArg);
128515 sqlite3_free(zCopy);
128516 return rc;
128520 #ifdef SQLITE_TEST
128522 #include <tcl.h>
128523 /* #include <string.h> */
128526 ** Implementation of a special SQL scalar function for testing tokenizers
128527 ** designed to be used in concert with the Tcl testing framework. This
128528 ** function must be called with two or more arguments:
128530 ** SELECT <function-name>(<key-name>, ..., <input-string>);
128532 ** where <function-name> is the name passed as the second argument
128533 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
128534 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
128536 ** The return value is a string that may be interpreted as a Tcl
128537 ** list. For each token in the <input-string>, three elements are
128538 ** added to the returned list. The first is the token position, the
128539 ** second is the token text (folded, stemmed, etc.) and the third is the
128540 ** substring of <input-string> associated with the token. For example,
128541 ** using the built-in "simple" tokenizer:
128543 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
128545 ** will return the string:
128547 ** "{0 i I 1 dont don't 2 see see 3 how how}"
128550 static void testFunc(
128551 sqlite3_context *context,
128552 int argc,
128553 sqlite3_value **argv
128555 Fts3Hash *pHash;
128556 sqlite3_tokenizer_module *p;
128557 sqlite3_tokenizer *pTokenizer = 0;
128558 sqlite3_tokenizer_cursor *pCsr = 0;
128560 const char *zErr = 0;
128562 const char *zName;
128563 int nName;
128564 const char *zInput;
128565 int nInput;
128567 const char *azArg[64];
128569 const char *zToken;
128570 int nToken = 0;
128571 int iStart = 0;
128572 int iEnd = 0;
128573 int iPos = 0;
128574 int i;
128576 Tcl_Obj *pRet;
128578 if( argc<2 ){
128579 sqlite3_result_error(context, "insufficient arguments", -1);
128580 return;
128583 nName = sqlite3_value_bytes(argv[0]);
128584 zName = (const char *)sqlite3_value_text(argv[0]);
128585 nInput = sqlite3_value_bytes(argv[argc-1]);
128586 zInput = (const char *)sqlite3_value_text(argv[argc-1]);
128588 pHash = (Fts3Hash *)sqlite3_user_data(context);
128589 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
128591 if( !p ){
128592 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
128593 sqlite3_result_error(context, zErr, -1);
128594 sqlite3_free(zErr);
128595 return;
128598 pRet = Tcl_NewObj();
128599 Tcl_IncrRefCount(pRet);
128601 for(i=1; i<argc-1; i++){
128602 azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
128605 if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
128606 zErr = "error in xCreate()";
128607 goto finish;
128609 pTokenizer->pModule = p;
128610 if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
128611 zErr = "error in xOpen()";
128612 goto finish;
128615 while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
128616 Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
128617 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
128618 zToken = &zInput[iStart];
128619 nToken = iEnd-iStart;
128620 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
128623 if( SQLITE_OK!=p->xClose(pCsr) ){
128624 zErr = "error in xClose()";
128625 goto finish;
128627 if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
128628 zErr = "error in xDestroy()";
128629 goto finish;
128632 finish:
128633 if( zErr ){
128634 sqlite3_result_error(context, zErr, -1);
128635 }else{
128636 sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
128638 Tcl_DecrRefCount(pRet);
128641 static
128642 int registerTokenizer(
128643 sqlite3 *db,
128644 char *zName,
128645 const sqlite3_tokenizer_module *p
128647 int rc;
128648 sqlite3_stmt *pStmt;
128649 const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
128651 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
128652 if( rc!=SQLITE_OK ){
128653 return rc;
128656 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
128657 sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
128658 sqlite3_step(pStmt);
128660 return sqlite3_finalize(pStmt);
128663 static
128664 int queryTokenizer(
128665 sqlite3 *db,
128666 char *zName,
128667 const sqlite3_tokenizer_module **pp
128669 int rc;
128670 sqlite3_stmt *pStmt;
128671 const char zSql[] = "SELECT fts3_tokenizer(?)";
128673 *pp = 0;
128674 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
128675 if( rc!=SQLITE_OK ){
128676 return rc;
128679 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
128680 if( SQLITE_ROW==sqlite3_step(pStmt) ){
128681 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
128682 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
128686 return sqlite3_finalize(pStmt);
128689 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
128692 ** Implementation of the scalar function fts3_tokenizer_internal_test().
128693 ** This function is used for testing only, it is not included in the
128694 ** build unless SQLITE_TEST is defined.
128696 ** The purpose of this is to test that the fts3_tokenizer() function
128697 ** can be used as designed by the C-code in the queryTokenizer and
128698 ** registerTokenizer() functions above. These two functions are repeated
128699 ** in the README.tokenizer file as an example, so it is important to
128700 ** test them.
128702 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
128703 ** function with no arguments. An assert() will fail if a problem is
128704 ** detected. i.e.:
128706 ** SELECT fts3_tokenizer_internal_test();
128709 static void intTestFunc(
128710 sqlite3_context *context,
128711 int argc,
128712 sqlite3_value **argv
128714 int rc;
128715 const sqlite3_tokenizer_module *p1;
128716 const sqlite3_tokenizer_module *p2;
128717 sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
128719 UNUSED_PARAMETER(argc);
128720 UNUSED_PARAMETER(argv);
128722 /* Test the query function */
128723 sqlite3Fts3SimpleTokenizerModule(&p1);
128724 rc = queryTokenizer(db, "simple", &p2);
128725 assert( rc==SQLITE_OK );
128726 assert( p1==p2 );
128727 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
128728 assert( rc==SQLITE_ERROR );
128729 assert( p2==0 );
128730 assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
128732 /* Test the storage function */
128733 rc = registerTokenizer(db, "nosuchtokenizer", p1);
128734 assert( rc==SQLITE_OK );
128735 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
128736 assert( rc==SQLITE_OK );
128737 assert( p2==p1 );
128739 sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
128742 #endif
128745 ** Set up SQL objects in database db used to access the contents of
128746 ** the hash table pointed to by argument pHash. The hash table must
128747 ** been initialized to use string keys, and to take a private copy
128748 ** of the key when a value is inserted. i.e. by a call similar to:
128750 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
128752 ** This function adds a scalar function (see header comment above
128753 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
128754 ** defined at compilation time, a temporary virtual table (see header
128755 ** comment above struct HashTableVtab) to the database schema. Both
128756 ** provide read/write access to the contents of *pHash.
128758 ** The third argument to this function, zName, is used as the name
128759 ** of both the scalar and, if created, the virtual table.
128761 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
128762 sqlite3 *db,
128763 Fts3Hash *pHash,
128764 const char *zName
128766 int rc = SQLITE_OK;
128767 void *p = (void *)pHash;
128768 const int any = SQLITE_ANY;
128770 #ifdef SQLITE_TEST
128771 char *zTest = 0;
128772 char *zTest2 = 0;
128773 void *pdb = (void *)db;
128774 zTest = sqlite3_mprintf("%s_test", zName);
128775 zTest2 = sqlite3_mprintf("%s_internal_test", zName);
128776 if( !zTest || !zTest2 ){
128777 rc = SQLITE_NOMEM;
128779 #endif
128781 if( SQLITE_OK==rc ){
128782 rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
128784 if( SQLITE_OK==rc ){
128785 rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
128787 #ifdef SQLITE_TEST
128788 if( SQLITE_OK==rc ){
128789 rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
128791 if( SQLITE_OK==rc ){
128792 rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
128794 #endif
128796 #ifdef SQLITE_TEST
128797 sqlite3_free(zTest);
128798 sqlite3_free(zTest2);
128799 #endif
128801 return rc;
128804 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
128806 /************** End of fts3_tokenizer.c **************************************/
128807 /************** Begin file fts3_tokenizer1.c *********************************/
128809 ** 2006 Oct 10
128811 ** The author disclaims copyright to this source code. In place of
128812 ** a legal notice, here is a blessing:
128814 ** May you do good and not evil.
128815 ** May you find forgiveness for yourself and forgive others.
128816 ** May you share freely, never taking more than you give.
128818 ******************************************************************************
128820 ** Implementation of the "simple" full-text-search tokenizer.
128824 ** The code in this file is only compiled if:
128826 ** * The FTS3 module is being built as an extension
128827 ** (in which case SQLITE_CORE is not defined), or
128829 ** * The FTS3 module is being built into the core of
128830 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
128832 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128834 /* #include <assert.h> */
128835 /* #include <stdlib.h> */
128836 /* #include <stdio.h> */
128837 /* #include <string.h> */
128840 typedef struct simple_tokenizer {
128841 sqlite3_tokenizer base;
128842 char delim[128]; /* flag ASCII delimiters */
128843 } simple_tokenizer;
128845 typedef struct simple_tokenizer_cursor {
128846 sqlite3_tokenizer_cursor base;
128847 const char *pInput; /* input we are tokenizing */
128848 int nBytes; /* size of the input */
128849 int iOffset; /* current position in pInput */
128850 int iToken; /* index of next token to be returned */
128851 char *pToken; /* storage for current token */
128852 int nTokenAllocated; /* space allocated to zToken buffer */
128853 } simple_tokenizer_cursor;
128856 static int simpleDelim(simple_tokenizer *t, unsigned char c){
128857 return c<0x80 && t->delim[c];
128859 static int fts3_isalnum(int x){
128860 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
128864 ** Create a new tokenizer instance.
128866 static int simpleCreate(
128867 int argc, const char * const *argv,
128868 sqlite3_tokenizer **ppTokenizer
128870 simple_tokenizer *t;
128872 t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
128873 if( t==NULL ) return SQLITE_NOMEM;
128874 memset(t, 0, sizeof(*t));
128876 /* TODO(shess) Delimiters need to remain the same from run to run,
128877 ** else we need to reindex. One solution would be a meta-table to
128878 ** track such information in the database, then we'd only want this
128879 ** information on the initial create.
128881 if( argc>1 ){
128882 int i, n = (int)strlen(argv[1]);
128883 for(i=0; i<n; i++){
128884 unsigned char ch = argv[1][i];
128885 /* We explicitly don't support UTF-8 delimiters for now. */
128886 if( ch>=0x80 ){
128887 sqlite3_free(t);
128888 return SQLITE_ERROR;
128890 t->delim[ch] = 1;
128892 } else {
128893 /* Mark non-alphanumeric ASCII characters as delimiters */
128894 int i;
128895 for(i=1; i<0x80; i++){
128896 t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
128900 *ppTokenizer = &t->base;
128901 return SQLITE_OK;
128905 ** Destroy a tokenizer
128907 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
128908 sqlite3_free(pTokenizer);
128909 return SQLITE_OK;
128913 ** Prepare to begin tokenizing a particular string. The input
128914 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
128915 ** used to incrementally tokenize this string is returned in
128916 ** *ppCursor.
128918 static int simpleOpen(
128919 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
128920 const char *pInput, int nBytes, /* String to be tokenized */
128921 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
128923 simple_tokenizer_cursor *c;
128925 UNUSED_PARAMETER(pTokenizer);
128927 c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
128928 if( c==NULL ) return SQLITE_NOMEM;
128930 c->pInput = pInput;
128931 if( pInput==0 ){
128932 c->nBytes = 0;
128933 }else if( nBytes<0 ){
128934 c->nBytes = (int)strlen(pInput);
128935 }else{
128936 c->nBytes = nBytes;
128938 c->iOffset = 0; /* start tokenizing at the beginning */
128939 c->iToken = 0;
128940 c->pToken = NULL; /* no space allocated, yet. */
128941 c->nTokenAllocated = 0;
128943 *ppCursor = &c->base;
128944 return SQLITE_OK;
128948 ** Close a tokenization cursor previously opened by a call to
128949 ** simpleOpen() above.
128951 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
128952 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
128953 sqlite3_free(c->pToken);
128954 sqlite3_free(c);
128955 return SQLITE_OK;
128959 ** Extract the next token from a tokenization cursor. The cursor must
128960 ** have been opened by a prior call to simpleOpen().
128962 static int simpleNext(
128963 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
128964 const char **ppToken, /* OUT: *ppToken is the token text */
128965 int *pnBytes, /* OUT: Number of bytes in token */
128966 int *piStartOffset, /* OUT: Starting offset of token */
128967 int *piEndOffset, /* OUT: Ending offset of token */
128968 int *piPosition /* OUT: Position integer of token */
128970 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
128971 simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
128972 unsigned char *p = (unsigned char *)c->pInput;
128974 while( c->iOffset<c->nBytes ){
128975 int iStartOffset;
128977 /* Scan past delimiter characters */
128978 while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
128979 c->iOffset++;
128982 /* Count non-delimiter characters. */
128983 iStartOffset = c->iOffset;
128984 while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
128985 c->iOffset++;
128988 if( c->iOffset>iStartOffset ){
128989 int i, n = c->iOffset-iStartOffset;
128990 if( n>c->nTokenAllocated ){
128991 char *pNew;
128992 c->nTokenAllocated = n+20;
128993 pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
128994 if( !pNew ) return SQLITE_NOMEM;
128995 c->pToken = pNew;
128997 for(i=0; i<n; i++){
128998 /* TODO(shess) This needs expansion to handle UTF-8
128999 ** case-insensitivity.
129001 unsigned char ch = p[iStartOffset+i];
129002 c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
129004 *ppToken = c->pToken;
129005 *pnBytes = n;
129006 *piStartOffset = iStartOffset;
129007 *piEndOffset = c->iOffset;
129008 *piPosition = c->iToken++;
129010 return SQLITE_OK;
129013 return SQLITE_DONE;
129017 ** The set of routines that implement the simple tokenizer
129019 static const sqlite3_tokenizer_module simpleTokenizerModule = {
129021 simpleCreate,
129022 simpleDestroy,
129023 simpleOpen,
129024 simpleClose,
129025 simpleNext,
129030 ** Allocate a new simple tokenizer. Return a pointer to the new
129031 ** tokenizer in *ppModule
129033 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
129034 sqlite3_tokenizer_module const**ppModule
129036 *ppModule = &simpleTokenizerModule;
129039 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
129041 /************** End of fts3_tokenizer1.c *************************************/
129042 /************** Begin file fts3_tokenize_vtab.c ******************************/
129044 ** 2013 Apr 22
129046 ** The author disclaims copyright to this source code. In place of
129047 ** a legal notice, here is a blessing:
129049 ** May you do good and not evil.
129050 ** May you find forgiveness for yourself and forgive others.
129051 ** May you share freely, never taking more than you give.
129053 ******************************************************************************
129055 ** This file contains code for the "fts3tokenize" virtual table module.
129056 ** An fts3tokenize virtual table is created as follows:
129058 ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
129059 ** <tokenizer-name>, <arg-1>, ...
129060 ** );
129062 ** The table created has the following schema:
129064 ** CREATE TABLE <tbl>(input, token, start, end, position)
129066 ** When queried, the query must include a WHERE clause of type:
129068 ** input = <string>
129070 ** The virtual table module tokenizes this <string>, using the FTS3
129071 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
129072 ** statement and returns one row for each token in the result. With
129073 ** fields set as follows:
129075 ** input: Always set to a copy of <string>
129076 ** token: A token from the input.
129077 ** start: Byte offset of the token within the input <string>.
129078 ** end: Byte offset of the byte immediately following the end of the
129079 ** token within the input string.
129080 ** pos: Token offset of token within input.
129083 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
129085 /* #include <string.h> */
129086 /* #include <assert.h> */
129088 typedef struct Fts3tokTable Fts3tokTable;
129089 typedef struct Fts3tokCursor Fts3tokCursor;
129092 ** Virtual table structure.
129094 struct Fts3tokTable {
129095 sqlite3_vtab base; /* Base class used by SQLite core */
129096 const sqlite3_tokenizer_module *pMod;
129097 sqlite3_tokenizer *pTok;
129101 ** Virtual table cursor structure.
129103 struct Fts3tokCursor {
129104 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
129105 char *zInput; /* Input string */
129106 sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
129107 int iRowid; /* Current 'rowid' value */
129108 const char *zToken; /* Current 'token' value */
129109 int nToken; /* Size of zToken in bytes */
129110 int iStart; /* Current 'start' value */
129111 int iEnd; /* Current 'end' value */
129112 int iPos; /* Current 'pos' value */
129116 ** Query FTS for the tokenizer implementation named zName.
129118 static int fts3tokQueryTokenizer(
129119 Fts3Hash *pHash,
129120 const char *zName,
129121 const sqlite3_tokenizer_module **pp,
129122 char **pzErr
129124 sqlite3_tokenizer_module *p;
129125 int nName = (int)strlen(zName);
129127 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
129128 if( !p ){
129129 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
129130 return SQLITE_ERROR;
129133 *pp = p;
129134 return SQLITE_OK;
129138 ** The second argument, argv[], is an array of pointers to nul-terminated
129139 ** strings. This function makes a copy of the array and strings into a
129140 ** single block of memory. It then dequotes any of the strings that appear
129141 ** to be quoted.
129143 ** If successful, output parameter *pazDequote is set to point at the
129144 ** array of dequoted strings and SQLITE_OK is returned. The caller is
129145 ** responsible for eventually calling sqlite3_free() to free the array
129146 ** in this case. Or, if an error occurs, an SQLite error code is returned.
129147 ** The final value of *pazDequote is undefined in this case.
129149 static int fts3tokDequoteArray(
129150 int argc, /* Number of elements in argv[] */
129151 const char * const *argv, /* Input array */
129152 char ***pazDequote /* Output array */
129154 int rc = SQLITE_OK; /* Return code */
129155 if( argc==0 ){
129156 *pazDequote = 0;
129157 }else{
129158 int i;
129159 int nByte = 0;
129160 char **azDequote;
129162 for(i=0; i<argc; i++){
129163 nByte += (int)(strlen(argv[i]) + 1);
129166 *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
129167 if( azDequote==0 ){
129168 rc = SQLITE_NOMEM;
129169 }else{
129170 char *pSpace = (char *)&azDequote[argc];
129171 for(i=0; i<argc; i++){
129172 int n = (int)strlen(argv[i]);
129173 azDequote[i] = pSpace;
129174 memcpy(pSpace, argv[i], n+1);
129175 sqlite3Fts3Dequote(pSpace);
129176 pSpace += (n+1);
129181 return rc;
129185 ** Schema of the tokenizer table.
129187 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
129190 ** This function does all the work for both the xConnect and xCreate methods.
129191 ** These tables have no persistent representation of their own, so xConnect
129192 ** and xCreate are identical operations.
129194 ** argv[0]: module name
129195 ** argv[1]: database name
129196 ** argv[2]: table name
129197 ** argv[3]: first argument (tokenizer name)
129199 static int fts3tokConnectMethod(
129200 sqlite3 *db, /* Database connection */
129201 void *pHash, /* Hash table of tokenizers */
129202 int argc, /* Number of elements in argv array */
129203 const char * const *argv, /* xCreate/xConnect argument array */
129204 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
129205 char **pzErr /* OUT: sqlite3_malloc'd error message */
129207 Fts3tokTable *pTab;
129208 const sqlite3_tokenizer_module *pMod = 0;
129209 sqlite3_tokenizer *pTok = 0;
129210 int rc;
129211 char **azDequote = 0;
129212 int nDequote;
129214 rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
129215 if( rc!=SQLITE_OK ) return rc;
129217 nDequote = argc-3;
129218 rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
129220 if( rc==SQLITE_OK ){
129221 const char *zModule;
129222 if( nDequote<1 ){
129223 zModule = "simple";
129224 }else{
129225 zModule = azDequote[0];
129227 rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
129230 assert( (rc==SQLITE_OK)==(pMod!=0) );
129231 if( rc==SQLITE_OK ){
129232 const char * const *azArg = (const char * const *)&azDequote[1];
129233 rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
129236 if( rc==SQLITE_OK ){
129237 pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
129238 if( pTab==0 ){
129239 rc = SQLITE_NOMEM;
129243 if( rc==SQLITE_OK ){
129244 memset(pTab, 0, sizeof(Fts3tokTable));
129245 pTab->pMod = pMod;
129246 pTab->pTok = pTok;
129247 *ppVtab = &pTab->base;
129248 }else{
129249 if( pTok ){
129250 pMod->xDestroy(pTok);
129254 sqlite3_free(azDequote);
129255 return rc;
129259 ** This function does the work for both the xDisconnect and xDestroy methods.
129260 ** These tables have no persistent representation of their own, so xDisconnect
129261 ** and xDestroy are identical operations.
129263 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
129264 Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
129266 pTab->pMod->xDestroy(pTab->pTok);
129267 sqlite3_free(pTab);
129268 return SQLITE_OK;
129272 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
129274 static int fts3tokBestIndexMethod(
129275 sqlite3_vtab *pVTab,
129276 sqlite3_index_info *pInfo
129278 int i;
129279 UNUSED_PARAMETER(pVTab);
129281 for(i=0; i<pInfo->nConstraint; i++){
129282 if( pInfo->aConstraint[i].usable
129283 && pInfo->aConstraint[i].iColumn==0
129284 && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
129286 pInfo->idxNum = 1;
129287 pInfo->aConstraintUsage[i].argvIndex = 1;
129288 pInfo->aConstraintUsage[i].omit = 1;
129289 pInfo->estimatedCost = 1;
129290 return SQLITE_OK;
129294 pInfo->idxNum = 0;
129295 assert( pInfo->estimatedCost>1000000.0 );
129297 return SQLITE_OK;
129301 ** xOpen - Open a cursor.
129303 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
129304 Fts3tokCursor *pCsr;
129305 UNUSED_PARAMETER(pVTab);
129307 pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
129308 if( pCsr==0 ){
129309 return SQLITE_NOMEM;
129311 memset(pCsr, 0, sizeof(Fts3tokCursor));
129313 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
129314 return SQLITE_OK;
129318 ** Reset the tokenizer cursor passed as the only argument. As if it had
129319 ** just been returned by fts3tokOpenMethod().
129321 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
129322 if( pCsr->pCsr ){
129323 Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
129324 pTab->pMod->xClose(pCsr->pCsr);
129325 pCsr->pCsr = 0;
129327 sqlite3_free(pCsr->zInput);
129328 pCsr->zInput = 0;
129329 pCsr->zToken = 0;
129330 pCsr->nToken = 0;
129331 pCsr->iStart = 0;
129332 pCsr->iEnd = 0;
129333 pCsr->iPos = 0;
129334 pCsr->iRowid = 0;
129338 ** xClose - Close a cursor.
129340 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
129341 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
129343 fts3tokResetCursor(pCsr);
129344 sqlite3_free(pCsr);
129345 return SQLITE_OK;
129349 ** xNext - Advance the cursor to the next row, if any.
129351 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
129352 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
129353 Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
129354 int rc; /* Return code */
129356 pCsr->iRowid++;
129357 rc = pTab->pMod->xNext(pCsr->pCsr,
129358 &pCsr->zToken, &pCsr->nToken,
129359 &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
129362 if( rc!=SQLITE_OK ){
129363 fts3tokResetCursor(pCsr);
129364 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
129367 return rc;
129371 ** xFilter - Initialize a cursor to point at the start of its data.
129373 static int fts3tokFilterMethod(
129374 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
129375 int idxNum, /* Strategy index */
129376 const char *idxStr, /* Unused */
129377 int nVal, /* Number of elements in apVal */
129378 sqlite3_value **apVal /* Arguments for the indexing scheme */
129380 int rc = SQLITE_ERROR;
129381 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
129382 Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
129383 UNUSED_PARAMETER(idxStr);
129384 UNUSED_PARAMETER(nVal);
129386 fts3tokResetCursor(pCsr);
129387 if( idxNum==1 ){
129388 const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
129389 int nByte = sqlite3_value_bytes(apVal[0]);
129390 pCsr->zInput = sqlite3_malloc(nByte+1);
129391 if( pCsr->zInput==0 ){
129392 rc = SQLITE_NOMEM;
129393 }else{
129394 memcpy(pCsr->zInput, zByte, nByte);
129395 pCsr->zInput[nByte] = 0;
129396 rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
129397 if( rc==SQLITE_OK ){
129398 pCsr->pCsr->pTokenizer = pTab->pTok;
129403 if( rc!=SQLITE_OK ) return rc;
129404 return fts3tokNextMethod(pCursor);
129408 ** xEof - Return true if the cursor is at EOF, or false otherwise.
129410 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
129411 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
129412 return (pCsr->zToken==0);
129416 ** xColumn - Return a column value.
129418 static int fts3tokColumnMethod(
129419 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
129420 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
129421 int iCol /* Index of column to read value from */
129423 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
129425 /* CREATE TABLE x(input, token, start, end, position) */
129426 switch( iCol ){
129427 case 0:
129428 sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
129429 break;
129430 case 1:
129431 sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
129432 break;
129433 case 2:
129434 sqlite3_result_int(pCtx, pCsr->iStart);
129435 break;
129436 case 3:
129437 sqlite3_result_int(pCtx, pCsr->iEnd);
129438 break;
129439 default:
129440 assert( iCol==4 );
129441 sqlite3_result_int(pCtx, pCsr->iPos);
129442 break;
129444 return SQLITE_OK;
129448 ** xRowid - Return the current rowid for the cursor.
129450 static int fts3tokRowidMethod(
129451 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
129452 sqlite_int64 *pRowid /* OUT: Rowid value */
129454 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
129455 *pRowid = (sqlite3_int64)pCsr->iRowid;
129456 return SQLITE_OK;
129460 ** Register the fts3tok module with database connection db. Return SQLITE_OK
129461 ** if successful or an error code if sqlite3_create_module() fails.
129463 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
129464 static const sqlite3_module fts3tok_module = {
129465 0, /* iVersion */
129466 fts3tokConnectMethod, /* xCreate */
129467 fts3tokConnectMethod, /* xConnect */
129468 fts3tokBestIndexMethod, /* xBestIndex */
129469 fts3tokDisconnectMethod, /* xDisconnect */
129470 fts3tokDisconnectMethod, /* xDestroy */
129471 fts3tokOpenMethod, /* xOpen */
129472 fts3tokCloseMethod, /* xClose */
129473 fts3tokFilterMethod, /* xFilter */
129474 fts3tokNextMethod, /* xNext */
129475 fts3tokEofMethod, /* xEof */
129476 fts3tokColumnMethod, /* xColumn */
129477 fts3tokRowidMethod, /* xRowid */
129478 0, /* xUpdate */
129479 0, /* xBegin */
129480 0, /* xSync */
129481 0, /* xCommit */
129482 0, /* xRollback */
129483 0, /* xFindFunction */
129484 0, /* xRename */
129485 0, /* xSavepoint */
129486 0, /* xRelease */
129487 0 /* xRollbackTo */
129489 int rc; /* Return code */
129491 rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
129492 return rc;
129495 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
129497 /************** End of fts3_tokenize_vtab.c **********************************/
129498 /************** Begin file fts3_write.c **************************************/
129500 ** 2009 Oct 23
129502 ** The author disclaims copyright to this source code. In place of
129503 ** a legal notice, here is a blessing:
129505 ** May you do good and not evil.
129506 ** May you find forgiveness for yourself and forgive others.
129507 ** May you share freely, never taking more than you give.
129509 ******************************************************************************
129511 ** This file is part of the SQLite FTS3 extension module. Specifically,
129512 ** this file contains code to insert, update and delete rows from FTS3
129513 ** tables. It also contains code to merge FTS3 b-tree segments. Some
129514 ** of the sub-routines used to merge segments are also used by the query
129515 ** code in fts3.c.
129518 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
129520 /* #include <string.h> */
129521 /* #include <assert.h> */
129522 /* #include <stdlib.h> */
129525 #define FTS_MAX_APPENDABLE_HEIGHT 16
129528 ** When full-text index nodes are loaded from disk, the buffer that they
129529 ** are loaded into has the following number of bytes of padding at the end
129530 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
129531 ** of 920 bytes is allocated for it.
129533 ** This means that if we have a pointer into a buffer containing node data,
129534 ** it is always safe to read up to two varints from it without risking an
129535 ** overread, even if the node data is corrupted.
129537 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
129540 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
129541 ** memory incrementally instead of all at once. This can be a big performance
129542 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
129543 ** method before retrieving all query results (as may happen, for example,
129544 ** if a query has a LIMIT clause).
129546 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
129547 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
129548 ** The code is written so that the hard lower-limit for each of these values
129549 ** is 1. Clearly such small values would be inefficient, but can be useful
129550 ** for testing purposes.
129552 ** If this module is built with SQLITE_TEST defined, these constants may
129553 ** be overridden at runtime for testing purposes. File fts3_test.c contains
129554 ** a Tcl interface to read and write the values.
129556 #ifdef SQLITE_TEST
129557 int test_fts3_node_chunksize = (4*1024);
129558 int test_fts3_node_chunk_threshold = (4*1024)*4;
129559 # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
129560 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
129561 #else
129562 # define FTS3_NODE_CHUNKSIZE (4*1024)
129563 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
129564 #endif
129567 ** The two values that may be meaningfully bound to the :1 parameter in
129568 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
129570 #define FTS_STAT_DOCTOTAL 0
129571 #define FTS_STAT_INCRMERGEHINT 1
129572 #define FTS_STAT_AUTOINCRMERGE 2
129575 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
129576 ** and incremental merge operation that takes place. This is used for
129577 ** debugging FTS only, it should not usually be turned on in production
129578 ** systems.
129580 #ifdef FTS3_LOG_MERGES
129581 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
129582 sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
129584 #else
129585 #define fts3LogMerge(x, y)
129586 #endif
129589 typedef struct PendingList PendingList;
129590 typedef struct SegmentNode SegmentNode;
129591 typedef struct SegmentWriter SegmentWriter;
129594 ** An instance of the following data structure is used to build doclists
129595 ** incrementally. See function fts3PendingListAppend() for details.
129597 struct PendingList {
129598 int nData;
129599 char *aData;
129600 int nSpace;
129601 sqlite3_int64 iLastDocid;
129602 sqlite3_int64 iLastCol;
129603 sqlite3_int64 iLastPos;
129608 ** Each cursor has a (possibly empty) linked list of the following objects.
129610 struct Fts3DeferredToken {
129611 Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
129612 int iCol; /* Column token must occur in */
129613 Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
129614 PendingList *pList; /* Doclist is assembled here */
129618 ** An instance of this structure is used to iterate through the terms on
129619 ** a contiguous set of segment b-tree leaf nodes. Although the details of
129620 ** this structure are only manipulated by code in this file, opaque handles
129621 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
129622 ** terms when querying the full-text index. See functions:
129624 ** sqlite3Fts3SegReaderNew()
129625 ** sqlite3Fts3SegReaderFree()
129626 ** sqlite3Fts3SegReaderIterate()
129628 ** Methods used to manipulate Fts3SegReader structures:
129630 ** fts3SegReaderNext()
129631 ** fts3SegReaderFirstDocid()
129632 ** fts3SegReaderNextDocid()
129634 struct Fts3SegReader {
129635 int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
129636 u8 bLookup; /* True for a lookup only */
129637 u8 rootOnly; /* True for a root-only reader */
129639 sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
129640 sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
129641 sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
129642 sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
129644 char *aNode; /* Pointer to node data (or NULL) */
129645 int nNode; /* Size of buffer at aNode (or 0) */
129646 int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
129647 sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
129649 Fts3HashElem **ppNextElem;
129651 /* Variables set by fts3SegReaderNext(). These may be read directly
129652 ** by the caller. They are valid from the time SegmentReaderNew() returns
129653 ** until SegmentReaderNext() returns something other than SQLITE_OK
129654 ** (i.e. SQLITE_DONE).
129656 int nTerm; /* Number of bytes in current term */
129657 char *zTerm; /* Pointer to current term */
129658 int nTermAlloc; /* Allocated size of zTerm buffer */
129659 char *aDoclist; /* Pointer to doclist of current entry */
129660 int nDoclist; /* Size of doclist in current entry */
129662 /* The following variables are used by fts3SegReaderNextDocid() to iterate
129663 ** through the current doclist (aDoclist/nDoclist).
129665 char *pOffsetList;
129666 int nOffsetList; /* For descending pending seg-readers only */
129667 sqlite3_int64 iDocid;
129670 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
129671 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
129674 ** An instance of this structure is used to create a segment b-tree in the
129675 ** database. The internal details of this type are only accessed by the
129676 ** following functions:
129678 ** fts3SegWriterAdd()
129679 ** fts3SegWriterFlush()
129680 ** fts3SegWriterFree()
129682 struct SegmentWriter {
129683 SegmentNode *pTree; /* Pointer to interior tree structure */
129684 sqlite3_int64 iFirst; /* First slot in %_segments written */
129685 sqlite3_int64 iFree; /* Next free slot in %_segments */
129686 char *zTerm; /* Pointer to previous term buffer */
129687 int nTerm; /* Number of bytes in zTerm */
129688 int nMalloc; /* Size of malloc'd buffer at zMalloc */
129689 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
129690 int nSize; /* Size of allocation at aData */
129691 int nData; /* Bytes of data in aData */
129692 char *aData; /* Pointer to block from malloc() */
129696 ** Type SegmentNode is used by the following three functions to create
129697 ** the interior part of the segment b+-tree structures (everything except
129698 ** the leaf nodes). These functions and type are only ever used by code
129699 ** within the fts3SegWriterXXX() family of functions described above.
129701 ** fts3NodeAddTerm()
129702 ** fts3NodeWrite()
129703 ** fts3NodeFree()
129705 ** When a b+tree is written to the database (either as a result of a merge
129706 ** or the pending-terms table being flushed), leaves are written into the
129707 ** database file as soon as they are completely populated. The interior of
129708 ** the tree is assembled in memory and written out only once all leaves have
129709 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
129710 ** very large, meaning that the interior of the tree consumes relatively
129711 ** little memory.
129713 struct SegmentNode {
129714 SegmentNode *pParent; /* Parent node (or NULL for root node) */
129715 SegmentNode *pRight; /* Pointer to right-sibling */
129716 SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
129717 int nEntry; /* Number of terms written to node so far */
129718 char *zTerm; /* Pointer to previous term buffer */
129719 int nTerm; /* Number of bytes in zTerm */
129720 int nMalloc; /* Size of malloc'd buffer at zMalloc */
129721 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
129722 int nData; /* Bytes of valid data so far */
129723 char *aData; /* Node data */
129727 ** Valid values for the second argument to fts3SqlStmt().
129729 #define SQL_DELETE_CONTENT 0
129730 #define SQL_IS_EMPTY 1
129731 #define SQL_DELETE_ALL_CONTENT 2
129732 #define SQL_DELETE_ALL_SEGMENTS 3
129733 #define SQL_DELETE_ALL_SEGDIR 4
129734 #define SQL_DELETE_ALL_DOCSIZE 5
129735 #define SQL_DELETE_ALL_STAT 6
129736 #define SQL_SELECT_CONTENT_BY_ROWID 7
129737 #define SQL_NEXT_SEGMENT_INDEX 8
129738 #define SQL_INSERT_SEGMENTS 9
129739 #define SQL_NEXT_SEGMENTS_ID 10
129740 #define SQL_INSERT_SEGDIR 11
129741 #define SQL_SELECT_LEVEL 12
129742 #define SQL_SELECT_LEVEL_RANGE 13
129743 #define SQL_SELECT_LEVEL_COUNT 14
129744 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
129745 #define SQL_DELETE_SEGDIR_LEVEL 16
129746 #define SQL_DELETE_SEGMENTS_RANGE 17
129747 #define SQL_CONTENT_INSERT 18
129748 #define SQL_DELETE_DOCSIZE 19
129749 #define SQL_REPLACE_DOCSIZE 20
129750 #define SQL_SELECT_DOCSIZE 21
129751 #define SQL_SELECT_STAT 22
129752 #define SQL_REPLACE_STAT 23
129754 #define SQL_SELECT_ALL_PREFIX_LEVEL 24
129755 #define SQL_DELETE_ALL_TERMS_SEGDIR 25
129756 #define SQL_DELETE_SEGDIR_RANGE 26
129757 #define SQL_SELECT_ALL_LANGID 27
129758 #define SQL_FIND_MERGE_LEVEL 28
129759 #define SQL_MAX_LEAF_NODE_ESTIMATE 29
129760 #define SQL_DELETE_SEGDIR_ENTRY 30
129761 #define SQL_SHIFT_SEGDIR_ENTRY 31
129762 #define SQL_SELECT_SEGDIR 32
129763 #define SQL_CHOMP_SEGDIR 33
129764 #define SQL_SEGMENT_IS_APPENDABLE 34
129765 #define SQL_SELECT_INDEXES 35
129766 #define SQL_SELECT_MXLEVEL 36
129769 ** This function is used to obtain an SQLite prepared statement handle
129770 ** for the statement identified by the second argument. If successful,
129771 ** *pp is set to the requested statement handle and SQLITE_OK returned.
129772 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
129774 ** If argument apVal is not NULL, then it must point to an array with
129775 ** at least as many entries as the requested statement has bound
129776 ** parameters. The values are bound to the statements parameters before
129777 ** returning.
129779 static int fts3SqlStmt(
129780 Fts3Table *p, /* Virtual table handle */
129781 int eStmt, /* One of the SQL_XXX constants above */
129782 sqlite3_stmt **pp, /* OUT: Statement handle */
129783 sqlite3_value **apVal /* Values to bind to statement */
129785 const char *azSql[] = {
129786 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
129787 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
129788 /* 2 */ "DELETE FROM %Q.'%q_content'",
129789 /* 3 */ "DELETE FROM %Q.'%q_segments'",
129790 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
129791 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
129792 /* 6 */ "DELETE FROM %Q.'%q_stat'",
129793 /* 7 */ "SELECT %s WHERE rowid=?",
129794 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
129795 /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
129796 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
129797 /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
129799 /* Return segments in order from oldest to newest.*/
129800 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
129801 "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
129802 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
129803 "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
129804 "ORDER BY level DESC, idx ASC",
129806 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
129807 /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
129809 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
129810 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
129811 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
129812 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
129813 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
129814 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
129815 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
129816 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
129817 /* 24 */ "",
129818 /* 25 */ "",
129820 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
129821 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
129823 /* This statement is used to determine which level to read the input from
129824 ** when performing an incremental merge. It returns the absolute level number
129825 ** of the oldest level in the db that contains at least ? segments. Or,
129826 ** if no level in the FTS index contains more than ? segments, the statement
129827 ** returns zero rows. */
129828 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
129829 " ORDER BY (level %% 1024) ASC LIMIT 1",
129831 /* Estimate the upper limit on the number of leaf nodes in a new segment
129832 ** created by merging the oldest :2 segments from absolute level :1. See
129833 ** function sqlite3Fts3Incrmerge() for details. */
129834 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
129835 " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
129837 /* SQL_DELETE_SEGDIR_ENTRY
129838 ** Delete the %_segdir entry on absolute level :1 with index :2. */
129839 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
129841 /* SQL_SHIFT_SEGDIR_ENTRY
129842 ** Modify the idx value for the segment with idx=:3 on absolute level :2
129843 ** to :1. */
129844 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
129846 /* SQL_SELECT_SEGDIR
129847 ** Read a single entry from the %_segdir table. The entry from absolute
129848 ** level :1 with index value :2. */
129849 /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
129850 "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
129852 /* SQL_CHOMP_SEGDIR
129853 ** Update the start_block (:1) and root (:2) fields of the %_segdir
129854 ** entry located on absolute level :3 with index :4. */
129855 /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
129856 "WHERE level = ? AND idx = ?",
129858 /* SQL_SEGMENT_IS_APPENDABLE
129859 ** Return a single row if the segment with end_block=? is appendable. Or
129860 ** no rows otherwise. */
129861 /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
129863 /* SQL_SELECT_INDEXES
129864 ** Return the list of valid segment indexes for absolute level ? */
129865 /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
129867 /* SQL_SELECT_MXLEVEL
129868 ** Return the largest relative level in the FTS index or indexes. */
129869 /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
129871 int rc = SQLITE_OK;
129872 sqlite3_stmt *pStmt;
129874 assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
129875 assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
129877 pStmt = p->aStmt[eStmt];
129878 if( !pStmt ){
129879 char *zSql;
129880 if( eStmt==SQL_CONTENT_INSERT ){
129881 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
129882 }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
129883 zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
129884 }else{
129885 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
129887 if( !zSql ){
129888 rc = SQLITE_NOMEM;
129889 }else{
129890 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
129891 sqlite3_free(zSql);
129892 assert( rc==SQLITE_OK || pStmt==0 );
129893 p->aStmt[eStmt] = pStmt;
129896 if( apVal ){
129897 int i;
129898 int nParam = sqlite3_bind_parameter_count(pStmt);
129899 for(i=0; rc==SQLITE_OK && i<nParam; i++){
129900 rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
129903 *pp = pStmt;
129904 return rc;
129908 static int fts3SelectDocsize(
129909 Fts3Table *pTab, /* FTS3 table handle */
129910 sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
129911 sqlite3_stmt **ppStmt /* OUT: Statement handle */
129913 sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
129914 int rc; /* Return code */
129916 rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
129917 if( rc==SQLITE_OK ){
129918 sqlite3_bind_int64(pStmt, 1, iDocid);
129919 rc = sqlite3_step(pStmt);
129920 if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
129921 rc = sqlite3_reset(pStmt);
129922 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
129923 pStmt = 0;
129924 }else{
129925 rc = SQLITE_OK;
129929 *ppStmt = pStmt;
129930 return rc;
129933 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
129934 Fts3Table *pTab, /* Fts3 table handle */
129935 sqlite3_stmt **ppStmt /* OUT: Statement handle */
129937 sqlite3_stmt *pStmt = 0;
129938 int rc;
129939 rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
129940 if( rc==SQLITE_OK ){
129941 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
129942 if( sqlite3_step(pStmt)!=SQLITE_ROW
129943 || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
129945 rc = sqlite3_reset(pStmt);
129946 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
129947 pStmt = 0;
129950 *ppStmt = pStmt;
129951 return rc;
129954 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
129955 Fts3Table *pTab, /* Fts3 table handle */
129956 sqlite3_int64 iDocid, /* Docid to read size data for */
129957 sqlite3_stmt **ppStmt /* OUT: Statement handle */
129959 return fts3SelectDocsize(pTab, iDocid, ppStmt);
129963 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
129964 ** array apVal[] to the SQL statement identified by eStmt, the statement
129965 ** is executed.
129967 ** Returns SQLITE_OK if the statement is successfully executed, or an
129968 ** SQLite error code otherwise.
129970 static void fts3SqlExec(
129971 int *pRC, /* Result code */
129972 Fts3Table *p, /* The FTS3 table */
129973 int eStmt, /* Index of statement to evaluate */
129974 sqlite3_value **apVal /* Parameters to bind */
129976 sqlite3_stmt *pStmt;
129977 int rc;
129978 if( *pRC ) return;
129979 rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
129980 if( rc==SQLITE_OK ){
129981 sqlite3_step(pStmt);
129982 rc = sqlite3_reset(pStmt);
129984 *pRC = rc;
129989 ** This function ensures that the caller has obtained an exclusive
129990 ** shared-cache table-lock on the %_segdir table. This is required before
129991 ** writing data to the fts3 table. If this lock is not acquired first, then
129992 ** the caller may end up attempting to take this lock as part of committing
129993 ** a transaction, causing SQLite to return SQLITE_LOCKED or
129994 ** LOCKED_SHAREDCACHEto a COMMIT command.
129996 ** It is best to avoid this because if FTS3 returns any error when
129997 ** committing a transaction, the whole transaction will be rolled back.
129998 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
129999 ** It can still happen if the user locks the underlying tables directly
130000 ** instead of accessing them via FTS.
130002 static int fts3Writelock(Fts3Table *p){
130003 int rc = SQLITE_OK;
130005 if( p->nPendingData==0 ){
130006 sqlite3_stmt *pStmt;
130007 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
130008 if( rc==SQLITE_OK ){
130009 sqlite3_bind_null(pStmt, 1);
130010 sqlite3_step(pStmt);
130011 rc = sqlite3_reset(pStmt);
130015 return rc;
130019 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
130020 ** Within each language id, a separate index is maintained to store the
130021 ** document terms, and each configured prefix size (configured the FTS
130022 ** "prefix=" option). And each index consists of multiple levels ("relative
130023 ** levels").
130025 ** All three of these values (the language id, the specific index and the
130026 ** level within the index) are encoded in 64-bit integer values stored
130027 ** in the %_segdir table on disk. This function is used to convert three
130028 ** separate component values into the single 64-bit integer value that
130029 ** can be used to query the %_segdir table.
130031 ** Specifically, each language-id/index combination is allocated 1024
130032 ** 64-bit integer level values ("absolute levels"). The main terms index
130033 ** for language-id 0 is allocate values 0-1023. The first prefix index
130034 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
130035 ** Language 1 indexes are allocated immediately following language 0.
130037 ** So, for a system with nPrefix prefix indexes configured, the block of
130038 ** absolute levels that corresponds to language-id iLangid and index
130039 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
130041 static sqlite3_int64 getAbsoluteLevel(
130042 Fts3Table *p, /* FTS3 table handle */
130043 int iLangid, /* Language id */
130044 int iIndex, /* Index in p->aIndex[] */
130045 int iLevel /* Level of segments */
130047 sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
130048 assert( iLangid>=0 );
130049 assert( p->nIndex>0 );
130050 assert( iIndex>=0 && iIndex<p->nIndex );
130052 iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
130053 return iBase + iLevel;
130057 ** Set *ppStmt to a statement handle that may be used to iterate through
130058 ** all rows in the %_segdir table, from oldest to newest. If successful,
130059 ** return SQLITE_OK. If an error occurs while preparing the statement,
130060 ** return an SQLite error code.
130062 ** There is only ever one instance of this SQL statement compiled for
130063 ** each FTS3 table.
130065 ** The statement returns the following columns from the %_segdir table:
130067 ** 0: idx
130068 ** 1: start_block
130069 ** 2: leaves_end_block
130070 ** 3: end_block
130071 ** 4: root
130073 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
130074 Fts3Table *p, /* FTS3 table */
130075 int iLangid, /* Language being queried */
130076 int iIndex, /* Index for p->aIndex[] */
130077 int iLevel, /* Level to select (relative level) */
130078 sqlite3_stmt **ppStmt /* OUT: Compiled statement */
130080 int rc;
130081 sqlite3_stmt *pStmt = 0;
130083 assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
130084 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
130085 assert( iIndex>=0 && iIndex<p->nIndex );
130087 if( iLevel<0 ){
130088 /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
130089 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
130090 if( rc==SQLITE_OK ){
130091 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
130092 sqlite3_bind_int64(pStmt, 2,
130093 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
130096 }else{
130097 /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
130098 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
130099 if( rc==SQLITE_OK ){
130100 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
130103 *ppStmt = pStmt;
130104 return rc;
130109 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
130110 ** if successful, or an SQLite error code otherwise.
130112 ** This function also serves to allocate the PendingList structure itself.
130113 ** For example, to create a new PendingList structure containing two
130114 ** varints:
130116 ** PendingList *p = 0;
130117 ** fts3PendingListAppendVarint(&p, 1);
130118 ** fts3PendingListAppendVarint(&p, 2);
130120 static int fts3PendingListAppendVarint(
130121 PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
130122 sqlite3_int64 i /* Value to append to data */
130124 PendingList *p = *pp;
130126 /* Allocate or grow the PendingList as required. */
130127 if( !p ){
130128 p = sqlite3_malloc(sizeof(*p) + 100);
130129 if( !p ){
130130 return SQLITE_NOMEM;
130132 p->nSpace = 100;
130133 p->aData = (char *)&p[1];
130134 p->nData = 0;
130136 else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
130137 int nNew = p->nSpace * 2;
130138 p = sqlite3_realloc(p, sizeof(*p) + nNew);
130139 if( !p ){
130140 sqlite3_free(*pp);
130141 *pp = 0;
130142 return SQLITE_NOMEM;
130144 p->nSpace = nNew;
130145 p->aData = (char *)&p[1];
130148 /* Append the new serialized varint to the end of the list. */
130149 p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
130150 p->aData[p->nData] = '\0';
130151 *pp = p;
130152 return SQLITE_OK;
130156 ** Add a docid/column/position entry to a PendingList structure. Non-zero
130157 ** is returned if the structure is sqlite3_realloced as part of adding
130158 ** the entry. Otherwise, zero.
130160 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
130161 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
130162 ** it is set to SQLITE_OK.
130164 static int fts3PendingListAppend(
130165 PendingList **pp, /* IN/OUT: PendingList structure */
130166 sqlite3_int64 iDocid, /* Docid for entry to add */
130167 sqlite3_int64 iCol, /* Column for entry to add */
130168 sqlite3_int64 iPos, /* Position of term for entry to add */
130169 int *pRc /* OUT: Return code */
130171 PendingList *p = *pp;
130172 int rc = SQLITE_OK;
130174 assert( !p || p->iLastDocid<=iDocid );
130176 if( !p || p->iLastDocid!=iDocid ){
130177 sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
130178 if( p ){
130179 assert( p->nData<p->nSpace );
130180 assert( p->aData[p->nData]==0 );
130181 p->nData++;
130183 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
130184 goto pendinglistappend_out;
130186 p->iLastCol = -1;
130187 p->iLastPos = 0;
130188 p->iLastDocid = iDocid;
130190 if( iCol>0 && p->iLastCol!=iCol ){
130191 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
130192 || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
130194 goto pendinglistappend_out;
130196 p->iLastCol = iCol;
130197 p->iLastPos = 0;
130199 if( iCol>=0 ){
130200 assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
130201 rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
130202 if( rc==SQLITE_OK ){
130203 p->iLastPos = iPos;
130207 pendinglistappend_out:
130208 *pRc = rc;
130209 if( p!=*pp ){
130210 *pp = p;
130211 return 1;
130213 return 0;
130217 ** Free a PendingList object allocated by fts3PendingListAppend().
130219 static void fts3PendingListDelete(PendingList *pList){
130220 sqlite3_free(pList);
130224 ** Add an entry to one of the pending-terms hash tables.
130226 static int fts3PendingTermsAddOne(
130227 Fts3Table *p,
130228 int iCol,
130229 int iPos,
130230 Fts3Hash *pHash, /* Pending terms hash table to add entry to */
130231 const char *zToken,
130232 int nToken
130234 PendingList *pList;
130235 int rc = SQLITE_OK;
130237 pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
130238 if( pList ){
130239 p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
130241 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
130242 if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
130243 /* Malloc failed while inserting the new entry. This can only
130244 ** happen if there was no previous entry for this token.
130246 assert( 0==fts3HashFind(pHash, zToken, nToken) );
130247 sqlite3_free(pList);
130248 rc = SQLITE_NOMEM;
130251 if( rc==SQLITE_OK ){
130252 p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
130254 return rc;
130258 ** Tokenize the nul-terminated string zText and add all tokens to the
130259 ** pending-terms hash-table. The docid used is that currently stored in
130260 ** p->iPrevDocid, and the column is specified by argument iCol.
130262 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
130264 static int fts3PendingTermsAdd(
130265 Fts3Table *p, /* Table into which text will be inserted */
130266 int iLangid, /* Language id to use */
130267 const char *zText, /* Text of document to be inserted */
130268 int iCol, /* Column into which text is being inserted */
130269 u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
130271 int rc;
130272 int iStart = 0;
130273 int iEnd = 0;
130274 int iPos = 0;
130275 int nWord = 0;
130277 char const *zToken;
130278 int nToken = 0;
130280 sqlite3_tokenizer *pTokenizer = p->pTokenizer;
130281 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
130282 sqlite3_tokenizer_cursor *pCsr;
130283 int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
130284 const char**,int*,int*,int*,int*);
130286 assert( pTokenizer && pModule );
130288 /* If the user has inserted a NULL value, this function may be called with
130289 ** zText==0. In this case, add zero token entries to the hash table and
130290 ** return early. */
130291 if( zText==0 ){
130292 *pnWord = 0;
130293 return SQLITE_OK;
130296 rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
130297 if( rc!=SQLITE_OK ){
130298 return rc;
130301 xNext = pModule->xNext;
130302 while( SQLITE_OK==rc
130303 && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
130305 int i;
130306 if( iPos>=nWord ) nWord = iPos+1;
130308 /* Positions cannot be negative; we use -1 as a terminator internally.
130309 ** Tokens must have a non-zero length.
130311 if( iPos<0 || !zToken || nToken<=0 ){
130312 rc = SQLITE_ERROR;
130313 break;
130316 /* Add the term to the terms index */
130317 rc = fts3PendingTermsAddOne(
130318 p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
130321 /* Add the term to each of the prefix indexes that it is not too
130322 ** short for. */
130323 for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
130324 struct Fts3Index *pIndex = &p->aIndex[i];
130325 if( nToken<pIndex->nPrefix ) continue;
130326 rc = fts3PendingTermsAddOne(
130327 p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
130332 pModule->xClose(pCsr);
130333 *pnWord += nWord;
130334 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
130338 ** Calling this function indicates that subsequent calls to
130339 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
130340 ** contents of the document with docid iDocid.
130342 static int fts3PendingTermsDocid(
130343 Fts3Table *p, /* Full-text table handle */
130344 int iLangid, /* Language id of row being written */
130345 sqlite_int64 iDocid /* Docid of row being written */
130347 assert( iLangid>=0 );
130349 /* TODO(shess) Explore whether partially flushing the buffer on
130350 ** forced-flush would provide better performance. I suspect that if
130351 ** we ordered the doclists by size and flushed the largest until the
130352 ** buffer was half empty, that would let the less frequent terms
130353 ** generate longer doclists.
130355 if( iDocid<=p->iPrevDocid
130356 || p->iPrevLangid!=iLangid
130357 || p->nPendingData>p->nMaxPendingData
130359 int rc = sqlite3Fts3PendingTermsFlush(p);
130360 if( rc!=SQLITE_OK ) return rc;
130362 p->iPrevDocid = iDocid;
130363 p->iPrevLangid = iLangid;
130364 return SQLITE_OK;
130368 ** Discard the contents of the pending-terms hash tables.
130370 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
130371 int i;
130372 for(i=0; i<p->nIndex; i++){
130373 Fts3HashElem *pElem;
130374 Fts3Hash *pHash = &p->aIndex[i].hPending;
130375 for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
130376 PendingList *pList = (PendingList *)fts3HashData(pElem);
130377 fts3PendingListDelete(pList);
130379 fts3HashClear(pHash);
130381 p->nPendingData = 0;
130385 ** This function is called by the xUpdate() method as part of an INSERT
130386 ** operation. It adds entries for each term in the new record to the
130387 ** pendingTerms hash table.
130389 ** Argument apVal is the same as the similarly named argument passed to
130390 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
130392 static int fts3InsertTerms(
130393 Fts3Table *p,
130394 int iLangid,
130395 sqlite3_value **apVal,
130396 u32 *aSz
130398 int i; /* Iterator variable */
130399 for(i=2; i<p->nColumn+2; i++){
130400 int iCol = i-2;
130401 if( p->abNotindexed[iCol]==0 ){
130402 const char *zText = (const char *)sqlite3_value_text(apVal[i]);
130403 int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
130404 if( rc!=SQLITE_OK ){
130405 return rc;
130407 aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
130410 return SQLITE_OK;
130414 ** This function is called by the xUpdate() method for an INSERT operation.
130415 ** The apVal parameter is passed a copy of the apVal argument passed by
130416 ** SQLite to the xUpdate() method. i.e:
130418 ** apVal[0] Not used for INSERT.
130419 ** apVal[1] rowid
130420 ** apVal[2] Left-most user-defined column
130421 ** ...
130422 ** apVal[p->nColumn+1] Right-most user-defined column
130423 ** apVal[p->nColumn+2] Hidden column with same name as table
130424 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
130425 ** apVal[p->nColumn+4] Hidden languageid column
130427 static int fts3InsertData(
130428 Fts3Table *p, /* Full-text table */
130429 sqlite3_value **apVal, /* Array of values to insert */
130430 sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
130432 int rc; /* Return code */
130433 sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
130435 if( p->zContentTbl ){
130436 sqlite3_value *pRowid = apVal[p->nColumn+3];
130437 if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
130438 pRowid = apVal[1];
130440 if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
130441 return SQLITE_CONSTRAINT;
130443 *piDocid = sqlite3_value_int64(pRowid);
130444 return SQLITE_OK;
130447 /* Locate the statement handle used to insert data into the %_content
130448 ** table. The SQL for this statement is:
130450 ** INSERT INTO %_content VALUES(?, ?, ?, ...)
130452 ** The statement features N '?' variables, where N is the number of user
130453 ** defined columns in the FTS3 table, plus one for the docid field.
130455 rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
130456 if( rc==SQLITE_OK && p->zLanguageid ){
130457 rc = sqlite3_bind_int(
130458 pContentInsert, p->nColumn+2,
130459 sqlite3_value_int(apVal[p->nColumn+4])
130462 if( rc!=SQLITE_OK ) return rc;
130464 /* There is a quirk here. The users INSERT statement may have specified
130465 ** a value for the "rowid" field, for the "docid" field, or for both.
130466 ** Which is a problem, since "rowid" and "docid" are aliases for the
130467 ** same value. For example:
130469 ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
130471 ** In FTS3, this is an error. It is an error to specify non-NULL values
130472 ** for both docid and some other rowid alias.
130474 if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
130475 if( SQLITE_NULL==sqlite3_value_type(apVal[0])
130476 && SQLITE_NULL!=sqlite3_value_type(apVal[1])
130478 /* A rowid/docid conflict. */
130479 return SQLITE_ERROR;
130481 rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
130482 if( rc!=SQLITE_OK ) return rc;
130485 /* Execute the statement to insert the record. Set *piDocid to the
130486 ** new docid value.
130488 sqlite3_step(pContentInsert);
130489 rc = sqlite3_reset(pContentInsert);
130491 *piDocid = sqlite3_last_insert_rowid(p->db);
130492 return rc;
130498 ** Remove all data from the FTS3 table. Clear the hash table containing
130499 ** pending terms.
130501 static int fts3DeleteAll(Fts3Table *p, int bContent){
130502 int rc = SQLITE_OK; /* Return code */
130504 /* Discard the contents of the pending-terms hash table. */
130505 sqlite3Fts3PendingTermsClear(p);
130507 /* Delete everything from the shadow tables. Except, leave %_content as
130508 ** is if bContent is false. */
130509 assert( p->zContentTbl==0 || bContent==0 );
130510 if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
130511 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
130512 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
130513 if( p->bHasDocsize ){
130514 fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
130516 if( p->bHasStat ){
130517 fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
130519 return rc;
130525 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
130526 int iLangid = 0;
130527 if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
130528 return iLangid;
130532 ** The first element in the apVal[] array is assumed to contain the docid
130533 ** (an integer) of a row about to be deleted. Remove all terms from the
130534 ** full-text index.
130536 static void fts3DeleteTerms(
130537 int *pRC, /* Result code */
130538 Fts3Table *p, /* The FTS table to delete from */
130539 sqlite3_value *pRowid, /* The docid to be deleted */
130540 u32 *aSz, /* Sizes of deleted document written here */
130541 int *pbFound /* OUT: Set to true if row really does exist */
130543 int rc;
130544 sqlite3_stmt *pSelect;
130546 assert( *pbFound==0 );
130547 if( *pRC ) return;
130548 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
130549 if( rc==SQLITE_OK ){
130550 if( SQLITE_ROW==sqlite3_step(pSelect) ){
130551 int i;
130552 int iLangid = langidFromSelect(p, pSelect);
130553 rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
130554 for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
130555 int iCol = i-1;
130556 if( p->abNotindexed[iCol]==0 ){
130557 const char *zText = (const char *)sqlite3_column_text(pSelect, i);
130558 rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
130559 aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
130562 if( rc!=SQLITE_OK ){
130563 sqlite3_reset(pSelect);
130564 *pRC = rc;
130565 return;
130567 *pbFound = 1;
130569 rc = sqlite3_reset(pSelect);
130570 }else{
130571 sqlite3_reset(pSelect);
130573 *pRC = rc;
130577 ** Forward declaration to account for the circular dependency between
130578 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
130580 static int fts3SegmentMerge(Fts3Table *, int, int, int);
130583 ** This function allocates a new level iLevel index in the segdir table.
130584 ** Usually, indexes are allocated within a level sequentially starting
130585 ** with 0, so the allocated index is one greater than the value returned
130586 ** by:
130588 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
130590 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
130591 ** level, they are merged into a single level (iLevel+1) segment and the
130592 ** allocated index is 0.
130594 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
130595 ** returned. Otherwise, an SQLite error code is returned.
130597 static int fts3AllocateSegdirIdx(
130598 Fts3Table *p,
130599 int iLangid, /* Language id */
130600 int iIndex, /* Index for p->aIndex */
130601 int iLevel,
130602 int *piIdx
130604 int rc; /* Return Code */
130605 sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
130606 int iNext = 0; /* Result of query pNextIdx */
130608 assert( iLangid>=0 );
130609 assert( p->nIndex>=1 );
130611 /* Set variable iNext to the next available segdir index at level iLevel. */
130612 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
130613 if( rc==SQLITE_OK ){
130614 sqlite3_bind_int64(
130615 pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
130617 if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
130618 iNext = sqlite3_column_int(pNextIdx, 0);
130620 rc = sqlite3_reset(pNextIdx);
130623 if( rc==SQLITE_OK ){
130624 /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
130625 ** full, merge all segments in level iLevel into a single iLevel+1
130626 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
130627 ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
130629 if( iNext>=FTS3_MERGE_COUNT ){
130630 fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
130631 rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
130632 *piIdx = 0;
130633 }else{
130634 *piIdx = iNext;
130638 return rc;
130642 ** The %_segments table is declared as follows:
130644 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
130646 ** This function reads data from a single row of the %_segments table. The
130647 ** specific row is identified by the iBlockid parameter. If paBlob is not
130648 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
130649 ** with the contents of the blob stored in the "block" column of the
130650 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
130651 ** to the size of the blob in bytes before returning.
130653 ** If an error occurs, or the table does not contain the specified row,
130654 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
130655 ** paBlob is non-NULL, then it is the responsibility of the caller to
130656 ** eventually free the returned buffer.
130658 ** This function may leave an open sqlite3_blob* handle in the
130659 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
130660 ** to this function. The handle may be closed by calling the
130661 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
130662 ** performance improvement, but the blob handle should always be closed
130663 ** before control is returned to the user (to prevent a lock being held
130664 ** on the database file for longer than necessary). Thus, any virtual table
130665 ** method (xFilter etc.) that may directly or indirectly call this function
130666 ** must call sqlite3Fts3SegmentsClose() before returning.
130668 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
130669 Fts3Table *p, /* FTS3 table handle */
130670 sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
130671 char **paBlob, /* OUT: Blob data in malloc'd buffer */
130672 int *pnBlob, /* OUT: Size of blob data */
130673 int *pnLoad /* OUT: Bytes actually loaded */
130675 int rc; /* Return code */
130677 /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
130678 assert( pnBlob );
130680 if( p->pSegments ){
130681 rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
130682 }else{
130683 if( 0==p->zSegmentsTbl ){
130684 p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
130685 if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
130687 rc = sqlite3_blob_open(
130688 p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
130692 if( rc==SQLITE_OK ){
130693 int nByte = sqlite3_blob_bytes(p->pSegments);
130694 *pnBlob = nByte;
130695 if( paBlob ){
130696 char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
130697 if( !aByte ){
130698 rc = SQLITE_NOMEM;
130699 }else{
130700 if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
130701 nByte = FTS3_NODE_CHUNKSIZE;
130702 *pnLoad = nByte;
130704 rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
130705 memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
130706 if( rc!=SQLITE_OK ){
130707 sqlite3_free(aByte);
130708 aByte = 0;
130711 *paBlob = aByte;
130715 return rc;
130719 ** Close the blob handle at p->pSegments, if it is open. See comments above
130720 ** the sqlite3Fts3ReadBlock() function for details.
130722 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
130723 sqlite3_blob_close(p->pSegments);
130724 p->pSegments = 0;
130727 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
130728 int nRead; /* Number of bytes to read */
130729 int rc; /* Return code */
130731 nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
130732 rc = sqlite3_blob_read(
130733 pReader->pBlob,
130734 &pReader->aNode[pReader->nPopulate],
130735 nRead,
130736 pReader->nPopulate
130739 if( rc==SQLITE_OK ){
130740 pReader->nPopulate += nRead;
130741 memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
130742 if( pReader->nPopulate==pReader->nNode ){
130743 sqlite3_blob_close(pReader->pBlob);
130744 pReader->pBlob = 0;
130745 pReader->nPopulate = 0;
130748 return rc;
130751 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
130752 int rc = SQLITE_OK;
130753 assert( !pReader->pBlob
130754 || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
130756 while( pReader->pBlob && rc==SQLITE_OK
130757 && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
130759 rc = fts3SegReaderIncrRead(pReader);
130761 return rc;
130765 ** Set an Fts3SegReader cursor to point at EOF.
130767 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
130768 if( !fts3SegReaderIsRootOnly(pSeg) ){
130769 sqlite3_free(pSeg->aNode);
130770 sqlite3_blob_close(pSeg->pBlob);
130771 pSeg->pBlob = 0;
130773 pSeg->aNode = 0;
130777 ** Move the iterator passed as the first argument to the next term in the
130778 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
130779 ** SQLITE_DONE. Otherwise, an SQLite error code.
130781 static int fts3SegReaderNext(
130782 Fts3Table *p,
130783 Fts3SegReader *pReader,
130784 int bIncr
130786 int rc; /* Return code of various sub-routines */
130787 char *pNext; /* Cursor variable */
130788 int nPrefix; /* Number of bytes in term prefix */
130789 int nSuffix; /* Number of bytes in term suffix */
130791 if( !pReader->aDoclist ){
130792 pNext = pReader->aNode;
130793 }else{
130794 pNext = &pReader->aDoclist[pReader->nDoclist];
130797 if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
130799 if( fts3SegReaderIsPending(pReader) ){
130800 Fts3HashElem *pElem = *(pReader->ppNextElem);
130801 if( pElem==0 ){
130802 pReader->aNode = 0;
130803 }else{
130804 PendingList *pList = (PendingList *)fts3HashData(pElem);
130805 pReader->zTerm = (char *)fts3HashKey(pElem);
130806 pReader->nTerm = fts3HashKeysize(pElem);
130807 pReader->nNode = pReader->nDoclist = pList->nData + 1;
130808 pReader->aNode = pReader->aDoclist = pList->aData;
130809 pReader->ppNextElem++;
130810 assert( pReader->aNode );
130812 return SQLITE_OK;
130815 fts3SegReaderSetEof(pReader);
130817 /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
130818 ** blocks have already been traversed. */
130819 assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
130820 if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
130821 return SQLITE_OK;
130824 rc = sqlite3Fts3ReadBlock(
130825 p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
130826 (bIncr ? &pReader->nPopulate : 0)
130828 if( rc!=SQLITE_OK ) return rc;
130829 assert( pReader->pBlob==0 );
130830 if( bIncr && pReader->nPopulate<pReader->nNode ){
130831 pReader->pBlob = p->pSegments;
130832 p->pSegments = 0;
130834 pNext = pReader->aNode;
130837 assert( !fts3SegReaderIsPending(pReader) );
130839 rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
130840 if( rc!=SQLITE_OK ) return rc;
130842 /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
130843 ** safe (no risk of overread) even if the node data is corrupted. */
130844 pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
130845 pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
130846 if( nPrefix<0 || nSuffix<=0
130847 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
130849 return FTS_CORRUPT_VTAB;
130852 if( nPrefix+nSuffix>pReader->nTermAlloc ){
130853 int nNew = (nPrefix+nSuffix)*2;
130854 char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
130855 if( !zNew ){
130856 return SQLITE_NOMEM;
130858 pReader->zTerm = zNew;
130859 pReader->nTermAlloc = nNew;
130862 rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
130863 if( rc!=SQLITE_OK ) return rc;
130865 memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
130866 pReader->nTerm = nPrefix+nSuffix;
130867 pNext += nSuffix;
130868 pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
130869 pReader->aDoclist = pNext;
130870 pReader->pOffsetList = 0;
130872 /* Check that the doclist does not appear to extend past the end of the
130873 ** b-tree node. And that the final byte of the doclist is 0x00. If either
130874 ** of these statements is untrue, then the data structure is corrupt.
130876 if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
130877 || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
130879 return FTS_CORRUPT_VTAB;
130881 return SQLITE_OK;
130885 ** Set the SegReader to point to the first docid in the doclist associated
130886 ** with the current term.
130888 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
130889 int rc = SQLITE_OK;
130890 assert( pReader->aDoclist );
130891 assert( !pReader->pOffsetList );
130892 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
130893 u8 bEof = 0;
130894 pReader->iDocid = 0;
130895 pReader->nOffsetList = 0;
130896 sqlite3Fts3DoclistPrev(0,
130897 pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
130898 &pReader->iDocid, &pReader->nOffsetList, &bEof
130900 }else{
130901 rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
130902 if( rc==SQLITE_OK ){
130903 int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
130904 pReader->pOffsetList = &pReader->aDoclist[n];
130907 return rc;
130911 ** Advance the SegReader to point to the next docid in the doclist
130912 ** associated with the current term.
130914 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
130915 ** *ppOffsetList is set to point to the first column-offset list
130916 ** in the doclist entry (i.e. immediately past the docid varint).
130917 ** *pnOffsetList is set to the length of the set of column-offset
130918 ** lists, not including the nul-terminator byte. For example:
130920 static int fts3SegReaderNextDocid(
130921 Fts3Table *pTab,
130922 Fts3SegReader *pReader, /* Reader to advance to next docid */
130923 char **ppOffsetList, /* OUT: Pointer to current position-list */
130924 int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
130926 int rc = SQLITE_OK;
130927 char *p = pReader->pOffsetList;
130928 char c = 0;
130930 assert( p );
130932 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
130933 /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
130934 ** Pending-terms doclists are always built up in ascending order, so
130935 ** we have to iterate through them backwards here. */
130936 u8 bEof = 0;
130937 if( ppOffsetList ){
130938 *ppOffsetList = pReader->pOffsetList;
130939 *pnOffsetList = pReader->nOffsetList - 1;
130941 sqlite3Fts3DoclistPrev(0,
130942 pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
130943 &pReader->nOffsetList, &bEof
130945 if( bEof ){
130946 pReader->pOffsetList = 0;
130947 }else{
130948 pReader->pOffsetList = p;
130950 }else{
130951 char *pEnd = &pReader->aDoclist[pReader->nDoclist];
130953 /* Pointer p currently points at the first byte of an offset list. The
130954 ** following block advances it to point one byte past the end of
130955 ** the same offset list. */
130956 while( 1 ){
130958 /* The following line of code (and the "p++" below the while() loop) is
130959 ** normally all that is required to move pointer p to the desired
130960 ** position. The exception is if this node is being loaded from disk
130961 ** incrementally and pointer "p" now points to the first byte past
130962 ** the populated part of pReader->aNode[].
130964 while( *p | c ) c = *p++ & 0x80;
130965 assert( *p==0 );
130967 if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
130968 rc = fts3SegReaderIncrRead(pReader);
130969 if( rc!=SQLITE_OK ) return rc;
130973 /* If required, populate the output variables with a pointer to and the
130974 ** size of the previous offset-list.
130976 if( ppOffsetList ){
130977 *ppOffsetList = pReader->pOffsetList;
130978 *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
130981 /* List may have been edited in place by fts3EvalNearTrim() */
130982 while( p<pEnd && *p==0 ) p++;
130984 /* If there are no more entries in the doclist, set pOffsetList to
130985 ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
130986 ** Fts3SegReader.pOffsetList to point to the next offset list before
130987 ** returning.
130989 if( p>=pEnd ){
130990 pReader->pOffsetList = 0;
130991 }else{
130992 rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
130993 if( rc==SQLITE_OK ){
130994 sqlite3_int64 iDelta;
130995 pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
130996 if( pTab->bDescIdx ){
130997 pReader->iDocid -= iDelta;
130998 }else{
130999 pReader->iDocid += iDelta;
131005 return SQLITE_OK;
131009 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
131010 Fts3Cursor *pCsr,
131011 Fts3MultiSegReader *pMsr,
131012 int *pnOvfl
131014 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
131015 int nOvfl = 0;
131016 int ii;
131017 int rc = SQLITE_OK;
131018 int pgsz = p->nPgsz;
131020 assert( p->bFts4 );
131021 assert( pgsz>0 );
131023 for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
131024 Fts3SegReader *pReader = pMsr->apSegment[ii];
131025 if( !fts3SegReaderIsPending(pReader)
131026 && !fts3SegReaderIsRootOnly(pReader)
131028 sqlite3_int64 jj;
131029 for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
131030 int nBlob;
131031 rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
131032 if( rc!=SQLITE_OK ) break;
131033 if( (nBlob+35)>pgsz ){
131034 nOvfl += (nBlob + 34)/pgsz;
131039 *pnOvfl = nOvfl;
131040 return rc;
131044 ** Free all allocations associated with the iterator passed as the
131045 ** second argument.
131047 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
131048 if( pReader && !fts3SegReaderIsPending(pReader) ){
131049 sqlite3_free(pReader->zTerm);
131050 if( !fts3SegReaderIsRootOnly(pReader) ){
131051 sqlite3_free(pReader->aNode);
131052 sqlite3_blob_close(pReader->pBlob);
131055 sqlite3_free(pReader);
131059 ** Allocate a new SegReader object.
131061 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
131062 int iAge, /* Segment "age". */
131063 int bLookup, /* True for a lookup only */
131064 sqlite3_int64 iStartLeaf, /* First leaf to traverse */
131065 sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
131066 sqlite3_int64 iEndBlock, /* Final block of segment */
131067 const char *zRoot, /* Buffer containing root node */
131068 int nRoot, /* Size of buffer containing root node */
131069 Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
131071 Fts3SegReader *pReader; /* Newly allocated SegReader object */
131072 int nExtra = 0; /* Bytes to allocate segment root node */
131074 assert( iStartLeaf<=iEndLeaf );
131075 if( iStartLeaf==0 ){
131076 nExtra = nRoot + FTS3_NODE_PADDING;
131079 pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
131080 if( !pReader ){
131081 return SQLITE_NOMEM;
131083 memset(pReader, 0, sizeof(Fts3SegReader));
131084 pReader->iIdx = iAge;
131085 pReader->bLookup = bLookup!=0;
131086 pReader->iStartBlock = iStartLeaf;
131087 pReader->iLeafEndBlock = iEndLeaf;
131088 pReader->iEndBlock = iEndBlock;
131090 if( nExtra ){
131091 /* The entire segment is stored in the root node. */
131092 pReader->aNode = (char *)&pReader[1];
131093 pReader->rootOnly = 1;
131094 pReader->nNode = nRoot;
131095 memcpy(pReader->aNode, zRoot, nRoot);
131096 memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
131097 }else{
131098 pReader->iCurrentBlock = iStartLeaf-1;
131100 *ppReader = pReader;
131101 return SQLITE_OK;
131105 ** This is a comparison function used as a qsort() callback when sorting
131106 ** an array of pending terms by term. This occurs as part of flushing
131107 ** the contents of the pending-terms hash table to the database.
131109 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
131110 char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
131111 char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
131112 int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
131113 int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
131115 int n = (n1<n2 ? n1 : n2);
131116 int c = memcmp(z1, z2, n);
131117 if( c==0 ){
131118 c = n1 - n2;
131120 return c;
131124 ** This function is used to allocate an Fts3SegReader that iterates through
131125 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
131127 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
131128 ** through each term in the pending-terms table. Or, if isPrefixIter is
131129 ** non-zero, it iterates through each term and its prefixes. For example, if
131130 ** the pending terms hash table contains the terms "sqlite", "mysql" and
131131 ** "firebird", then the iterator visits the following 'terms' (in the order
131132 ** shown):
131134 ** f fi fir fire fireb firebi firebir firebird
131135 ** m my mys mysq mysql
131136 ** s sq sql sqli sqlit sqlite
131138 ** Whereas if isPrefixIter is zero, the terms visited are:
131140 ** firebird mysql sqlite
131142 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
131143 Fts3Table *p, /* Virtual table handle */
131144 int iIndex, /* Index for p->aIndex */
131145 const char *zTerm, /* Term to search for */
131146 int nTerm, /* Size of buffer zTerm */
131147 int bPrefix, /* True for a prefix iterator */
131148 Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
131150 Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
131151 Fts3HashElem *pE; /* Iterator variable */
131152 Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
131153 int nElem = 0; /* Size of array at aElem */
131154 int rc = SQLITE_OK; /* Return Code */
131155 Fts3Hash *pHash;
131157 pHash = &p->aIndex[iIndex].hPending;
131158 if( bPrefix ){
131159 int nAlloc = 0; /* Size of allocated array at aElem */
131161 for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
131162 char *zKey = (char *)fts3HashKey(pE);
131163 int nKey = fts3HashKeysize(pE);
131164 if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
131165 if( nElem==nAlloc ){
131166 Fts3HashElem **aElem2;
131167 nAlloc += 16;
131168 aElem2 = (Fts3HashElem **)sqlite3_realloc(
131169 aElem, nAlloc*sizeof(Fts3HashElem *)
131171 if( !aElem2 ){
131172 rc = SQLITE_NOMEM;
131173 nElem = 0;
131174 break;
131176 aElem = aElem2;
131179 aElem[nElem++] = pE;
131183 /* If more than one term matches the prefix, sort the Fts3HashElem
131184 ** objects in term order using qsort(). This uses the same comparison
131185 ** callback as is used when flushing terms to disk.
131187 if( nElem>1 ){
131188 qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
131191 }else{
131192 /* The query is a simple term lookup that matches at most one term in
131193 ** the index. All that is required is a straight hash-lookup.
131195 ** Because the stack address of pE may be accessed via the aElem pointer
131196 ** below, the "Fts3HashElem *pE" must be declared so that it is valid
131197 ** within this entire function, not just this "else{...}" block.
131199 pE = fts3HashFindElem(pHash, zTerm, nTerm);
131200 if( pE ){
131201 aElem = &pE;
131202 nElem = 1;
131206 if( nElem>0 ){
131207 int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
131208 pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
131209 if( !pReader ){
131210 rc = SQLITE_NOMEM;
131211 }else{
131212 memset(pReader, 0, nByte);
131213 pReader->iIdx = 0x7FFFFFFF;
131214 pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
131215 memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
131219 if( bPrefix ){
131220 sqlite3_free(aElem);
131222 *ppReader = pReader;
131223 return rc;
131227 ** Compare the entries pointed to by two Fts3SegReader structures.
131228 ** Comparison is as follows:
131230 ** 1) EOF is greater than not EOF.
131232 ** 2) The current terms (if any) are compared using memcmp(). If one
131233 ** term is a prefix of another, the longer term is considered the
131234 ** larger.
131236 ** 3) By segment age. An older segment is considered larger.
131238 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
131239 int rc;
131240 if( pLhs->aNode && pRhs->aNode ){
131241 int rc2 = pLhs->nTerm - pRhs->nTerm;
131242 if( rc2<0 ){
131243 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
131244 }else{
131245 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
131247 if( rc==0 ){
131248 rc = rc2;
131250 }else{
131251 rc = (pLhs->aNode==0) - (pRhs->aNode==0);
131253 if( rc==0 ){
131254 rc = pRhs->iIdx - pLhs->iIdx;
131256 assert( rc!=0 );
131257 return rc;
131261 ** A different comparison function for SegReader structures. In this
131262 ** version, it is assumed that each SegReader points to an entry in
131263 ** a doclist for identical terms. Comparison is made as follows:
131265 ** 1) EOF (end of doclist in this case) is greater than not EOF.
131267 ** 2) By current docid.
131269 ** 3) By segment age. An older segment is considered larger.
131271 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
131272 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
131273 if( rc==0 ){
131274 if( pLhs->iDocid==pRhs->iDocid ){
131275 rc = pRhs->iIdx - pLhs->iIdx;
131276 }else{
131277 rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
131280 assert( pLhs->aNode && pRhs->aNode );
131281 return rc;
131283 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
131284 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
131285 if( rc==0 ){
131286 if( pLhs->iDocid==pRhs->iDocid ){
131287 rc = pRhs->iIdx - pLhs->iIdx;
131288 }else{
131289 rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
131292 assert( pLhs->aNode && pRhs->aNode );
131293 return rc;
131297 ** Compare the term that the Fts3SegReader object passed as the first argument
131298 ** points to with the term specified by arguments zTerm and nTerm.
131300 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
131301 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
131302 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
131304 static int fts3SegReaderTermCmp(
131305 Fts3SegReader *pSeg, /* Segment reader object */
131306 const char *zTerm, /* Term to compare to */
131307 int nTerm /* Size of term zTerm in bytes */
131309 int res = 0;
131310 if( pSeg->aNode ){
131311 if( pSeg->nTerm>nTerm ){
131312 res = memcmp(pSeg->zTerm, zTerm, nTerm);
131313 }else{
131314 res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
131316 if( res==0 ){
131317 res = pSeg->nTerm-nTerm;
131320 return res;
131324 ** Argument apSegment is an array of nSegment elements. It is known that
131325 ** the final (nSegment-nSuspect) members are already in sorted order
131326 ** (according to the comparison function provided). This function shuffles
131327 ** the array around until all entries are in sorted order.
131329 static void fts3SegReaderSort(
131330 Fts3SegReader **apSegment, /* Array to sort entries of */
131331 int nSegment, /* Size of apSegment array */
131332 int nSuspect, /* Unsorted entry count */
131333 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
131335 int i; /* Iterator variable */
131337 assert( nSuspect<=nSegment );
131339 if( nSuspect==nSegment ) nSuspect--;
131340 for(i=nSuspect-1; i>=0; i--){
131341 int j;
131342 for(j=i; j<(nSegment-1); j++){
131343 Fts3SegReader *pTmp;
131344 if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
131345 pTmp = apSegment[j+1];
131346 apSegment[j+1] = apSegment[j];
131347 apSegment[j] = pTmp;
131351 #ifndef NDEBUG
131352 /* Check that the list really is sorted now. */
131353 for(i=0; i<(nSuspect-1); i++){
131354 assert( xCmp(apSegment[i], apSegment[i+1])<0 );
131356 #endif
131360 ** Insert a record into the %_segments table.
131362 static int fts3WriteSegment(
131363 Fts3Table *p, /* Virtual table handle */
131364 sqlite3_int64 iBlock, /* Block id for new block */
131365 char *z, /* Pointer to buffer containing block data */
131366 int n /* Size of buffer z in bytes */
131368 sqlite3_stmt *pStmt;
131369 int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
131370 if( rc==SQLITE_OK ){
131371 sqlite3_bind_int64(pStmt, 1, iBlock);
131372 sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
131373 sqlite3_step(pStmt);
131374 rc = sqlite3_reset(pStmt);
131376 return rc;
131380 ** Find the largest relative level number in the table. If successful, set
131381 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
131382 ** set *pnMax to zero and return an SQLite error code.
131384 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
131385 int rc;
131386 int mxLevel = 0;
131387 sqlite3_stmt *pStmt = 0;
131389 rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
131390 if( rc==SQLITE_OK ){
131391 if( SQLITE_ROW==sqlite3_step(pStmt) ){
131392 mxLevel = sqlite3_column_int(pStmt, 0);
131394 rc = sqlite3_reset(pStmt);
131396 *pnMax = mxLevel;
131397 return rc;
131401 ** Insert a record into the %_segdir table.
131403 static int fts3WriteSegdir(
131404 Fts3Table *p, /* Virtual table handle */
131405 sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
131406 int iIdx, /* Value for "idx" field */
131407 sqlite3_int64 iStartBlock, /* Value for "start_block" field */
131408 sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
131409 sqlite3_int64 iEndBlock, /* Value for "end_block" field */
131410 char *zRoot, /* Blob value for "root" field */
131411 int nRoot /* Number of bytes in buffer zRoot */
131413 sqlite3_stmt *pStmt;
131414 int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
131415 if( rc==SQLITE_OK ){
131416 sqlite3_bind_int64(pStmt, 1, iLevel);
131417 sqlite3_bind_int(pStmt, 2, iIdx);
131418 sqlite3_bind_int64(pStmt, 3, iStartBlock);
131419 sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
131420 sqlite3_bind_int64(pStmt, 5, iEndBlock);
131421 sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
131422 sqlite3_step(pStmt);
131423 rc = sqlite3_reset(pStmt);
131425 return rc;
131429 ** Return the size of the common prefix (if any) shared by zPrev and
131430 ** zNext, in bytes. For example,
131432 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
131433 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
131434 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
131436 static int fts3PrefixCompress(
131437 const char *zPrev, /* Buffer containing previous term */
131438 int nPrev, /* Size of buffer zPrev in bytes */
131439 const char *zNext, /* Buffer containing next term */
131440 int nNext /* Size of buffer zNext in bytes */
131442 int n;
131443 UNUSED_PARAMETER(nNext);
131444 for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
131445 return n;
131449 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
131450 ** (according to memcmp) than the previous term.
131452 static int fts3NodeAddTerm(
131453 Fts3Table *p, /* Virtual table handle */
131454 SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
131455 int isCopyTerm, /* True if zTerm/nTerm is transient */
131456 const char *zTerm, /* Pointer to buffer containing term */
131457 int nTerm /* Size of term in bytes */
131459 SegmentNode *pTree = *ppTree;
131460 int rc;
131461 SegmentNode *pNew;
131463 /* First try to append the term to the current node. Return early if
131464 ** this is possible.
131466 if( pTree ){
131467 int nData = pTree->nData; /* Current size of node in bytes */
131468 int nReq = nData; /* Required space after adding zTerm */
131469 int nPrefix; /* Number of bytes of prefix compression */
131470 int nSuffix; /* Suffix length */
131472 nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
131473 nSuffix = nTerm-nPrefix;
131475 nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
131476 if( nReq<=p->nNodeSize || !pTree->zTerm ){
131478 if( nReq>p->nNodeSize ){
131479 /* An unusual case: this is the first term to be added to the node
131480 ** and the static node buffer (p->nNodeSize bytes) is not large
131481 ** enough. Use a separately malloced buffer instead This wastes
131482 ** p->nNodeSize bytes, but since this scenario only comes about when
131483 ** the database contain two terms that share a prefix of almost 2KB,
131484 ** this is not expected to be a serious problem.
131486 assert( pTree->aData==(char *)&pTree[1] );
131487 pTree->aData = (char *)sqlite3_malloc(nReq);
131488 if( !pTree->aData ){
131489 return SQLITE_NOMEM;
131493 if( pTree->zTerm ){
131494 /* There is no prefix-length field for first term in a node */
131495 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
131498 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
131499 memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
131500 pTree->nData = nData + nSuffix;
131501 pTree->nEntry++;
131503 if( isCopyTerm ){
131504 if( pTree->nMalloc<nTerm ){
131505 char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
131506 if( !zNew ){
131507 return SQLITE_NOMEM;
131509 pTree->nMalloc = nTerm*2;
131510 pTree->zMalloc = zNew;
131512 pTree->zTerm = pTree->zMalloc;
131513 memcpy(pTree->zTerm, zTerm, nTerm);
131514 pTree->nTerm = nTerm;
131515 }else{
131516 pTree->zTerm = (char *)zTerm;
131517 pTree->nTerm = nTerm;
131519 return SQLITE_OK;
131523 /* If control flows to here, it was not possible to append zTerm to the
131524 ** current node. Create a new node (a right-sibling of the current node).
131525 ** If this is the first node in the tree, the term is added to it.
131527 ** Otherwise, the term is not added to the new node, it is left empty for
131528 ** now. Instead, the term is inserted into the parent of pTree. If pTree
131529 ** has no parent, one is created here.
131531 pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
131532 if( !pNew ){
131533 return SQLITE_NOMEM;
131535 memset(pNew, 0, sizeof(SegmentNode));
131536 pNew->nData = 1 + FTS3_VARINT_MAX;
131537 pNew->aData = (char *)&pNew[1];
131539 if( pTree ){
131540 SegmentNode *pParent = pTree->pParent;
131541 rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
131542 if( pTree->pParent==0 ){
131543 pTree->pParent = pParent;
131545 pTree->pRight = pNew;
131546 pNew->pLeftmost = pTree->pLeftmost;
131547 pNew->pParent = pParent;
131548 pNew->zMalloc = pTree->zMalloc;
131549 pNew->nMalloc = pTree->nMalloc;
131550 pTree->zMalloc = 0;
131551 }else{
131552 pNew->pLeftmost = pNew;
131553 rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
131556 *ppTree = pNew;
131557 return rc;
131561 ** Helper function for fts3NodeWrite().
131563 static int fts3TreeFinishNode(
131564 SegmentNode *pTree,
131565 int iHeight,
131566 sqlite3_int64 iLeftChild
131568 int nStart;
131569 assert( iHeight>=1 && iHeight<128 );
131570 nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
131571 pTree->aData[nStart] = (char)iHeight;
131572 sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
131573 return nStart;
131577 ** Write the buffer for the segment node pTree and all of its peers to the
131578 ** database. Then call this function recursively to write the parent of
131579 ** pTree and its peers to the database.
131581 ** Except, if pTree is a root node, do not write it to the database. Instead,
131582 ** set output variables *paRoot and *pnRoot to contain the root node.
131584 ** If successful, SQLITE_OK is returned and output variable *piLast is
131585 ** set to the largest blockid written to the database (or zero if no
131586 ** blocks were written to the db). Otherwise, an SQLite error code is
131587 ** returned.
131589 static int fts3NodeWrite(
131590 Fts3Table *p, /* Virtual table handle */
131591 SegmentNode *pTree, /* SegmentNode handle */
131592 int iHeight, /* Height of this node in tree */
131593 sqlite3_int64 iLeaf, /* Block id of first leaf node */
131594 sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
131595 sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
131596 char **paRoot, /* OUT: Data for root node */
131597 int *pnRoot /* OUT: Size of root node in bytes */
131599 int rc = SQLITE_OK;
131601 if( !pTree->pParent ){
131602 /* Root node of the tree. */
131603 int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
131604 *piLast = iFree-1;
131605 *pnRoot = pTree->nData - nStart;
131606 *paRoot = &pTree->aData[nStart];
131607 }else{
131608 SegmentNode *pIter;
131609 sqlite3_int64 iNextFree = iFree;
131610 sqlite3_int64 iNextLeaf = iLeaf;
131611 for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
131612 int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
131613 int nWrite = pIter->nData - nStart;
131615 rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
131616 iNextFree++;
131617 iNextLeaf += (pIter->nEntry+1);
131619 if( rc==SQLITE_OK ){
131620 assert( iNextLeaf==iFree );
131621 rc = fts3NodeWrite(
131622 p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
131627 return rc;
131631 ** Free all memory allocations associated with the tree pTree.
131633 static void fts3NodeFree(SegmentNode *pTree){
131634 if( pTree ){
131635 SegmentNode *p = pTree->pLeftmost;
131636 fts3NodeFree(p->pParent);
131637 while( p ){
131638 SegmentNode *pRight = p->pRight;
131639 if( p->aData!=(char *)&p[1] ){
131640 sqlite3_free(p->aData);
131642 assert( pRight==0 || p->zMalloc==0 );
131643 sqlite3_free(p->zMalloc);
131644 sqlite3_free(p);
131645 p = pRight;
131651 ** Add a term to the segment being constructed by the SegmentWriter object
131652 ** *ppWriter. When adding the first term to a segment, *ppWriter should
131653 ** be passed NULL. This function will allocate a new SegmentWriter object
131654 ** and return it via the input/output variable *ppWriter in this case.
131656 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
131658 static int fts3SegWriterAdd(
131659 Fts3Table *p, /* Virtual table handle */
131660 SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
131661 int isCopyTerm, /* True if buffer zTerm must be copied */
131662 const char *zTerm, /* Pointer to buffer containing term */
131663 int nTerm, /* Size of term in bytes */
131664 const char *aDoclist, /* Pointer to buffer containing doclist */
131665 int nDoclist /* Size of doclist in bytes */
131667 int nPrefix; /* Size of term prefix in bytes */
131668 int nSuffix; /* Size of term suffix in bytes */
131669 int nReq; /* Number of bytes required on leaf page */
131670 int nData;
131671 SegmentWriter *pWriter = *ppWriter;
131673 if( !pWriter ){
131674 int rc;
131675 sqlite3_stmt *pStmt;
131677 /* Allocate the SegmentWriter structure */
131678 pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
131679 if( !pWriter ) return SQLITE_NOMEM;
131680 memset(pWriter, 0, sizeof(SegmentWriter));
131681 *ppWriter = pWriter;
131683 /* Allocate a buffer in which to accumulate data */
131684 pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
131685 if( !pWriter->aData ) return SQLITE_NOMEM;
131686 pWriter->nSize = p->nNodeSize;
131688 /* Find the next free blockid in the %_segments table */
131689 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
131690 if( rc!=SQLITE_OK ) return rc;
131691 if( SQLITE_ROW==sqlite3_step(pStmt) ){
131692 pWriter->iFree = sqlite3_column_int64(pStmt, 0);
131693 pWriter->iFirst = pWriter->iFree;
131695 rc = sqlite3_reset(pStmt);
131696 if( rc!=SQLITE_OK ) return rc;
131698 nData = pWriter->nData;
131700 nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
131701 nSuffix = nTerm-nPrefix;
131703 /* Figure out how many bytes are required by this new entry */
131704 nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
131705 sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
131706 nSuffix + /* Term suffix */
131707 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
131708 nDoclist; /* Doclist data */
131710 if( nData>0 && nData+nReq>p->nNodeSize ){
131711 int rc;
131713 /* The current leaf node is full. Write it out to the database. */
131714 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
131715 if( rc!=SQLITE_OK ) return rc;
131716 p->nLeafAdd++;
131718 /* Add the current term to the interior node tree. The term added to
131719 ** the interior tree must:
131721 ** a) be greater than the largest term on the leaf node just written
131722 ** to the database (still available in pWriter->zTerm), and
131724 ** b) be less than or equal to the term about to be added to the new
131725 ** leaf node (zTerm/nTerm).
131727 ** In other words, it must be the prefix of zTerm 1 byte longer than
131728 ** the common prefix (if any) of zTerm and pWriter->zTerm.
131730 assert( nPrefix<nTerm );
131731 rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
131732 if( rc!=SQLITE_OK ) return rc;
131734 nData = 0;
131735 pWriter->nTerm = 0;
131737 nPrefix = 0;
131738 nSuffix = nTerm;
131739 nReq = 1 + /* varint containing prefix size */
131740 sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
131741 nTerm + /* Term suffix */
131742 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
131743 nDoclist; /* Doclist data */
131746 /* If the buffer currently allocated is too small for this entry, realloc
131747 ** the buffer to make it large enough.
131749 if( nReq>pWriter->nSize ){
131750 char *aNew = sqlite3_realloc(pWriter->aData, nReq);
131751 if( !aNew ) return SQLITE_NOMEM;
131752 pWriter->aData = aNew;
131753 pWriter->nSize = nReq;
131755 assert( nData+nReq<=pWriter->nSize );
131757 /* Append the prefix-compressed term and doclist to the buffer. */
131758 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
131759 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
131760 memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
131761 nData += nSuffix;
131762 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
131763 memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
131764 pWriter->nData = nData + nDoclist;
131766 /* Save the current term so that it can be used to prefix-compress the next.
131767 ** If the isCopyTerm parameter is true, then the buffer pointed to by
131768 ** zTerm is transient, so take a copy of the term data. Otherwise, just
131769 ** store a copy of the pointer.
131771 if( isCopyTerm ){
131772 if( nTerm>pWriter->nMalloc ){
131773 char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
131774 if( !zNew ){
131775 return SQLITE_NOMEM;
131777 pWriter->nMalloc = nTerm*2;
131778 pWriter->zMalloc = zNew;
131779 pWriter->zTerm = zNew;
131781 assert( pWriter->zTerm==pWriter->zMalloc );
131782 memcpy(pWriter->zTerm, zTerm, nTerm);
131783 }else{
131784 pWriter->zTerm = (char *)zTerm;
131786 pWriter->nTerm = nTerm;
131788 return SQLITE_OK;
131792 ** Flush all data associated with the SegmentWriter object pWriter to the
131793 ** database. This function must be called after all terms have been added
131794 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
131795 ** returned. Otherwise, an SQLite error code.
131797 static int fts3SegWriterFlush(
131798 Fts3Table *p, /* Virtual table handle */
131799 SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
131800 sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
131801 int iIdx /* Value for 'idx' column of %_segdir */
131803 int rc; /* Return code */
131804 if( pWriter->pTree ){
131805 sqlite3_int64 iLast = 0; /* Largest block id written to database */
131806 sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
131807 char *zRoot = NULL; /* Pointer to buffer containing root node */
131808 int nRoot = 0; /* Size of buffer zRoot */
131810 iLastLeaf = pWriter->iFree;
131811 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
131812 if( rc==SQLITE_OK ){
131813 rc = fts3NodeWrite(p, pWriter->pTree, 1,
131814 pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
131816 if( rc==SQLITE_OK ){
131817 rc = fts3WriteSegdir(
131818 p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
131820 }else{
131821 /* The entire tree fits on the root node. Write it to the segdir table. */
131822 rc = fts3WriteSegdir(
131823 p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
131825 p->nLeafAdd++;
131826 return rc;
131830 ** Release all memory held by the SegmentWriter object passed as the
131831 ** first argument.
131833 static void fts3SegWriterFree(SegmentWriter *pWriter){
131834 if( pWriter ){
131835 sqlite3_free(pWriter->aData);
131836 sqlite3_free(pWriter->zMalloc);
131837 fts3NodeFree(pWriter->pTree);
131838 sqlite3_free(pWriter);
131843 ** The first value in the apVal[] array is assumed to contain an integer.
131844 ** This function tests if there exist any documents with docid values that
131845 ** are different from that integer. i.e. if deleting the document with docid
131846 ** pRowid would mean the FTS3 table were empty.
131848 ** If successful, *pisEmpty is set to true if the table is empty except for
131849 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
131850 ** error occurs, an SQLite error code is returned.
131852 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
131853 sqlite3_stmt *pStmt;
131854 int rc;
131855 if( p->zContentTbl ){
131856 /* If using the content=xxx option, assume the table is never empty */
131857 *pisEmpty = 0;
131858 rc = SQLITE_OK;
131859 }else{
131860 rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
131861 if( rc==SQLITE_OK ){
131862 if( SQLITE_ROW==sqlite3_step(pStmt) ){
131863 *pisEmpty = sqlite3_column_int(pStmt, 0);
131865 rc = sqlite3_reset(pStmt);
131868 return rc;
131872 ** Set *pnMax to the largest segment level in the database for the index
131873 ** iIndex.
131875 ** Segment levels are stored in the 'level' column of the %_segdir table.
131877 ** Return SQLITE_OK if successful, or an SQLite error code if not.
131879 static int fts3SegmentMaxLevel(
131880 Fts3Table *p,
131881 int iLangid,
131882 int iIndex,
131883 sqlite3_int64 *pnMax
131885 sqlite3_stmt *pStmt;
131886 int rc;
131887 assert( iIndex>=0 && iIndex<p->nIndex );
131889 /* Set pStmt to the compiled version of:
131891 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
131893 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
131895 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
131896 if( rc!=SQLITE_OK ) return rc;
131897 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
131898 sqlite3_bind_int64(pStmt, 2,
131899 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
131901 if( SQLITE_ROW==sqlite3_step(pStmt) ){
131902 *pnMax = sqlite3_column_int64(pStmt, 0);
131904 return sqlite3_reset(pStmt);
131908 ** Delete all entries in the %_segments table associated with the segment
131909 ** opened with seg-reader pSeg. This function does not affect the contents
131910 ** of the %_segdir table.
131912 static int fts3DeleteSegment(
131913 Fts3Table *p, /* FTS table handle */
131914 Fts3SegReader *pSeg /* Segment to delete */
131916 int rc = SQLITE_OK; /* Return code */
131917 if( pSeg->iStartBlock ){
131918 sqlite3_stmt *pDelete; /* SQL statement to delete rows */
131919 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
131920 if( rc==SQLITE_OK ){
131921 sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
131922 sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
131923 sqlite3_step(pDelete);
131924 rc = sqlite3_reset(pDelete);
131927 return rc;
131931 ** This function is used after merging multiple segments into a single large
131932 ** segment to delete the old, now redundant, segment b-trees. Specifically,
131933 ** it:
131935 ** 1) Deletes all %_segments entries for the segments associated with
131936 ** each of the SegReader objects in the array passed as the third
131937 ** argument, and
131939 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
131940 ** entries regardless of level if (iLevel<0).
131942 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
131944 static int fts3DeleteSegdir(
131945 Fts3Table *p, /* Virtual table handle */
131946 int iLangid, /* Language id */
131947 int iIndex, /* Index for p->aIndex */
131948 int iLevel, /* Level of %_segdir entries to delete */
131949 Fts3SegReader **apSegment, /* Array of SegReader objects */
131950 int nReader /* Size of array apSegment */
131952 int rc = SQLITE_OK; /* Return Code */
131953 int i; /* Iterator variable */
131954 sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
131956 for(i=0; rc==SQLITE_OK && i<nReader; i++){
131957 rc = fts3DeleteSegment(p, apSegment[i]);
131959 if( rc!=SQLITE_OK ){
131960 return rc;
131963 assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
131964 if( iLevel==FTS3_SEGCURSOR_ALL ){
131965 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
131966 if( rc==SQLITE_OK ){
131967 sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
131968 sqlite3_bind_int64(pDelete, 2,
131969 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
131972 }else{
131973 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
131974 if( rc==SQLITE_OK ){
131975 sqlite3_bind_int64(
131976 pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
131981 if( rc==SQLITE_OK ){
131982 sqlite3_step(pDelete);
131983 rc = sqlite3_reset(pDelete);
131986 return rc;
131990 ** When this function is called, buffer *ppList (size *pnList bytes) contains
131991 ** a position list that may (or may not) feature multiple columns. This
131992 ** function adjusts the pointer *ppList and the length *pnList so that they
131993 ** identify the subset of the position list that corresponds to column iCol.
131995 ** If there are no entries in the input position list for column iCol, then
131996 ** *pnList is set to zero before returning.
131998 ** If parameter bZero is non-zero, then any part of the input list following
131999 ** the end of the output list is zeroed before returning.
132001 static void fts3ColumnFilter(
132002 int iCol, /* Column to filter on */
132003 int bZero, /* Zero out anything following *ppList */
132004 char **ppList, /* IN/OUT: Pointer to position list */
132005 int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
132007 char *pList = *ppList;
132008 int nList = *pnList;
132009 char *pEnd = &pList[nList];
132010 int iCurrent = 0;
132011 char *p = pList;
132013 assert( iCol>=0 );
132014 while( 1 ){
132015 char c = 0;
132016 while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
132018 if( iCol==iCurrent ){
132019 nList = (int)(p - pList);
132020 break;
132023 nList -= (int)(p - pList);
132024 pList = p;
132025 if( nList==0 ){
132026 break;
132028 p = &pList[1];
132029 p += sqlite3Fts3GetVarint32(p, &iCurrent);
132032 if( bZero && &pList[nList]!=pEnd ){
132033 memset(&pList[nList], 0, pEnd - &pList[nList]);
132035 *ppList = pList;
132036 *pnList = nList;
132040 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
132041 ** existing data). Grow the buffer if required.
132043 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
132044 ** trying to resize the buffer, return SQLITE_NOMEM.
132046 static int fts3MsrBufferData(
132047 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
132048 char *pList,
132049 int nList
132051 if( nList>pMsr->nBuffer ){
132052 char *pNew;
132053 pMsr->nBuffer = nList*2;
132054 pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
132055 if( !pNew ) return SQLITE_NOMEM;
132056 pMsr->aBuffer = pNew;
132059 memcpy(pMsr->aBuffer, pList, nList);
132060 return SQLITE_OK;
132063 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
132064 Fts3Table *p, /* Virtual table handle */
132065 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
132066 sqlite3_int64 *piDocid, /* OUT: Docid value */
132067 char **paPoslist, /* OUT: Pointer to position list */
132068 int *pnPoslist /* OUT: Size of position list in bytes */
132070 int nMerge = pMsr->nAdvance;
132071 Fts3SegReader **apSegment = pMsr->apSegment;
132072 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
132073 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
132076 if( nMerge==0 ){
132077 *paPoslist = 0;
132078 return SQLITE_OK;
132081 while( 1 ){
132082 Fts3SegReader *pSeg;
132083 pSeg = pMsr->apSegment[0];
132085 if( pSeg->pOffsetList==0 ){
132086 *paPoslist = 0;
132087 break;
132088 }else{
132089 int rc;
132090 char *pList;
132091 int nList;
132092 int j;
132093 sqlite3_int64 iDocid = apSegment[0]->iDocid;
132095 rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
132096 j = 1;
132097 while( rc==SQLITE_OK
132098 && j<nMerge
132099 && apSegment[j]->pOffsetList
132100 && apSegment[j]->iDocid==iDocid
132102 rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
132105 if( rc!=SQLITE_OK ) return rc;
132106 fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
132108 if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
132109 rc = fts3MsrBufferData(pMsr, pList, nList+1);
132110 if( rc!=SQLITE_OK ) return rc;
132111 assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
132112 pList = pMsr->aBuffer;
132115 if( pMsr->iColFilter>=0 ){
132116 fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
132119 if( nList>0 ){
132120 *paPoslist = pList;
132121 *piDocid = iDocid;
132122 *pnPoslist = nList;
132123 break;
132128 return SQLITE_OK;
132131 static int fts3SegReaderStart(
132132 Fts3Table *p, /* Virtual table handle */
132133 Fts3MultiSegReader *pCsr, /* Cursor object */
132134 const char *zTerm, /* Term searched for (or NULL) */
132135 int nTerm /* Length of zTerm in bytes */
132137 int i;
132138 int nSeg = pCsr->nSegment;
132140 /* If the Fts3SegFilter defines a specific term (or term prefix) to search
132141 ** for, then advance each segment iterator until it points to a term of
132142 ** equal or greater value than the specified term. This prevents many
132143 ** unnecessary merge/sort operations for the case where single segment
132144 ** b-tree leaf nodes contain more than one term.
132146 for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
132147 int res = 0;
132148 Fts3SegReader *pSeg = pCsr->apSegment[i];
132150 int rc = fts3SegReaderNext(p, pSeg, 0);
132151 if( rc!=SQLITE_OK ) return rc;
132152 }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
132154 if( pSeg->bLookup && res!=0 ){
132155 fts3SegReaderSetEof(pSeg);
132158 fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
132160 return SQLITE_OK;
132163 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
132164 Fts3Table *p, /* Virtual table handle */
132165 Fts3MultiSegReader *pCsr, /* Cursor object */
132166 Fts3SegFilter *pFilter /* Restrictions on range of iteration */
132168 pCsr->pFilter = pFilter;
132169 return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
132172 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
132173 Fts3Table *p, /* Virtual table handle */
132174 Fts3MultiSegReader *pCsr, /* Cursor object */
132175 int iCol, /* Column to match on. */
132176 const char *zTerm, /* Term to iterate through a doclist for */
132177 int nTerm /* Number of bytes in zTerm */
132179 int i;
132180 int rc;
132181 int nSegment = pCsr->nSegment;
132182 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
132183 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
132186 assert( pCsr->pFilter==0 );
132187 assert( zTerm && nTerm>0 );
132189 /* Advance each segment iterator until it points to the term zTerm/nTerm. */
132190 rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
132191 if( rc!=SQLITE_OK ) return rc;
132193 /* Determine how many of the segments actually point to zTerm/nTerm. */
132194 for(i=0; i<nSegment; i++){
132195 Fts3SegReader *pSeg = pCsr->apSegment[i];
132196 if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
132197 break;
132200 pCsr->nAdvance = i;
132202 /* Advance each of the segments to point to the first docid. */
132203 for(i=0; i<pCsr->nAdvance; i++){
132204 rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
132205 if( rc!=SQLITE_OK ) return rc;
132207 fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
132209 assert( iCol<0 || iCol<p->nColumn );
132210 pCsr->iColFilter = iCol;
132212 return SQLITE_OK;
132216 ** This function is called on a MultiSegReader that has been started using
132217 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
132218 ** have been made. Calling this function puts the MultiSegReader in such
132219 ** a state that if the next two calls are:
132221 ** sqlite3Fts3SegReaderStart()
132222 ** sqlite3Fts3SegReaderStep()
132224 ** then the entire doclist for the term is available in
132225 ** MultiSegReader.aDoclist/nDoclist.
132227 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
132228 int i; /* Used to iterate through segment-readers */
132230 assert( pCsr->zTerm==0 );
132231 assert( pCsr->nTerm==0 );
132232 assert( pCsr->aDoclist==0 );
132233 assert( pCsr->nDoclist==0 );
132235 pCsr->nAdvance = 0;
132236 pCsr->bRestart = 1;
132237 for(i=0; i<pCsr->nSegment; i++){
132238 pCsr->apSegment[i]->pOffsetList = 0;
132239 pCsr->apSegment[i]->nOffsetList = 0;
132240 pCsr->apSegment[i]->iDocid = 0;
132243 return SQLITE_OK;
132247 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
132248 Fts3Table *p, /* Virtual table handle */
132249 Fts3MultiSegReader *pCsr /* Cursor object */
132251 int rc = SQLITE_OK;
132253 int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
132254 int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
132255 int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
132256 int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
132257 int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
132258 int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
132260 Fts3SegReader **apSegment = pCsr->apSegment;
132261 int nSegment = pCsr->nSegment;
132262 Fts3SegFilter *pFilter = pCsr->pFilter;
132263 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
132264 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
132267 if( pCsr->nSegment==0 ) return SQLITE_OK;
132270 int nMerge;
132271 int i;
132273 /* Advance the first pCsr->nAdvance entries in the apSegment[] array
132274 ** forward. Then sort the list in order of current term again.
132276 for(i=0; i<pCsr->nAdvance; i++){
132277 Fts3SegReader *pSeg = apSegment[i];
132278 if( pSeg->bLookup ){
132279 fts3SegReaderSetEof(pSeg);
132280 }else{
132281 rc = fts3SegReaderNext(p, pSeg, 0);
132283 if( rc!=SQLITE_OK ) return rc;
132285 fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
132286 pCsr->nAdvance = 0;
132288 /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
132289 assert( rc==SQLITE_OK );
132290 if( apSegment[0]->aNode==0 ) break;
132292 pCsr->nTerm = apSegment[0]->nTerm;
132293 pCsr->zTerm = apSegment[0]->zTerm;
132295 /* If this is a prefix-search, and if the term that apSegment[0] points
132296 ** to does not share a suffix with pFilter->zTerm/nTerm, then all
132297 ** required callbacks have been made. In this case exit early.
132299 ** Similarly, if this is a search for an exact match, and the first term
132300 ** of segment apSegment[0] is not a match, exit early.
132302 if( pFilter->zTerm && !isScan ){
132303 if( pCsr->nTerm<pFilter->nTerm
132304 || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
132305 || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
132307 break;
132311 nMerge = 1;
132312 while( nMerge<nSegment
132313 && apSegment[nMerge]->aNode
132314 && apSegment[nMerge]->nTerm==pCsr->nTerm
132315 && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
132317 nMerge++;
132320 assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
132321 if( nMerge==1
132322 && !isIgnoreEmpty
132323 && !isFirst
132324 && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
132326 pCsr->nDoclist = apSegment[0]->nDoclist;
132327 if( fts3SegReaderIsPending(apSegment[0]) ){
132328 rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
132329 pCsr->aDoclist = pCsr->aBuffer;
132330 }else{
132331 pCsr->aDoclist = apSegment[0]->aDoclist;
132333 if( rc==SQLITE_OK ) rc = SQLITE_ROW;
132334 }else{
132335 int nDoclist = 0; /* Size of doclist */
132336 sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
132338 /* The current term of the first nMerge entries in the array
132339 ** of Fts3SegReader objects is the same. The doclists must be merged
132340 ** and a single term returned with the merged doclist.
132342 for(i=0; i<nMerge; i++){
132343 fts3SegReaderFirstDocid(p, apSegment[i]);
132345 fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
132346 while( apSegment[0]->pOffsetList ){
132347 int j; /* Number of segments that share a docid */
132348 char *pList = 0;
132349 int nList = 0;
132350 int nByte;
132351 sqlite3_int64 iDocid = apSegment[0]->iDocid;
132352 fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
132353 j = 1;
132354 while( j<nMerge
132355 && apSegment[j]->pOffsetList
132356 && apSegment[j]->iDocid==iDocid
132358 fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
132362 if( isColFilter ){
132363 fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
132366 if( !isIgnoreEmpty || nList>0 ){
132368 /* Calculate the 'docid' delta value to write into the merged
132369 ** doclist. */
132370 sqlite3_int64 iDelta;
132371 if( p->bDescIdx && nDoclist>0 ){
132372 iDelta = iPrev - iDocid;
132373 }else{
132374 iDelta = iDocid - iPrev;
132376 assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
132377 assert( nDoclist>0 || iDelta==iDocid );
132379 nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
132380 if( nDoclist+nByte>pCsr->nBuffer ){
132381 char *aNew;
132382 pCsr->nBuffer = (nDoclist+nByte)*2;
132383 aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
132384 if( !aNew ){
132385 return SQLITE_NOMEM;
132387 pCsr->aBuffer = aNew;
132390 if( isFirst ){
132391 char *a = &pCsr->aBuffer[nDoclist];
132392 int nWrite;
132394 nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
132395 if( nWrite ){
132396 iPrev = iDocid;
132397 nDoclist += nWrite;
132399 }else{
132400 nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
132401 iPrev = iDocid;
132402 if( isRequirePos ){
132403 memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
132404 nDoclist += nList;
132405 pCsr->aBuffer[nDoclist++] = '\0';
132410 fts3SegReaderSort(apSegment, nMerge, j, xCmp);
132412 if( nDoclist>0 ){
132413 pCsr->aDoclist = pCsr->aBuffer;
132414 pCsr->nDoclist = nDoclist;
132415 rc = SQLITE_ROW;
132418 pCsr->nAdvance = nMerge;
132419 }while( rc==SQLITE_OK );
132421 return rc;
132425 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
132426 Fts3MultiSegReader *pCsr /* Cursor object */
132428 if( pCsr ){
132429 int i;
132430 for(i=0; i<pCsr->nSegment; i++){
132431 sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
132433 sqlite3_free(pCsr->apSegment);
132434 sqlite3_free(pCsr->aBuffer);
132436 pCsr->nSegment = 0;
132437 pCsr->apSegment = 0;
132438 pCsr->aBuffer = 0;
132443 ** Merge all level iLevel segments in the database into a single
132444 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
132445 ** single segment with a level equal to the numerically largest level
132446 ** currently present in the database.
132448 ** If this function is called with iLevel<0, but there is only one
132449 ** segment in the database, SQLITE_DONE is returned immediately.
132450 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
132451 ** an SQLite error code is returned.
132453 static int fts3SegmentMerge(
132454 Fts3Table *p,
132455 int iLangid, /* Language id to merge */
132456 int iIndex, /* Index in p->aIndex[] to merge */
132457 int iLevel /* Level to merge */
132459 int rc; /* Return code */
132460 int iIdx = 0; /* Index of new segment */
132461 sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
132462 SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
132463 Fts3SegFilter filter; /* Segment term filter condition */
132464 Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
132465 int bIgnoreEmpty = 0; /* True to ignore empty segments */
132467 assert( iLevel==FTS3_SEGCURSOR_ALL
132468 || iLevel==FTS3_SEGCURSOR_PENDING
132469 || iLevel>=0
132471 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
132472 assert( iIndex>=0 && iIndex<p->nIndex );
132474 rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
132475 if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
132477 if( iLevel==FTS3_SEGCURSOR_ALL ){
132478 /* This call is to merge all segments in the database to a single
132479 ** segment. The level of the new segment is equal to the numerically
132480 ** greatest segment level currently present in the database for this
132481 ** index. The idx of the new segment is always 0. */
132482 if( csr.nSegment==1 ){
132483 rc = SQLITE_DONE;
132484 goto finished;
132486 rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
132487 bIgnoreEmpty = 1;
132489 }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
132490 iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
132491 rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
132492 }else{
132493 /* This call is to merge all segments at level iLevel. find the next
132494 ** available segment index at level iLevel+1. The call to
132495 ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
132496 ** a single iLevel+2 segment if necessary. */
132497 rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
132498 iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
132500 if( rc!=SQLITE_OK ) goto finished;
132501 assert( csr.nSegment>0 );
132502 assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
132503 assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
132505 memset(&filter, 0, sizeof(Fts3SegFilter));
132506 filter.flags = FTS3_SEGMENT_REQUIRE_POS;
132507 filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
132509 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
132510 while( SQLITE_OK==rc ){
132511 rc = sqlite3Fts3SegReaderStep(p, &csr);
132512 if( rc!=SQLITE_ROW ) break;
132513 rc = fts3SegWriterAdd(p, &pWriter, 1,
132514 csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
132516 if( rc!=SQLITE_OK ) goto finished;
132517 assert( pWriter );
132519 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
132520 rc = fts3DeleteSegdir(
132521 p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
132523 if( rc!=SQLITE_OK ) goto finished;
132525 rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
132527 finished:
132528 fts3SegWriterFree(pWriter);
132529 sqlite3Fts3SegReaderFinish(&csr);
132530 return rc;
132535 ** Flush the contents of pendingTerms to level 0 segments.
132537 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
132538 int rc = SQLITE_OK;
132539 int i;
132541 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
132542 rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
132543 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
132545 sqlite3Fts3PendingTermsClear(p);
132547 /* Determine the auto-incr-merge setting if unknown. If enabled,
132548 ** estimate the number of leaf blocks of content to be written
132550 if( rc==SQLITE_OK && p->bHasStat
132551 && p->bAutoincrmerge==0xff && p->nLeafAdd>0
132553 sqlite3_stmt *pStmt = 0;
132554 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
132555 if( rc==SQLITE_OK ){
132556 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
132557 rc = sqlite3_step(pStmt);
132558 p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
132559 rc = sqlite3_reset(pStmt);
132562 return rc;
132566 ** Encode N integers as varints into a blob.
132568 static void fts3EncodeIntArray(
132569 int N, /* The number of integers to encode */
132570 u32 *a, /* The integer values */
132571 char *zBuf, /* Write the BLOB here */
132572 int *pNBuf /* Write number of bytes if zBuf[] used here */
132574 int i, j;
132575 for(i=j=0; i<N; i++){
132576 j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
132578 *pNBuf = j;
132582 ** Decode a blob of varints into N integers
132584 static void fts3DecodeIntArray(
132585 int N, /* The number of integers to decode */
132586 u32 *a, /* Write the integer values */
132587 const char *zBuf, /* The BLOB containing the varints */
132588 int nBuf /* size of the BLOB */
132590 int i, j;
132591 UNUSED_PARAMETER(nBuf);
132592 for(i=j=0; i<N; i++){
132593 sqlite3_int64 x;
132594 j += sqlite3Fts3GetVarint(&zBuf[j], &x);
132595 assert(j<=nBuf);
132596 a[i] = (u32)(x & 0xffffffff);
132601 ** Insert the sizes (in tokens) for each column of the document
132602 ** with docid equal to p->iPrevDocid. The sizes are encoded as
132603 ** a blob of varints.
132605 static void fts3InsertDocsize(
132606 int *pRC, /* Result code */
132607 Fts3Table *p, /* Table into which to insert */
132608 u32 *aSz /* Sizes of each column, in tokens */
132610 char *pBlob; /* The BLOB encoding of the document size */
132611 int nBlob; /* Number of bytes in the BLOB */
132612 sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
132613 int rc; /* Result code from subfunctions */
132615 if( *pRC ) return;
132616 pBlob = sqlite3_malloc( 10*p->nColumn );
132617 if( pBlob==0 ){
132618 *pRC = SQLITE_NOMEM;
132619 return;
132621 fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
132622 rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
132623 if( rc ){
132624 sqlite3_free(pBlob);
132625 *pRC = rc;
132626 return;
132628 sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
132629 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
132630 sqlite3_step(pStmt);
132631 *pRC = sqlite3_reset(pStmt);
132635 ** Record 0 of the %_stat table contains a blob consisting of N varints,
132636 ** where N is the number of user defined columns in the fts3 table plus
132637 ** two. If nCol is the number of user defined columns, then values of the
132638 ** varints are set as follows:
132640 ** Varint 0: Total number of rows in the table.
132642 ** Varint 1..nCol: For each column, the total number of tokens stored in
132643 ** the column for all rows of the table.
132645 ** Varint 1+nCol: The total size, in bytes, of all text values in all
132646 ** columns of all rows of the table.
132649 static void fts3UpdateDocTotals(
132650 int *pRC, /* The result code */
132651 Fts3Table *p, /* Table being updated */
132652 u32 *aSzIns, /* Size increases */
132653 u32 *aSzDel, /* Size decreases */
132654 int nChng /* Change in the number of documents */
132656 char *pBlob; /* Storage for BLOB written into %_stat */
132657 int nBlob; /* Size of BLOB written into %_stat */
132658 u32 *a; /* Array of integers that becomes the BLOB */
132659 sqlite3_stmt *pStmt; /* Statement for reading and writing */
132660 int i; /* Loop counter */
132661 int rc; /* Result code from subfunctions */
132663 const int nStat = p->nColumn+2;
132665 if( *pRC ) return;
132666 a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
132667 if( a==0 ){
132668 *pRC = SQLITE_NOMEM;
132669 return;
132671 pBlob = (char*)&a[nStat];
132672 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
132673 if( rc ){
132674 sqlite3_free(a);
132675 *pRC = rc;
132676 return;
132678 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
132679 if( sqlite3_step(pStmt)==SQLITE_ROW ){
132680 fts3DecodeIntArray(nStat, a,
132681 sqlite3_column_blob(pStmt, 0),
132682 sqlite3_column_bytes(pStmt, 0));
132683 }else{
132684 memset(a, 0, sizeof(u32)*(nStat) );
132686 rc = sqlite3_reset(pStmt);
132687 if( rc!=SQLITE_OK ){
132688 sqlite3_free(a);
132689 *pRC = rc;
132690 return;
132692 if( nChng<0 && a[0]<(u32)(-nChng) ){
132693 a[0] = 0;
132694 }else{
132695 a[0] += nChng;
132697 for(i=0; i<p->nColumn+1; i++){
132698 u32 x = a[i+1];
132699 if( x+aSzIns[i] < aSzDel[i] ){
132700 x = 0;
132701 }else{
132702 x = x + aSzIns[i] - aSzDel[i];
132704 a[i+1] = x;
132706 fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
132707 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
132708 if( rc ){
132709 sqlite3_free(a);
132710 *pRC = rc;
132711 return;
132713 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
132714 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
132715 sqlite3_step(pStmt);
132716 *pRC = sqlite3_reset(pStmt);
132717 sqlite3_free(a);
132721 ** Merge the entire database so that there is one segment for each
132722 ** iIndex/iLangid combination.
132724 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
132725 int bSeenDone = 0;
132726 int rc;
132727 sqlite3_stmt *pAllLangid = 0;
132729 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
132730 if( rc==SQLITE_OK ){
132731 int rc2;
132732 sqlite3_bind_int(pAllLangid, 1, p->nIndex);
132733 while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
132734 int i;
132735 int iLangid = sqlite3_column_int(pAllLangid, 0);
132736 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
132737 rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
132738 if( rc==SQLITE_DONE ){
132739 bSeenDone = 1;
132740 rc = SQLITE_OK;
132744 rc2 = sqlite3_reset(pAllLangid);
132745 if( rc==SQLITE_OK ) rc = rc2;
132748 sqlite3Fts3SegmentsClose(p);
132749 sqlite3Fts3PendingTermsClear(p);
132751 return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
132755 ** This function is called when the user executes the following statement:
132757 ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
132759 ** The entire FTS index is discarded and rebuilt. If the table is one
132760 ** created using the content=xxx option, then the new index is based on
132761 ** the current contents of the xxx table. Otherwise, it is rebuilt based
132762 ** on the contents of the %_content table.
132764 static int fts3DoRebuild(Fts3Table *p){
132765 int rc; /* Return Code */
132767 rc = fts3DeleteAll(p, 0);
132768 if( rc==SQLITE_OK ){
132769 u32 *aSz = 0;
132770 u32 *aSzIns = 0;
132771 u32 *aSzDel = 0;
132772 sqlite3_stmt *pStmt = 0;
132773 int nEntry = 0;
132775 /* Compose and prepare an SQL statement to loop through the content table */
132776 char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
132777 if( !zSql ){
132778 rc = SQLITE_NOMEM;
132779 }else{
132780 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
132781 sqlite3_free(zSql);
132784 if( rc==SQLITE_OK ){
132785 int nByte = sizeof(u32) * (p->nColumn+1)*3;
132786 aSz = (u32 *)sqlite3_malloc(nByte);
132787 if( aSz==0 ){
132788 rc = SQLITE_NOMEM;
132789 }else{
132790 memset(aSz, 0, nByte);
132791 aSzIns = &aSz[p->nColumn+1];
132792 aSzDel = &aSzIns[p->nColumn+1];
132796 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
132797 int iCol;
132798 int iLangid = langidFromSelect(p, pStmt);
132799 rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
132800 memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
132801 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
132802 if( p->abNotindexed[iCol]==0 ){
132803 const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
132804 rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
132805 aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
132808 if( p->bHasDocsize ){
132809 fts3InsertDocsize(&rc, p, aSz);
132811 if( rc!=SQLITE_OK ){
132812 sqlite3_finalize(pStmt);
132813 pStmt = 0;
132814 }else{
132815 nEntry++;
132816 for(iCol=0; iCol<=p->nColumn; iCol++){
132817 aSzIns[iCol] += aSz[iCol];
132821 if( p->bFts4 ){
132822 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
132824 sqlite3_free(aSz);
132826 if( pStmt ){
132827 int rc2 = sqlite3_finalize(pStmt);
132828 if( rc==SQLITE_OK ){
132829 rc = rc2;
132834 return rc;
132839 ** This function opens a cursor used to read the input data for an
132840 ** incremental merge operation. Specifically, it opens a cursor to scan
132841 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
132842 ** level iAbsLevel.
132844 static int fts3IncrmergeCsr(
132845 Fts3Table *p, /* FTS3 table handle */
132846 sqlite3_int64 iAbsLevel, /* Absolute level to open */
132847 int nSeg, /* Number of segments to merge */
132848 Fts3MultiSegReader *pCsr /* Cursor object to populate */
132850 int rc; /* Return Code */
132851 sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
132852 int nByte; /* Bytes allocated at pCsr->apSegment[] */
132854 /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
132855 memset(pCsr, 0, sizeof(*pCsr));
132856 nByte = sizeof(Fts3SegReader *) * nSeg;
132857 pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
132859 if( pCsr->apSegment==0 ){
132860 rc = SQLITE_NOMEM;
132861 }else{
132862 memset(pCsr->apSegment, 0, nByte);
132863 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
132865 if( rc==SQLITE_OK ){
132866 int i;
132867 int rc2;
132868 sqlite3_bind_int64(pStmt, 1, iAbsLevel);
132869 assert( pCsr->nSegment==0 );
132870 for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
132871 rc = sqlite3Fts3SegReaderNew(i, 0,
132872 sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
132873 sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
132874 sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
132875 sqlite3_column_blob(pStmt, 4), /* segdir.root */
132876 sqlite3_column_bytes(pStmt, 4), /* segdir.root */
132877 &pCsr->apSegment[i]
132879 pCsr->nSegment++;
132881 rc2 = sqlite3_reset(pStmt);
132882 if( rc==SQLITE_OK ) rc = rc2;
132885 return rc;
132888 typedef struct IncrmergeWriter IncrmergeWriter;
132889 typedef struct NodeWriter NodeWriter;
132890 typedef struct Blob Blob;
132891 typedef struct NodeReader NodeReader;
132894 ** An instance of the following structure is used as a dynamic buffer
132895 ** to build up nodes or other blobs of data in.
132897 ** The function blobGrowBuffer() is used to extend the allocation.
132899 struct Blob {
132900 char *a; /* Pointer to allocation */
132901 int n; /* Number of valid bytes of data in a[] */
132902 int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
132906 ** This structure is used to build up buffers containing segment b-tree
132907 ** nodes (blocks).
132909 struct NodeWriter {
132910 sqlite3_int64 iBlock; /* Current block id */
132911 Blob key; /* Last key written to the current block */
132912 Blob block; /* Current block image */
132916 ** An object of this type contains the state required to create or append
132917 ** to an appendable b-tree segment.
132919 struct IncrmergeWriter {
132920 int nLeafEst; /* Space allocated for leaf blocks */
132921 int nWork; /* Number of leaf pages flushed */
132922 sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
132923 int iIdx; /* Index of *output* segment in iAbsLevel+1 */
132924 sqlite3_int64 iStart; /* Block number of first allocated block */
132925 sqlite3_int64 iEnd; /* Block number of last allocated block */
132926 NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
132930 ** An object of the following type is used to read data from a single
132931 ** FTS segment node. See the following functions:
132933 ** nodeReaderInit()
132934 ** nodeReaderNext()
132935 ** nodeReaderRelease()
132937 struct NodeReader {
132938 const char *aNode;
132939 int nNode;
132940 int iOff; /* Current offset within aNode[] */
132942 /* Output variables. Containing the current node entry. */
132943 sqlite3_int64 iChild; /* Pointer to child node */
132944 Blob term; /* Current term */
132945 const char *aDoclist; /* Pointer to doclist */
132946 int nDoclist; /* Size of doclist in bytes */
132950 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
132951 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
132952 ** bytes in size, extend (realloc) it to be so.
132954 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
132955 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
132956 ** to reflect the new size of the pBlob->a[] buffer.
132958 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
132959 if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
132960 int nAlloc = nMin;
132961 char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
132962 if( a ){
132963 pBlob->nAlloc = nAlloc;
132964 pBlob->a = a;
132965 }else{
132966 *pRc = SQLITE_NOMEM;
132972 ** Attempt to advance the node-reader object passed as the first argument to
132973 ** the next entry on the node.
132975 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
132976 ** Otherwise return SQLITE_OK. If there is no next entry on the node
132977 ** (e.g. because the current entry is the last) set NodeReader->aNode to
132978 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
132979 ** variables for the new entry.
132981 static int nodeReaderNext(NodeReader *p){
132982 int bFirst = (p->term.n==0); /* True for first term on the node */
132983 int nPrefix = 0; /* Bytes to copy from previous term */
132984 int nSuffix = 0; /* Bytes to append to the prefix */
132985 int rc = SQLITE_OK; /* Return code */
132987 assert( p->aNode );
132988 if( p->iChild && bFirst==0 ) p->iChild++;
132989 if( p->iOff>=p->nNode ){
132990 /* EOF */
132991 p->aNode = 0;
132992 }else{
132993 if( bFirst==0 ){
132994 p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
132996 p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
132998 blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
132999 if( rc==SQLITE_OK ){
133000 memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
133001 p->term.n = nPrefix+nSuffix;
133002 p->iOff += nSuffix;
133003 if( p->iChild==0 ){
133004 p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
133005 p->aDoclist = &p->aNode[p->iOff];
133006 p->iOff += p->nDoclist;
133011 assert( p->iOff<=p->nNode );
133013 return rc;
133017 ** Release all dynamic resources held by node-reader object *p.
133019 static void nodeReaderRelease(NodeReader *p){
133020 sqlite3_free(p->term.a);
133024 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
133026 ** If successful, SQLITE_OK is returned and the NodeReader object set to
133027 ** point to the first entry on the node (if any). Otherwise, an SQLite
133028 ** error code is returned.
133030 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
133031 memset(p, 0, sizeof(NodeReader));
133032 p->aNode = aNode;
133033 p->nNode = nNode;
133035 /* Figure out if this is a leaf or an internal node. */
133036 if( p->aNode[0] ){
133037 /* An internal node. */
133038 p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
133039 }else{
133040 p->iOff = 1;
133043 return nodeReaderNext(p);
133047 ** This function is called while writing an FTS segment each time a leaf o
133048 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
133049 ** to be greater than the largest key on the node just written, but smaller
133050 ** than or equal to the first key that will be written to the next leaf
133051 ** node.
133053 ** The block id of the leaf node just written to disk may be found in
133054 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
133056 static int fts3IncrmergePush(
133057 Fts3Table *p, /* Fts3 table handle */
133058 IncrmergeWriter *pWriter, /* Writer object */
133059 const char *zTerm, /* Term to write to internal node */
133060 int nTerm /* Bytes at zTerm */
133062 sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
133063 int iLayer;
133065 assert( nTerm>0 );
133066 for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
133067 sqlite3_int64 iNextPtr = 0;
133068 NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
133069 int rc = SQLITE_OK;
133070 int nPrefix;
133071 int nSuffix;
133072 int nSpace;
133074 /* Figure out how much space the key will consume if it is written to
133075 ** the current node of layer iLayer. Due to the prefix compression,
133076 ** the space required changes depending on which node the key is to
133077 ** be added to. */
133078 nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
133079 nSuffix = nTerm - nPrefix;
133080 nSpace = sqlite3Fts3VarintLen(nPrefix);
133081 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
133083 if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
133084 /* If the current node of layer iLayer contains zero keys, or if adding
133085 ** the key to it will not cause it to grow to larger than nNodeSize
133086 ** bytes in size, write the key here. */
133088 Blob *pBlk = &pNode->block;
133089 if( pBlk->n==0 ){
133090 blobGrowBuffer(pBlk, p->nNodeSize, &rc);
133091 if( rc==SQLITE_OK ){
133092 pBlk->a[0] = (char)iLayer;
133093 pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
133096 blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
133097 blobGrowBuffer(&pNode->key, nTerm, &rc);
133099 if( rc==SQLITE_OK ){
133100 if( pNode->key.n ){
133101 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
133103 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
133104 memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
133105 pBlk->n += nSuffix;
133107 memcpy(pNode->key.a, zTerm, nTerm);
133108 pNode->key.n = nTerm;
133110 }else{
133111 /* Otherwise, flush the current node of layer iLayer to disk.
133112 ** Then allocate a new, empty sibling node. The key will be written
133113 ** into the parent of this node. */
133114 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
133116 assert( pNode->block.nAlloc>=p->nNodeSize );
133117 pNode->block.a[0] = (char)iLayer;
133118 pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
133120 iNextPtr = pNode->iBlock;
133121 pNode->iBlock++;
133122 pNode->key.n = 0;
133125 if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
133126 iPtr = iNextPtr;
133129 assert( 0 );
133130 return 0;
133134 ** Append a term and (optionally) doclist to the FTS segment node currently
133135 ** stored in blob *pNode. The node need not contain any terms, but the
133136 ** header must be written before this function is called.
133138 ** A node header is a single 0x00 byte for a leaf node, or a height varint
133139 ** followed by the left-hand-child varint for an internal node.
133141 ** The term to be appended is passed via arguments zTerm/nTerm. For a
133142 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
133143 ** node, both aDoclist and nDoclist must be passed 0.
133145 ** If the size of the value in blob pPrev is zero, then this is the first
133146 ** term written to the node. Otherwise, pPrev contains a copy of the
133147 ** previous term. Before this function returns, it is updated to contain a
133148 ** copy of zTerm/nTerm.
133150 ** It is assumed that the buffer associated with pNode is already large
133151 ** enough to accommodate the new entry. The buffer associated with pPrev
133152 ** is extended by this function if requrired.
133154 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
133155 ** returned. Otherwise, SQLITE_OK.
133157 static int fts3AppendToNode(
133158 Blob *pNode, /* Current node image to append to */
133159 Blob *pPrev, /* Buffer containing previous term written */
133160 const char *zTerm, /* New term to write */
133161 int nTerm, /* Size of zTerm in bytes */
133162 const char *aDoclist, /* Doclist (or NULL) to write */
133163 int nDoclist /* Size of aDoclist in bytes */
133165 int rc = SQLITE_OK; /* Return code */
133166 int bFirst = (pPrev->n==0); /* True if this is the first term written */
133167 int nPrefix; /* Size of term prefix in bytes */
133168 int nSuffix; /* Size of term suffix in bytes */
133170 /* Node must have already been started. There must be a doclist for a
133171 ** leaf node, and there must not be a doclist for an internal node. */
133172 assert( pNode->n>0 );
133173 assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
133175 blobGrowBuffer(pPrev, nTerm, &rc);
133176 if( rc!=SQLITE_OK ) return rc;
133178 nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
133179 nSuffix = nTerm - nPrefix;
133180 memcpy(pPrev->a, zTerm, nTerm);
133181 pPrev->n = nTerm;
133183 if( bFirst==0 ){
133184 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
133186 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
133187 memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
133188 pNode->n += nSuffix;
133190 if( aDoclist ){
133191 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
133192 memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
133193 pNode->n += nDoclist;
133196 assert( pNode->n<=pNode->nAlloc );
133198 return SQLITE_OK;
133202 ** Append the current term and doclist pointed to by cursor pCsr to the
133203 ** appendable b-tree segment opened for writing by pWriter.
133205 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
133207 static int fts3IncrmergeAppend(
133208 Fts3Table *p, /* Fts3 table handle */
133209 IncrmergeWriter *pWriter, /* Writer object */
133210 Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
133212 const char *zTerm = pCsr->zTerm;
133213 int nTerm = pCsr->nTerm;
133214 const char *aDoclist = pCsr->aDoclist;
133215 int nDoclist = pCsr->nDoclist;
133216 int rc = SQLITE_OK; /* Return code */
133217 int nSpace; /* Total space in bytes required on leaf */
133218 int nPrefix; /* Size of prefix shared with previous term */
133219 int nSuffix; /* Size of suffix (nTerm - nPrefix) */
133220 NodeWriter *pLeaf; /* Object used to write leaf nodes */
133222 pLeaf = &pWriter->aNodeWriter[0];
133223 nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
133224 nSuffix = nTerm - nPrefix;
133226 nSpace = sqlite3Fts3VarintLen(nPrefix);
133227 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
133228 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
133230 /* If the current block is not empty, and if adding this term/doclist
133231 ** to the current block would make it larger than Fts3Table.nNodeSize
133232 ** bytes, write this block out to the database. */
133233 if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
133234 rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
133235 pWriter->nWork++;
133237 /* Add the current term to the parent node. The term added to the
133238 ** parent must:
133240 ** a) be greater than the largest term on the leaf node just written
133241 ** to the database (still available in pLeaf->key), and
133243 ** b) be less than or equal to the term about to be added to the new
133244 ** leaf node (zTerm/nTerm).
133246 ** In other words, it must be the prefix of zTerm 1 byte longer than
133247 ** the common prefix (if any) of zTerm and pWriter->zTerm.
133249 if( rc==SQLITE_OK ){
133250 rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
133253 /* Advance to the next output block */
133254 pLeaf->iBlock++;
133255 pLeaf->key.n = 0;
133256 pLeaf->block.n = 0;
133258 nSuffix = nTerm;
133259 nSpace = 1;
133260 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
133261 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
133264 blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
133266 if( rc==SQLITE_OK ){
133267 if( pLeaf->block.n==0 ){
133268 pLeaf->block.n = 1;
133269 pLeaf->block.a[0] = '\0';
133271 rc = fts3AppendToNode(
133272 &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
133276 return rc;
133280 ** This function is called to release all dynamic resources held by the
133281 ** merge-writer object pWriter, and if no error has occurred, to flush
133282 ** all outstanding node buffers held by pWriter to disk.
133284 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
133285 ** is made to write any data to disk. Instead, this function serves only
133286 ** to release outstanding resources.
133288 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
133289 ** flushing buffers to disk, *pRc is set to an SQLite error code before
133290 ** returning.
133292 static void fts3IncrmergeRelease(
133293 Fts3Table *p, /* FTS3 table handle */
133294 IncrmergeWriter *pWriter, /* Merge-writer object */
133295 int *pRc /* IN/OUT: Error code */
133297 int i; /* Used to iterate through non-root layers */
133298 int iRoot; /* Index of root in pWriter->aNodeWriter */
133299 NodeWriter *pRoot; /* NodeWriter for root node */
133300 int rc = *pRc; /* Error code */
133302 /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
133303 ** root node. If the segment fits entirely on a single leaf node, iRoot
133304 ** will be set to 0. If the root node is the parent of the leaves, iRoot
133305 ** will be 1. And so on. */
133306 for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
133307 NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
133308 if( pNode->block.n>0 ) break;
133309 assert( *pRc || pNode->block.nAlloc==0 );
133310 assert( *pRc || pNode->key.nAlloc==0 );
133311 sqlite3_free(pNode->block.a);
133312 sqlite3_free(pNode->key.a);
133315 /* Empty output segment. This is a no-op. */
133316 if( iRoot<0 ) return;
133318 /* The entire output segment fits on a single node. Normally, this means
133319 ** the node would be stored as a blob in the "root" column of the %_segdir
133320 ** table. However, this is not permitted in this case. The problem is that
133321 ** space has already been reserved in the %_segments table, and so the
133322 ** start_block and end_block fields of the %_segdir table must be populated.
133323 ** And, by design or by accident, released versions of FTS cannot handle
133324 ** segments that fit entirely on the root node with start_block!=0.
133326 ** Instead, create a synthetic root node that contains nothing but a
133327 ** pointer to the single content node. So that the segment consists of a
133328 ** single leaf and a single interior (root) node.
133330 ** Todo: Better might be to defer allocating space in the %_segments
133331 ** table until we are sure it is needed.
133333 if( iRoot==0 ){
133334 Blob *pBlock = &pWriter->aNodeWriter[1].block;
133335 blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
133336 if( rc==SQLITE_OK ){
133337 pBlock->a[0] = 0x01;
133338 pBlock->n = 1 + sqlite3Fts3PutVarint(
133339 &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
133342 iRoot = 1;
133344 pRoot = &pWriter->aNodeWriter[iRoot];
133346 /* Flush all currently outstanding nodes to disk. */
133347 for(i=0; i<iRoot; i++){
133348 NodeWriter *pNode = &pWriter->aNodeWriter[i];
133349 if( pNode->block.n>0 && rc==SQLITE_OK ){
133350 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
133352 sqlite3_free(pNode->block.a);
133353 sqlite3_free(pNode->key.a);
133356 /* Write the %_segdir record. */
133357 if( rc==SQLITE_OK ){
133358 rc = fts3WriteSegdir(p,
133359 pWriter->iAbsLevel+1, /* level */
133360 pWriter->iIdx, /* idx */
133361 pWriter->iStart, /* start_block */
133362 pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
133363 pWriter->iEnd, /* end_block */
133364 pRoot->block.a, pRoot->block.n /* root */
133367 sqlite3_free(pRoot->block.a);
133368 sqlite3_free(pRoot->key.a);
133370 *pRc = rc;
133374 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
133375 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
133376 ** the other, it is considered to be smaller than the other.
133378 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
133379 ** if it is greater.
133381 static int fts3TermCmp(
133382 const char *zLhs, int nLhs, /* LHS of comparison */
133383 const char *zRhs, int nRhs /* RHS of comparison */
133385 int nCmp = MIN(nLhs, nRhs);
133386 int res;
133388 res = memcmp(zLhs, zRhs, nCmp);
133389 if( res==0 ) res = nLhs - nRhs;
133391 return res;
133396 ** Query to see if the entry in the %_segments table with blockid iEnd is
133397 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
133398 ** returning. Otherwise, set *pbRes to 0.
133400 ** Or, if an error occurs while querying the database, return an SQLite
133401 ** error code. The final value of *pbRes is undefined in this case.
133403 ** This is used to test if a segment is an "appendable" segment. If it
133404 ** is, then a NULL entry has been inserted into the %_segments table
133405 ** with blockid %_segdir.end_block.
133407 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
133408 int bRes = 0; /* Result to set *pbRes to */
133409 sqlite3_stmt *pCheck = 0; /* Statement to query database with */
133410 int rc; /* Return code */
133412 rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
133413 if( rc==SQLITE_OK ){
133414 sqlite3_bind_int64(pCheck, 1, iEnd);
133415 if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
133416 rc = sqlite3_reset(pCheck);
133419 *pbRes = bRes;
133420 return rc;
133424 ** This function is called when initializing an incremental-merge operation.
133425 ** It checks if the existing segment with index value iIdx at absolute level
133426 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
133427 ** merge-writer object *pWriter is initialized to write to it.
133429 ** An existing segment can be appended to by an incremental merge if:
133431 ** * It was initially created as an appendable segment (with all required
133432 ** space pre-allocated), and
133434 ** * The first key read from the input (arguments zKey and nKey) is
133435 ** greater than the largest key currently stored in the potential
133436 ** output segment.
133438 static int fts3IncrmergeLoad(
133439 Fts3Table *p, /* Fts3 table handle */
133440 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
133441 int iIdx, /* Index of candidate output segment */
133442 const char *zKey, /* First key to write */
133443 int nKey, /* Number of bytes in nKey */
133444 IncrmergeWriter *pWriter /* Populate this object */
133446 int rc; /* Return code */
133447 sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
133449 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
133450 if( rc==SQLITE_OK ){
133451 sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
133452 sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
133453 sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
133454 const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
133455 int nRoot = 0; /* Size of aRoot[] in bytes */
133456 int rc2; /* Return code from sqlite3_reset() */
133457 int bAppendable = 0; /* Set to true if segment is appendable */
133459 /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
133460 sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
133461 sqlite3_bind_int(pSelect, 2, iIdx);
133462 if( sqlite3_step(pSelect)==SQLITE_ROW ){
133463 iStart = sqlite3_column_int64(pSelect, 1);
133464 iLeafEnd = sqlite3_column_int64(pSelect, 2);
133465 iEnd = sqlite3_column_int64(pSelect, 3);
133466 nRoot = sqlite3_column_bytes(pSelect, 4);
133467 aRoot = sqlite3_column_blob(pSelect, 4);
133468 }else{
133469 return sqlite3_reset(pSelect);
133472 /* Check for the zero-length marker in the %_segments table */
133473 rc = fts3IsAppendable(p, iEnd, &bAppendable);
133475 /* Check that zKey/nKey is larger than the largest key the candidate */
133476 if( rc==SQLITE_OK && bAppendable ){
133477 char *aLeaf = 0;
133478 int nLeaf = 0;
133480 rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
133481 if( rc==SQLITE_OK ){
133482 NodeReader reader;
133483 for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
133484 rc==SQLITE_OK && reader.aNode;
133485 rc = nodeReaderNext(&reader)
133487 assert( reader.aNode );
133489 if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
133490 bAppendable = 0;
133492 nodeReaderRelease(&reader);
133494 sqlite3_free(aLeaf);
133497 if( rc==SQLITE_OK && bAppendable ){
133498 /* It is possible to append to this segment. Set up the IncrmergeWriter
133499 ** object to do so. */
133500 int i;
133501 int nHeight = (int)aRoot[0];
133502 NodeWriter *pNode;
133504 pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
133505 pWriter->iStart = iStart;
133506 pWriter->iEnd = iEnd;
133507 pWriter->iAbsLevel = iAbsLevel;
133508 pWriter->iIdx = iIdx;
133510 for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
133511 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
133514 pNode = &pWriter->aNodeWriter[nHeight];
133515 pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
133516 blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
133517 if( rc==SQLITE_OK ){
133518 memcpy(pNode->block.a, aRoot, nRoot);
133519 pNode->block.n = nRoot;
133522 for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
133523 NodeReader reader;
133524 pNode = &pWriter->aNodeWriter[i];
133526 rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
133527 while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
133528 blobGrowBuffer(&pNode->key, reader.term.n, &rc);
133529 if( rc==SQLITE_OK ){
133530 memcpy(pNode->key.a, reader.term.a, reader.term.n);
133531 pNode->key.n = reader.term.n;
133532 if( i>0 ){
133533 char *aBlock = 0;
133534 int nBlock = 0;
133535 pNode = &pWriter->aNodeWriter[i-1];
133536 pNode->iBlock = reader.iChild;
133537 rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
133538 blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
133539 if( rc==SQLITE_OK ){
133540 memcpy(pNode->block.a, aBlock, nBlock);
133541 pNode->block.n = nBlock;
133543 sqlite3_free(aBlock);
133546 nodeReaderRelease(&reader);
133550 rc2 = sqlite3_reset(pSelect);
133551 if( rc==SQLITE_OK ) rc = rc2;
133554 return rc;
133558 ** Determine the largest segment index value that exists within absolute
133559 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
133560 ** one before returning SQLITE_OK. Or, if there are no segments at all
133561 ** within level iAbsLevel, set *piIdx to zero.
133563 ** If an error occurs, return an SQLite error code. The final value of
133564 ** *piIdx is undefined in this case.
133566 static int fts3IncrmergeOutputIdx(
133567 Fts3Table *p, /* FTS Table handle */
133568 sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
133569 int *piIdx /* OUT: Next free index at iAbsLevel+1 */
133571 int rc;
133572 sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
133574 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
133575 if( rc==SQLITE_OK ){
133576 sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
133577 sqlite3_step(pOutputIdx);
133578 *piIdx = sqlite3_column_int(pOutputIdx, 0);
133579 rc = sqlite3_reset(pOutputIdx);
133582 return rc;
133586 ** Allocate an appendable output segment on absolute level iAbsLevel+1
133587 ** with idx value iIdx.
133589 ** In the %_segdir table, a segment is defined by the values in three
133590 ** columns:
133592 ** start_block
133593 ** leaves_end_block
133594 ** end_block
133596 ** When an appendable segment is allocated, it is estimated that the
133597 ** maximum number of leaf blocks that may be required is the sum of the
133598 ** number of leaf blocks consumed by the input segments, plus the number
133599 ** of input segments, multiplied by two. This value is stored in stack
133600 ** variable nLeafEst.
133602 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
133603 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
133604 ** array of leaf nodes starts at the first block allocated. The array
133605 ** of interior nodes that are parents of the leaf nodes start at block
133606 ** (start_block + (1 + end_block - start_block) / 16). And so on.
133608 ** In the actual code below, the value "16" is replaced with the
133609 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
133611 static int fts3IncrmergeWriter(
133612 Fts3Table *p, /* Fts3 table handle */
133613 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
133614 int iIdx, /* Index of new output segment */
133615 Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
133616 IncrmergeWriter *pWriter /* Populate this object */
133618 int rc; /* Return Code */
133619 int i; /* Iterator variable */
133620 int nLeafEst = 0; /* Blocks allocated for leaf nodes */
133621 sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
133622 sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
133624 /* Calculate nLeafEst. */
133625 rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
133626 if( rc==SQLITE_OK ){
133627 sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
133628 sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
133629 if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
133630 nLeafEst = sqlite3_column_int(pLeafEst, 0);
133632 rc = sqlite3_reset(pLeafEst);
133634 if( rc!=SQLITE_OK ) return rc;
133636 /* Calculate the first block to use in the output segment */
133637 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
133638 if( rc==SQLITE_OK ){
133639 if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
133640 pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
133641 pWriter->iEnd = pWriter->iStart - 1;
133642 pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
133644 rc = sqlite3_reset(pFirstBlock);
133646 if( rc!=SQLITE_OK ) return rc;
133648 /* Insert the marker in the %_segments table to make sure nobody tries
133649 ** to steal the space just allocated. This is also used to identify
133650 ** appendable segments. */
133651 rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
133652 if( rc!=SQLITE_OK ) return rc;
133654 pWriter->iAbsLevel = iAbsLevel;
133655 pWriter->nLeafEst = nLeafEst;
133656 pWriter->iIdx = iIdx;
133658 /* Set up the array of NodeWriter objects */
133659 for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
133660 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
133662 return SQLITE_OK;
133666 ** Remove an entry from the %_segdir table. This involves running the
133667 ** following two statements:
133669 ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
133670 ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
133672 ** The DELETE statement removes the specific %_segdir level. The UPDATE
133673 ** statement ensures that the remaining segments have contiguously allocated
133674 ** idx values.
133676 static int fts3RemoveSegdirEntry(
133677 Fts3Table *p, /* FTS3 table handle */
133678 sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
133679 int iIdx /* Index of %_segdir entry to delete */
133681 int rc; /* Return code */
133682 sqlite3_stmt *pDelete = 0; /* DELETE statement */
133684 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
133685 if( rc==SQLITE_OK ){
133686 sqlite3_bind_int64(pDelete, 1, iAbsLevel);
133687 sqlite3_bind_int(pDelete, 2, iIdx);
133688 sqlite3_step(pDelete);
133689 rc = sqlite3_reset(pDelete);
133692 return rc;
133696 ** One or more segments have just been removed from absolute level iAbsLevel.
133697 ** Update the 'idx' values of the remaining segments in the level so that
133698 ** the idx values are a contiguous sequence starting from 0.
133700 static int fts3RepackSegdirLevel(
133701 Fts3Table *p, /* FTS3 table handle */
133702 sqlite3_int64 iAbsLevel /* Absolute level to repack */
133704 int rc; /* Return code */
133705 int *aIdx = 0; /* Array of remaining idx values */
133706 int nIdx = 0; /* Valid entries in aIdx[] */
133707 int nAlloc = 0; /* Allocated size of aIdx[] */
133708 int i; /* Iterator variable */
133709 sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
133710 sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
133712 rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
133713 if( rc==SQLITE_OK ){
133714 int rc2;
133715 sqlite3_bind_int64(pSelect, 1, iAbsLevel);
133716 while( SQLITE_ROW==sqlite3_step(pSelect) ){
133717 if( nIdx>=nAlloc ){
133718 int *aNew;
133719 nAlloc += 16;
133720 aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
133721 if( !aNew ){
133722 rc = SQLITE_NOMEM;
133723 break;
133725 aIdx = aNew;
133727 aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
133729 rc2 = sqlite3_reset(pSelect);
133730 if( rc==SQLITE_OK ) rc = rc2;
133733 if( rc==SQLITE_OK ){
133734 rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
133736 if( rc==SQLITE_OK ){
133737 sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
133740 assert( p->bIgnoreSavepoint==0 );
133741 p->bIgnoreSavepoint = 1;
133742 for(i=0; rc==SQLITE_OK && i<nIdx; i++){
133743 if( aIdx[i]!=i ){
133744 sqlite3_bind_int(pUpdate, 3, aIdx[i]);
133745 sqlite3_bind_int(pUpdate, 1, i);
133746 sqlite3_step(pUpdate);
133747 rc = sqlite3_reset(pUpdate);
133750 p->bIgnoreSavepoint = 0;
133752 sqlite3_free(aIdx);
133753 return rc;
133756 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
133757 pNode->a[0] = (char)iHeight;
133758 if( iChild ){
133759 assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
133760 pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
133761 }else{
133762 assert( pNode->nAlloc>=1 );
133763 pNode->n = 1;
133768 ** The first two arguments are a pointer to and the size of a segment b-tree
133769 ** node. The node may be a leaf or an internal node.
133771 ** This function creates a new node image in blob object *pNew by copying
133772 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
133773 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
133775 static int fts3TruncateNode(
133776 const char *aNode, /* Current node image */
133777 int nNode, /* Size of aNode in bytes */
133778 Blob *pNew, /* OUT: Write new node image here */
133779 const char *zTerm, /* Omit all terms smaller than this */
133780 int nTerm, /* Size of zTerm in bytes */
133781 sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
133783 NodeReader reader; /* Reader object */
133784 Blob prev = {0, 0, 0}; /* Previous term written to new node */
133785 int rc = SQLITE_OK; /* Return code */
133786 int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
133788 /* Allocate required output space */
133789 blobGrowBuffer(pNew, nNode, &rc);
133790 if( rc!=SQLITE_OK ) return rc;
133791 pNew->n = 0;
133793 /* Populate new node buffer */
133794 for(rc = nodeReaderInit(&reader, aNode, nNode);
133795 rc==SQLITE_OK && reader.aNode;
133796 rc = nodeReaderNext(&reader)
133798 if( pNew->n==0 ){
133799 int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
133800 if( res<0 || (bLeaf==0 && res==0) ) continue;
133801 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
133802 *piBlock = reader.iChild;
133804 rc = fts3AppendToNode(
133805 pNew, &prev, reader.term.a, reader.term.n,
133806 reader.aDoclist, reader.nDoclist
133808 if( rc!=SQLITE_OK ) break;
133810 if( pNew->n==0 ){
133811 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
133812 *piBlock = reader.iChild;
133814 assert( pNew->n<=pNew->nAlloc );
133816 nodeReaderRelease(&reader);
133817 sqlite3_free(prev.a);
133818 return rc;
133822 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
133823 ** level iAbsLevel. This may involve deleting entries from the %_segments
133824 ** table, and modifying existing entries in both the %_segments and %_segdir
133825 ** tables.
133827 ** SQLITE_OK is returned if the segment is updated successfully. Or an
133828 ** SQLite error code otherwise.
133830 static int fts3TruncateSegment(
133831 Fts3Table *p, /* FTS3 table handle */
133832 sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
133833 int iIdx, /* Index within level of segment to modify */
133834 const char *zTerm, /* Remove terms smaller than this */
133835 int nTerm /* Number of bytes in buffer zTerm */
133837 int rc = SQLITE_OK; /* Return code */
133838 Blob root = {0,0,0}; /* New root page image */
133839 Blob block = {0,0,0}; /* Buffer used for any other block */
133840 sqlite3_int64 iBlock = 0; /* Block id */
133841 sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
133842 sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
133843 sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
133845 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
133846 if( rc==SQLITE_OK ){
133847 int rc2; /* sqlite3_reset() return code */
133848 sqlite3_bind_int64(pFetch, 1, iAbsLevel);
133849 sqlite3_bind_int(pFetch, 2, iIdx);
133850 if( SQLITE_ROW==sqlite3_step(pFetch) ){
133851 const char *aRoot = sqlite3_column_blob(pFetch, 4);
133852 int nRoot = sqlite3_column_bytes(pFetch, 4);
133853 iOldStart = sqlite3_column_int64(pFetch, 1);
133854 rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
133856 rc2 = sqlite3_reset(pFetch);
133857 if( rc==SQLITE_OK ) rc = rc2;
133860 while( rc==SQLITE_OK && iBlock ){
133861 char *aBlock = 0;
133862 int nBlock = 0;
133863 iNewStart = iBlock;
133865 rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
133866 if( rc==SQLITE_OK ){
133867 rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
133869 if( rc==SQLITE_OK ){
133870 rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
133872 sqlite3_free(aBlock);
133875 /* Variable iNewStart now contains the first valid leaf node. */
133876 if( rc==SQLITE_OK && iNewStart ){
133877 sqlite3_stmt *pDel = 0;
133878 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
133879 if( rc==SQLITE_OK ){
133880 sqlite3_bind_int64(pDel, 1, iOldStart);
133881 sqlite3_bind_int64(pDel, 2, iNewStart-1);
133882 sqlite3_step(pDel);
133883 rc = sqlite3_reset(pDel);
133887 if( rc==SQLITE_OK ){
133888 sqlite3_stmt *pChomp = 0;
133889 rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
133890 if( rc==SQLITE_OK ){
133891 sqlite3_bind_int64(pChomp, 1, iNewStart);
133892 sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
133893 sqlite3_bind_int64(pChomp, 3, iAbsLevel);
133894 sqlite3_bind_int(pChomp, 4, iIdx);
133895 sqlite3_step(pChomp);
133896 rc = sqlite3_reset(pChomp);
133900 sqlite3_free(root.a);
133901 sqlite3_free(block.a);
133902 return rc;
133906 ** This function is called after an incrmental-merge operation has run to
133907 ** merge (or partially merge) two or more segments from absolute level
133908 ** iAbsLevel.
133910 ** Each input segment is either removed from the db completely (if all of
133911 ** its data was copied to the output segment by the incrmerge operation)
133912 ** or modified in place so that it no longer contains those entries that
133913 ** have been duplicated in the output segment.
133915 static int fts3IncrmergeChomp(
133916 Fts3Table *p, /* FTS table handle */
133917 sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
133918 Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
133919 int *pnRem /* Number of segments not deleted */
133921 int i;
133922 int nRem = 0;
133923 int rc = SQLITE_OK;
133925 for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
133926 Fts3SegReader *pSeg = 0;
133927 int j;
133929 /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
133930 ** somewhere in the pCsr->apSegment[] array. */
133931 for(j=0; ALWAYS(j<pCsr->nSegment); j++){
133932 pSeg = pCsr->apSegment[j];
133933 if( pSeg->iIdx==i ) break;
133935 assert( j<pCsr->nSegment && pSeg->iIdx==i );
133937 if( pSeg->aNode==0 ){
133938 /* Seg-reader is at EOF. Remove the entire input segment. */
133939 rc = fts3DeleteSegment(p, pSeg);
133940 if( rc==SQLITE_OK ){
133941 rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
133943 *pnRem = 0;
133944 }else{
133945 /* The incremental merge did not copy all the data from this
133946 ** segment to the upper level. The segment is modified in place
133947 ** so that it contains no keys smaller than zTerm/nTerm. */
133948 const char *zTerm = pSeg->zTerm;
133949 int nTerm = pSeg->nTerm;
133950 rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
133951 nRem++;
133955 if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
133956 rc = fts3RepackSegdirLevel(p, iAbsLevel);
133959 *pnRem = nRem;
133960 return rc;
133964 ** Store an incr-merge hint in the database.
133966 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
133967 sqlite3_stmt *pReplace = 0;
133968 int rc; /* Return code */
133970 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
133971 if( rc==SQLITE_OK ){
133972 sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
133973 sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
133974 sqlite3_step(pReplace);
133975 rc = sqlite3_reset(pReplace);
133978 return rc;
133982 ** Load an incr-merge hint from the database. The incr-merge hint, if one
133983 ** exists, is stored in the rowid==1 row of the %_stat table.
133985 ** If successful, populate blob *pHint with the value read from the %_stat
133986 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
133987 ** SQLite error code.
133989 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
133990 sqlite3_stmt *pSelect = 0;
133991 int rc;
133993 pHint->n = 0;
133994 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
133995 if( rc==SQLITE_OK ){
133996 int rc2;
133997 sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
133998 if( SQLITE_ROW==sqlite3_step(pSelect) ){
133999 const char *aHint = sqlite3_column_blob(pSelect, 0);
134000 int nHint = sqlite3_column_bytes(pSelect, 0);
134001 if( aHint ){
134002 blobGrowBuffer(pHint, nHint, &rc);
134003 if( rc==SQLITE_OK ){
134004 memcpy(pHint->a, aHint, nHint);
134005 pHint->n = nHint;
134009 rc2 = sqlite3_reset(pSelect);
134010 if( rc==SQLITE_OK ) rc = rc2;
134013 return rc;
134017 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
134018 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
134019 ** consists of two varints, the absolute level number of the input segments
134020 ** and the number of input segments.
134022 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
134023 ** set *pRc to an SQLite error code before returning.
134025 static void fts3IncrmergeHintPush(
134026 Blob *pHint, /* Hint blob to append to */
134027 i64 iAbsLevel, /* First varint to store in hint */
134028 int nInput, /* Second varint to store in hint */
134029 int *pRc /* IN/OUT: Error code */
134031 blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
134032 if( *pRc==SQLITE_OK ){
134033 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
134034 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
134039 ** Read the last entry (most recently pushed) from the hint blob *pHint
134040 ** and then remove the entry. Write the two values read to *piAbsLevel and
134041 ** *pnInput before returning.
134043 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
134044 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
134046 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
134047 const int nHint = pHint->n;
134048 int i;
134050 i = pHint->n-2;
134051 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
134052 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
134054 pHint->n = i;
134055 i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
134056 i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
134057 if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
134059 return SQLITE_OK;
134064 ** Attempt an incremental merge that writes nMerge leaf blocks.
134066 ** Incremental merges happen nMin segments at a time. The two
134067 ** segments to be merged are the nMin oldest segments (the ones with
134068 ** the smallest indexes) in the highest level that contains at least
134069 ** nMin segments. Multiple merges might occur in an attempt to write the
134070 ** quota of nMerge leaf blocks.
134072 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
134073 int rc; /* Return code */
134074 int nRem = nMerge; /* Number of leaf pages yet to be written */
134075 Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
134076 Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
134077 IncrmergeWriter *pWriter; /* Writer object */
134078 int nSeg = 0; /* Number of input segments */
134079 sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
134080 Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
134081 int bDirtyHint = 0; /* True if blob 'hint' has been modified */
134083 /* Allocate space for the cursor, filter and writer objects */
134084 const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
134085 pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
134086 if( !pWriter ) return SQLITE_NOMEM;
134087 pFilter = (Fts3SegFilter *)&pWriter[1];
134088 pCsr = (Fts3MultiSegReader *)&pFilter[1];
134090 rc = fts3IncrmergeHintLoad(p, &hint);
134091 while( rc==SQLITE_OK && nRem>0 ){
134092 const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
134093 sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
134094 int bUseHint = 0; /* True if attempting to append */
134096 /* Search the %_segdir table for the absolute level with the smallest
134097 ** relative level number that contains at least nMin segments, if any.
134098 ** If one is found, set iAbsLevel to the absolute level number and
134099 ** nSeg to nMin. If no level with at least nMin segments can be found,
134100 ** set nSeg to -1.
134102 rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
134103 sqlite3_bind_int(pFindLevel, 1, nMin);
134104 if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
134105 iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
134106 nSeg = nMin;
134107 }else{
134108 nSeg = -1;
134110 rc = sqlite3_reset(pFindLevel);
134112 /* If the hint read from the %_stat table is not empty, check if the
134113 ** last entry in it specifies a relative level smaller than or equal
134114 ** to the level identified by the block above (if any). If so, this
134115 ** iteration of the loop will work on merging at the hinted level.
134117 if( rc==SQLITE_OK && hint.n ){
134118 int nHint = hint.n;
134119 sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
134120 int nHintSeg = 0; /* Hint number of segments */
134122 rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
134123 if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
134124 iAbsLevel = iHintAbsLevel;
134125 nSeg = nHintSeg;
134126 bUseHint = 1;
134127 bDirtyHint = 1;
134128 }else{
134129 /* This undoes the effect of the HintPop() above - so that no entry
134130 ** is removed from the hint blob. */
134131 hint.n = nHint;
134135 /* If nSeg is less that zero, then there is no level with at least
134136 ** nMin segments and no hint in the %_stat table. No work to do.
134137 ** Exit early in this case. */
134138 if( nSeg<0 ) break;
134140 /* Open a cursor to iterate through the contents of the oldest nSeg
134141 ** indexes of absolute level iAbsLevel. If this cursor is opened using
134142 ** the 'hint' parameters, it is possible that there are less than nSeg
134143 ** segments available in level iAbsLevel. In this case, no work is
134144 ** done on iAbsLevel - fall through to the next iteration of the loop
134145 ** to start work on some other level. */
134146 memset(pWriter, 0, nAlloc);
134147 pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
134148 if( rc==SQLITE_OK ){
134149 rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
134151 if( SQLITE_OK==rc && pCsr->nSegment==nSeg
134152 && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
134153 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
134155 int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
134156 rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
134157 if( rc==SQLITE_OK ){
134158 if( bUseHint && iIdx>0 ){
134159 const char *zKey = pCsr->zTerm;
134160 int nKey = pCsr->nTerm;
134161 rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
134162 }else{
134163 rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
134167 if( rc==SQLITE_OK && pWriter->nLeafEst ){
134168 fts3LogMerge(nSeg, iAbsLevel);
134170 rc = fts3IncrmergeAppend(p, pWriter, pCsr);
134171 if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
134172 if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
134173 }while( rc==SQLITE_ROW );
134175 /* Update or delete the input segments */
134176 if( rc==SQLITE_OK ){
134177 nRem -= (1 + pWriter->nWork);
134178 rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
134179 if( nSeg!=0 ){
134180 bDirtyHint = 1;
134181 fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
134186 fts3IncrmergeRelease(p, pWriter, &rc);
134189 sqlite3Fts3SegReaderFinish(pCsr);
134192 /* Write the hint values into the %_stat table for the next incr-merger */
134193 if( bDirtyHint && rc==SQLITE_OK ){
134194 rc = fts3IncrmergeHintStore(p, &hint);
134197 sqlite3_free(pWriter);
134198 sqlite3_free(hint.a);
134199 return rc;
134203 ** Convert the text beginning at *pz into an integer and return
134204 ** its value. Advance *pz to point to the first character past
134205 ** the integer.
134207 static int fts3Getint(const char **pz){
134208 const char *z = *pz;
134209 int i = 0;
134210 while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
134211 *pz = z;
134212 return i;
134216 ** Process statements of the form:
134218 ** INSERT INTO table(table) VALUES('merge=A,B');
134220 ** A and B are integers that decode to be the number of leaf pages
134221 ** written for the merge, and the minimum number of segments on a level
134222 ** before it will be selected for a merge, respectively.
134224 static int fts3DoIncrmerge(
134225 Fts3Table *p, /* FTS3 table handle */
134226 const char *zParam /* Nul-terminated string containing "A,B" */
134228 int rc;
134229 int nMin = (FTS3_MERGE_COUNT / 2);
134230 int nMerge = 0;
134231 const char *z = zParam;
134233 /* Read the first integer value */
134234 nMerge = fts3Getint(&z);
134236 /* If the first integer value is followed by a ',', read the second
134237 ** integer value. */
134238 if( z[0]==',' && z[1]!='\0' ){
134240 nMin = fts3Getint(&z);
134243 if( z[0]!='\0' || nMin<2 ){
134244 rc = SQLITE_ERROR;
134245 }else{
134246 rc = SQLITE_OK;
134247 if( !p->bHasStat ){
134248 assert( p->bFts4==0 );
134249 sqlite3Fts3CreateStatTable(&rc, p);
134251 if( rc==SQLITE_OK ){
134252 rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
134254 sqlite3Fts3SegmentsClose(p);
134256 return rc;
134260 ** Process statements of the form:
134262 ** INSERT INTO table(table) VALUES('automerge=X');
134264 ** where X is an integer. X==0 means to turn automerge off. X!=0 means
134265 ** turn it on. The setting is persistent.
134267 static int fts3DoAutoincrmerge(
134268 Fts3Table *p, /* FTS3 table handle */
134269 const char *zParam /* Nul-terminated string containing boolean */
134271 int rc = SQLITE_OK;
134272 sqlite3_stmt *pStmt = 0;
134273 p->bAutoincrmerge = fts3Getint(&zParam)!=0;
134274 if( !p->bHasStat ){
134275 assert( p->bFts4==0 );
134276 sqlite3Fts3CreateStatTable(&rc, p);
134277 if( rc ) return rc;
134279 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
134280 if( rc ) return rc;;
134281 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
134282 sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
134283 sqlite3_step(pStmt);
134284 rc = sqlite3_reset(pStmt);
134285 return rc;
134289 ** Return a 64-bit checksum for the FTS index entry specified by the
134290 ** arguments to this function.
134292 static u64 fts3ChecksumEntry(
134293 const char *zTerm, /* Pointer to buffer containing term */
134294 int nTerm, /* Size of zTerm in bytes */
134295 int iLangid, /* Language id for current row */
134296 int iIndex, /* Index (0..Fts3Table.nIndex-1) */
134297 i64 iDocid, /* Docid for current row. */
134298 int iCol, /* Column number */
134299 int iPos /* Position */
134301 int i;
134302 u64 ret = (u64)iDocid;
134304 ret += (ret<<3) + iLangid;
134305 ret += (ret<<3) + iIndex;
134306 ret += (ret<<3) + iCol;
134307 ret += (ret<<3) + iPos;
134308 for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
134310 return ret;
134314 ** Return a checksum of all entries in the FTS index that correspond to
134315 ** language id iLangid. The checksum is calculated by XORing the checksums
134316 ** of each individual entry (see fts3ChecksumEntry()) together.
134318 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
134319 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
134320 ** return value is undefined in this case.
134322 static u64 fts3ChecksumIndex(
134323 Fts3Table *p, /* FTS3 table handle */
134324 int iLangid, /* Language id to return cksum for */
134325 int iIndex, /* Index to cksum (0..p->nIndex-1) */
134326 int *pRc /* OUT: Return code */
134328 Fts3SegFilter filter;
134329 Fts3MultiSegReader csr;
134330 int rc;
134331 u64 cksum = 0;
134333 assert( *pRc==SQLITE_OK );
134335 memset(&filter, 0, sizeof(filter));
134336 memset(&csr, 0, sizeof(csr));
134337 filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
134338 filter.flags |= FTS3_SEGMENT_SCAN;
134340 rc = sqlite3Fts3SegReaderCursor(
134341 p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
134343 if( rc==SQLITE_OK ){
134344 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
134347 if( rc==SQLITE_OK ){
134348 while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
134349 char *pCsr = csr.aDoclist;
134350 char *pEnd = &pCsr[csr.nDoclist];
134352 i64 iDocid = 0;
134353 i64 iCol = 0;
134354 i64 iPos = 0;
134356 pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
134357 while( pCsr<pEnd ){
134358 i64 iVal = 0;
134359 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
134360 if( pCsr<pEnd ){
134361 if( iVal==0 || iVal==1 ){
134362 iCol = 0;
134363 iPos = 0;
134364 if( iVal ){
134365 pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
134366 }else{
134367 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
134368 iDocid += iVal;
134370 }else{
134371 iPos += (iVal - 2);
134372 cksum = cksum ^ fts3ChecksumEntry(
134373 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
134374 (int)iCol, (int)iPos
134381 sqlite3Fts3SegReaderFinish(&csr);
134383 *pRc = rc;
134384 return cksum;
134388 ** Check if the contents of the FTS index match the current contents of the
134389 ** content table. If no error occurs and the contents do match, set *pbOk
134390 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
134391 ** to false before returning.
134393 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
134394 ** code. The final value of *pbOk is undefined in this case.
134396 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
134397 int rc = SQLITE_OK; /* Return code */
134398 u64 cksum1 = 0; /* Checksum based on FTS index contents */
134399 u64 cksum2 = 0; /* Checksum based on %_content contents */
134400 sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
134402 /* This block calculates the checksum according to the FTS index. */
134403 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
134404 if( rc==SQLITE_OK ){
134405 int rc2;
134406 sqlite3_bind_int(pAllLangid, 1, p->nIndex);
134407 while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
134408 int iLangid = sqlite3_column_int(pAllLangid, 0);
134409 int i;
134410 for(i=0; i<p->nIndex; i++){
134411 cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
134414 rc2 = sqlite3_reset(pAllLangid);
134415 if( rc==SQLITE_OK ) rc = rc2;
134418 /* This block calculates the checksum according to the %_content table */
134419 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
134420 if( rc==SQLITE_OK ){
134421 sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
134422 sqlite3_stmt *pStmt = 0;
134423 char *zSql;
134425 zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
134426 if( !zSql ){
134427 rc = SQLITE_NOMEM;
134428 }else{
134429 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
134430 sqlite3_free(zSql);
134433 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
134434 i64 iDocid = sqlite3_column_int64(pStmt, 0);
134435 int iLang = langidFromSelect(p, pStmt);
134436 int iCol;
134438 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
134439 const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
134440 int nText = sqlite3_column_bytes(pStmt, iCol+1);
134441 sqlite3_tokenizer_cursor *pT = 0;
134443 rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
134444 while( rc==SQLITE_OK ){
134445 char const *zToken; /* Buffer containing token */
134446 int nToken = 0; /* Number of bytes in token */
134447 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
134448 int iPos = 0; /* Position of token in zText */
134450 rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
134451 if( rc==SQLITE_OK ){
134452 int i;
134453 cksum2 = cksum2 ^ fts3ChecksumEntry(
134454 zToken, nToken, iLang, 0, iDocid, iCol, iPos
134456 for(i=1; i<p->nIndex; i++){
134457 if( p->aIndex[i].nPrefix<=nToken ){
134458 cksum2 = cksum2 ^ fts3ChecksumEntry(
134459 zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
134465 if( pT ) pModule->xClose(pT);
134466 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
134470 sqlite3_finalize(pStmt);
134473 *pbOk = (cksum1==cksum2);
134474 return rc;
134478 ** Run the integrity-check. If no error occurs and the current contents of
134479 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
134480 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
134482 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
134483 ** error code.
134485 ** The integrity-check works as follows. For each token and indexed token
134486 ** prefix in the document set, a 64-bit checksum is calculated (by code
134487 ** in fts3ChecksumEntry()) based on the following:
134489 ** + The index number (0 for the main index, 1 for the first prefix
134490 ** index etc.),
134491 ** + The token (or token prefix) text itself,
134492 ** + The language-id of the row it appears in,
134493 ** + The docid of the row it appears in,
134494 ** + The column it appears in, and
134495 ** + The tokens position within that column.
134497 ** The checksums for all entries in the index are XORed together to create
134498 ** a single checksum for the entire index.
134500 ** The integrity-check code calculates the same checksum in two ways:
134502 ** 1. By scanning the contents of the FTS index, and
134503 ** 2. By scanning and tokenizing the content table.
134505 ** If the two checksums are identical, the integrity-check is deemed to have
134506 ** passed.
134508 static int fts3DoIntegrityCheck(
134509 Fts3Table *p /* FTS3 table handle */
134511 int rc;
134512 int bOk = 0;
134513 rc = fts3IntegrityCheck(p, &bOk);
134514 if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
134515 return rc;
134519 ** Handle a 'special' INSERT of the form:
134521 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
134523 ** Argument pVal contains the result of <expr>. Currently the only
134524 ** meaningful value to insert is the text 'optimize'.
134526 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
134527 int rc; /* Return Code */
134528 const char *zVal = (const char *)sqlite3_value_text(pVal);
134529 int nVal = sqlite3_value_bytes(pVal);
134531 if( !zVal ){
134532 return SQLITE_NOMEM;
134533 }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
134534 rc = fts3DoOptimize(p, 0);
134535 }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
134536 rc = fts3DoRebuild(p);
134537 }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
134538 rc = fts3DoIntegrityCheck(p);
134539 }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
134540 rc = fts3DoIncrmerge(p, &zVal[6]);
134541 }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
134542 rc = fts3DoAutoincrmerge(p, &zVal[10]);
134543 #ifdef SQLITE_TEST
134544 }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
134545 p->nNodeSize = atoi(&zVal[9]);
134546 rc = SQLITE_OK;
134547 }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
134548 p->nMaxPendingData = atoi(&zVal[11]);
134549 rc = SQLITE_OK;
134550 #endif
134551 }else{
134552 rc = SQLITE_ERROR;
134555 return rc;
134558 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
134560 ** Delete all cached deferred doclists. Deferred doclists are cached
134561 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
134563 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
134564 Fts3DeferredToken *pDef;
134565 for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
134566 fts3PendingListDelete(pDef->pList);
134567 pDef->pList = 0;
134572 ** Free all entries in the pCsr->pDeffered list. Entries are added to
134573 ** this list using sqlite3Fts3DeferToken().
134575 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
134576 Fts3DeferredToken *pDef;
134577 Fts3DeferredToken *pNext;
134578 for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
134579 pNext = pDef->pNext;
134580 fts3PendingListDelete(pDef->pList);
134581 sqlite3_free(pDef);
134583 pCsr->pDeferred = 0;
134587 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
134588 ** based on the row that pCsr currently points to.
134590 ** A deferred-doclist is like any other doclist with position information
134591 ** included, except that it only contains entries for a single row of the
134592 ** table, not for all rows.
134594 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
134595 int rc = SQLITE_OK; /* Return code */
134596 if( pCsr->pDeferred ){
134597 int i; /* Used to iterate through table columns */
134598 sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
134599 Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
134601 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
134602 sqlite3_tokenizer *pT = p->pTokenizer;
134603 sqlite3_tokenizer_module const *pModule = pT->pModule;
134605 assert( pCsr->isRequireSeek==0 );
134606 iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
134608 for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
134609 if( p->abNotindexed[i]==0 ){
134610 const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
134611 sqlite3_tokenizer_cursor *pTC = 0;
134613 rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
134614 while( rc==SQLITE_OK ){
134615 char const *zToken; /* Buffer containing token */
134616 int nToken = 0; /* Number of bytes in token */
134617 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
134618 int iPos = 0; /* Position of token in zText */
134620 rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
134621 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
134622 Fts3PhraseToken *pPT = pDef->pToken;
134623 if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
134624 && (pPT->bFirst==0 || iPos==0)
134625 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
134626 && (0==memcmp(zToken, pPT->z, pPT->n))
134628 fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
134632 if( pTC ) pModule->xClose(pTC);
134633 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
134637 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
134638 if( pDef->pList ){
134639 rc = fts3PendingListAppendVarint(&pDef->pList, 0);
134644 return rc;
134647 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
134648 Fts3DeferredToken *p,
134649 char **ppData,
134650 int *pnData
134652 char *pRet;
134653 int nSkip;
134654 sqlite3_int64 dummy;
134656 *ppData = 0;
134657 *pnData = 0;
134659 if( p->pList==0 ){
134660 return SQLITE_OK;
134663 pRet = (char *)sqlite3_malloc(p->pList->nData);
134664 if( !pRet ) return SQLITE_NOMEM;
134666 nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
134667 *pnData = p->pList->nData - nSkip;
134668 *ppData = pRet;
134670 memcpy(pRet, &p->pList->aData[nSkip], *pnData);
134671 return SQLITE_OK;
134675 ** Add an entry for token pToken to the pCsr->pDeferred list.
134677 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
134678 Fts3Cursor *pCsr, /* Fts3 table cursor */
134679 Fts3PhraseToken *pToken, /* Token to defer */
134680 int iCol /* Column that token must appear in (or -1) */
134682 Fts3DeferredToken *pDeferred;
134683 pDeferred = sqlite3_malloc(sizeof(*pDeferred));
134684 if( !pDeferred ){
134685 return SQLITE_NOMEM;
134687 memset(pDeferred, 0, sizeof(*pDeferred));
134688 pDeferred->pToken = pToken;
134689 pDeferred->pNext = pCsr->pDeferred;
134690 pDeferred->iCol = iCol;
134691 pCsr->pDeferred = pDeferred;
134693 assert( pToken->pDeferred==0 );
134694 pToken->pDeferred = pDeferred;
134696 return SQLITE_OK;
134698 #endif
134701 ** SQLite value pRowid contains the rowid of a row that may or may not be
134702 ** present in the FTS3 table. If it is, delete it and adjust the contents
134703 ** of subsiduary data structures accordingly.
134705 static int fts3DeleteByRowid(
134706 Fts3Table *p,
134707 sqlite3_value *pRowid,
134708 int *pnChng, /* IN/OUT: Decrement if row is deleted */
134709 u32 *aSzDel
134711 int rc = SQLITE_OK; /* Return code */
134712 int bFound = 0; /* True if *pRowid really is in the table */
134714 fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
134715 if( bFound && rc==SQLITE_OK ){
134716 int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
134717 rc = fts3IsEmpty(p, pRowid, &isEmpty);
134718 if( rc==SQLITE_OK ){
134719 if( isEmpty ){
134720 /* Deleting this row means the whole table is empty. In this case
134721 ** delete the contents of all three tables and throw away any
134722 ** data in the pendingTerms hash table. */
134723 rc = fts3DeleteAll(p, 1);
134724 *pnChng = 0;
134725 memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
134726 }else{
134727 *pnChng = *pnChng - 1;
134728 if( p->zContentTbl==0 ){
134729 fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
134731 if( p->bHasDocsize ){
134732 fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
134738 return rc;
134742 ** This function does the work for the xUpdate method of FTS3 virtual
134743 ** tables. The schema of the virtual table being:
134745 ** CREATE TABLE <table name>(
134746 ** <user columns>,
134747 ** <table name> HIDDEN,
134748 ** docid HIDDEN,
134749 ** <langid> HIDDEN
134750 ** );
134754 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
134755 sqlite3_vtab *pVtab, /* FTS3 vtab object */
134756 int nArg, /* Size of argument array */
134757 sqlite3_value **apVal, /* Array of arguments */
134758 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
134760 Fts3Table *p = (Fts3Table *)pVtab;
134761 int rc = SQLITE_OK; /* Return Code */
134762 int isRemove = 0; /* True for an UPDATE or DELETE */
134763 u32 *aSzIns = 0; /* Sizes of inserted documents */
134764 u32 *aSzDel = 0; /* Sizes of deleted documents */
134765 int nChng = 0; /* Net change in number of documents */
134766 int bInsertDone = 0;
134768 assert( p->pSegments==0 );
134769 assert(
134770 nArg==1 /* DELETE operations */
134771 || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
134774 /* Check for a "special" INSERT operation. One of the form:
134776 ** INSERT INTO xyz(xyz) VALUES('command');
134778 if( nArg>1
134779 && sqlite3_value_type(apVal[0])==SQLITE_NULL
134780 && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
134782 rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
134783 goto update_out;
134786 if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
134787 rc = SQLITE_CONSTRAINT;
134788 goto update_out;
134791 /* Allocate space to hold the change in document sizes */
134792 aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
134793 if( aSzDel==0 ){
134794 rc = SQLITE_NOMEM;
134795 goto update_out;
134797 aSzIns = &aSzDel[p->nColumn+1];
134798 memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
134800 rc = fts3Writelock(p);
134801 if( rc!=SQLITE_OK ) goto update_out;
134803 /* If this is an INSERT operation, or an UPDATE that modifies the rowid
134804 ** value, then this operation requires constraint handling.
134806 ** If the on-conflict mode is REPLACE, this means that the existing row
134807 ** should be deleted from the database before inserting the new row. Or,
134808 ** if the on-conflict mode is other than REPLACE, then this method must
134809 ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
134810 ** modify the database file.
134812 if( nArg>1 && p->zContentTbl==0 ){
134813 /* Find the value object that holds the new rowid value. */
134814 sqlite3_value *pNewRowid = apVal[3+p->nColumn];
134815 if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
134816 pNewRowid = apVal[1];
134819 if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
134820 sqlite3_value_type(apVal[0])==SQLITE_NULL
134821 || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
134823 /* The new rowid is not NULL (in this case the rowid will be
134824 ** automatically assigned and there is no chance of a conflict), and
134825 ** the statement is either an INSERT or an UPDATE that modifies the
134826 ** rowid column. So if the conflict mode is REPLACE, then delete any
134827 ** existing row with rowid=pNewRowid.
134829 ** Or, if the conflict mode is not REPLACE, insert the new record into
134830 ** the %_content table. If we hit the duplicate rowid constraint (or any
134831 ** other error) while doing so, return immediately.
134833 ** This branch may also run if pNewRowid contains a value that cannot
134834 ** be losslessly converted to an integer. In this case, the eventual
134835 ** call to fts3InsertData() (either just below or further on in this
134836 ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
134837 ** invoked, it will delete zero rows (since no row will have
134838 ** docid=$pNewRowid if $pNewRowid is not an integer value).
134840 if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
134841 rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
134842 }else{
134843 rc = fts3InsertData(p, apVal, pRowid);
134844 bInsertDone = 1;
134848 if( rc!=SQLITE_OK ){
134849 goto update_out;
134852 /* If this is a DELETE or UPDATE operation, remove the old record. */
134853 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
134854 assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
134855 rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
134856 isRemove = 1;
134859 /* If this is an INSERT or UPDATE operation, insert the new record. */
134860 if( nArg>1 && rc==SQLITE_OK ){
134861 int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
134862 if( bInsertDone==0 ){
134863 rc = fts3InsertData(p, apVal, pRowid);
134864 if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
134865 rc = FTS_CORRUPT_VTAB;
134868 if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
134869 rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
134871 if( rc==SQLITE_OK ){
134872 assert( p->iPrevDocid==*pRowid );
134873 rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
134875 if( p->bHasDocsize ){
134876 fts3InsertDocsize(&rc, p, aSzIns);
134878 nChng++;
134881 if( p->bFts4 ){
134882 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
134885 update_out:
134886 sqlite3_free(aSzDel);
134887 sqlite3Fts3SegmentsClose(p);
134888 return rc;
134892 ** Flush any data in the pending-terms hash table to disk. If successful,
134893 ** merge all segments in the database (including the new segment, if
134894 ** there was any data to flush) into a single segment.
134896 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
134897 int rc;
134898 rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
134899 if( rc==SQLITE_OK ){
134900 rc = fts3DoOptimize(p, 1);
134901 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
134902 int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
134903 if( rc2!=SQLITE_OK ) rc = rc2;
134904 }else{
134905 sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
134906 sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
134909 sqlite3Fts3SegmentsClose(p);
134910 return rc;
134913 #endif
134915 /************** End of fts3_write.c ******************************************/
134916 /************** Begin file fts3_snippet.c ************************************/
134918 ** 2009 Oct 23
134920 ** The author disclaims copyright to this source code. In place of
134921 ** a legal notice, here is a blessing:
134923 ** May you do good and not evil.
134924 ** May you find forgiveness for yourself and forgive others.
134925 ** May you share freely, never taking more than you give.
134927 ******************************************************************************
134930 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
134932 /* #include <string.h> */
134933 /* #include <assert.h> */
134936 ** Characters that may appear in the second argument to matchinfo().
134938 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
134939 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
134940 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
134941 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
134942 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
134943 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
134944 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
134947 ** The default value for the second argument to matchinfo().
134949 #define FTS3_MATCHINFO_DEFAULT "pcx"
134953 ** Used as an fts3ExprIterate() context when loading phrase doclists to
134954 ** Fts3Expr.aDoclist[]/nDoclist.
134956 typedef struct LoadDoclistCtx LoadDoclistCtx;
134957 struct LoadDoclistCtx {
134958 Fts3Cursor *pCsr; /* FTS3 Cursor */
134959 int nPhrase; /* Number of phrases seen so far */
134960 int nToken; /* Number of tokens seen so far */
134964 ** The following types are used as part of the implementation of the
134965 ** fts3BestSnippet() routine.
134967 typedef struct SnippetIter SnippetIter;
134968 typedef struct SnippetPhrase SnippetPhrase;
134969 typedef struct SnippetFragment SnippetFragment;
134971 struct SnippetIter {
134972 Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
134973 int iCol; /* Extract snippet from this column */
134974 int nSnippet; /* Requested snippet length (in tokens) */
134975 int nPhrase; /* Number of phrases in query */
134976 SnippetPhrase *aPhrase; /* Array of size nPhrase */
134977 int iCurrent; /* First token of current snippet */
134980 struct SnippetPhrase {
134981 int nToken; /* Number of tokens in phrase */
134982 char *pList; /* Pointer to start of phrase position list */
134983 int iHead; /* Next value in position list */
134984 char *pHead; /* Position list data following iHead */
134985 int iTail; /* Next value in trailing position list */
134986 char *pTail; /* Position list data following iTail */
134989 struct SnippetFragment {
134990 int iCol; /* Column snippet is extracted from */
134991 int iPos; /* Index of first token in snippet */
134992 u64 covered; /* Mask of query phrases covered */
134993 u64 hlmask; /* Mask of snippet terms to highlight */
134997 ** This type is used as an fts3ExprIterate() context object while
134998 ** accumulating the data returned by the matchinfo() function.
135000 typedef struct MatchInfo MatchInfo;
135001 struct MatchInfo {
135002 Fts3Cursor *pCursor; /* FTS3 Cursor */
135003 int nCol; /* Number of columns in table */
135004 int nPhrase; /* Number of matchable phrases in query */
135005 sqlite3_int64 nDoc; /* Number of docs in database */
135006 u32 *aMatchinfo; /* Pre-allocated buffer */
135012 ** The snippet() and offsets() functions both return text values. An instance
135013 ** of the following structure is used to accumulate those values while the
135014 ** functions are running. See fts3StringAppend() for details.
135016 typedef struct StrBuffer StrBuffer;
135017 struct StrBuffer {
135018 char *z; /* Pointer to buffer containing string */
135019 int n; /* Length of z in bytes (excl. nul-term) */
135020 int nAlloc; /* Allocated size of buffer z in bytes */
135025 ** This function is used to help iterate through a position-list. A position
135026 ** list is a list of unique integers, sorted from smallest to largest. Each
135027 ** element of the list is represented by an FTS3 varint that takes the value
135028 ** of the difference between the current element and the previous one plus
135029 ** two. For example, to store the position-list:
135031 ** 4 9 113
135033 ** the three varints:
135035 ** 6 7 106
135037 ** are encoded.
135039 ** When this function is called, *pp points to the start of an element of
135040 ** the list. *piPos contains the value of the previous entry in the list.
135041 ** After it returns, *piPos contains the value of the next element of the
135042 ** list and *pp is advanced to the following varint.
135044 static void fts3GetDeltaPosition(char **pp, int *piPos){
135045 int iVal;
135046 *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
135047 *piPos += (iVal-2);
135051 ** Helper function for fts3ExprIterate() (see below).
135053 static int fts3ExprIterate2(
135054 Fts3Expr *pExpr, /* Expression to iterate phrases of */
135055 int *piPhrase, /* Pointer to phrase counter */
135056 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
135057 void *pCtx /* Second argument to pass to callback */
135059 int rc; /* Return code */
135060 int eType = pExpr->eType; /* Type of expression node pExpr */
135062 if( eType!=FTSQUERY_PHRASE ){
135063 assert( pExpr->pLeft && pExpr->pRight );
135064 rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
135065 if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
135066 rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
135068 }else{
135069 rc = x(pExpr, *piPhrase, pCtx);
135070 (*piPhrase)++;
135072 return rc;
135076 ** Iterate through all phrase nodes in an FTS3 query, except those that
135077 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
135078 ** For each phrase node found, the supplied callback function is invoked.
135080 ** If the callback function returns anything other than SQLITE_OK,
135081 ** the iteration is abandoned and the error code returned immediately.
135082 ** Otherwise, SQLITE_OK is returned after a callback has been made for
135083 ** all eligible phrase nodes.
135085 static int fts3ExprIterate(
135086 Fts3Expr *pExpr, /* Expression to iterate phrases of */
135087 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
135088 void *pCtx /* Second argument to pass to callback */
135090 int iPhrase = 0; /* Variable used as the phrase counter */
135091 return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
135095 ** This is an fts3ExprIterate() callback used while loading the doclists
135096 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
135097 ** fts3ExprLoadDoclists().
135099 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
135100 int rc = SQLITE_OK;
135101 Fts3Phrase *pPhrase = pExpr->pPhrase;
135102 LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
135104 UNUSED_PARAMETER(iPhrase);
135106 p->nPhrase++;
135107 p->nToken += pPhrase->nToken;
135109 return rc;
135113 ** Load the doclists for each phrase in the query associated with FTS3 cursor
135114 ** pCsr.
135116 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
135117 ** phrases in the expression (all phrases except those directly or
135118 ** indirectly descended from the right-hand-side of a NOT operator). If
135119 ** pnToken is not NULL, then it is set to the number of tokens in all
135120 ** matchable phrases of the expression.
135122 static int fts3ExprLoadDoclists(
135123 Fts3Cursor *pCsr, /* Fts3 cursor for current query */
135124 int *pnPhrase, /* OUT: Number of phrases in query */
135125 int *pnToken /* OUT: Number of tokens in query */
135127 int rc; /* Return Code */
135128 LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
135129 sCtx.pCsr = pCsr;
135130 rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
135131 if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
135132 if( pnToken ) *pnToken = sCtx.nToken;
135133 return rc;
135136 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
135137 (*(int *)ctx)++;
135138 UNUSED_PARAMETER(pExpr);
135139 UNUSED_PARAMETER(iPhrase);
135140 return SQLITE_OK;
135142 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
135143 int nPhrase = 0;
135144 (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
135145 return nPhrase;
135149 ** Advance the position list iterator specified by the first two
135150 ** arguments so that it points to the first element with a value greater
135151 ** than or equal to parameter iNext.
135153 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
135154 char *pIter = *ppIter;
135155 if( pIter ){
135156 int iIter = *piIter;
135158 while( iIter<iNext ){
135159 if( 0==(*pIter & 0xFE) ){
135160 iIter = -1;
135161 pIter = 0;
135162 break;
135164 fts3GetDeltaPosition(&pIter, &iIter);
135167 *piIter = iIter;
135168 *ppIter = pIter;
135173 ** Advance the snippet iterator to the next candidate snippet.
135175 static int fts3SnippetNextCandidate(SnippetIter *pIter){
135176 int i; /* Loop counter */
135178 if( pIter->iCurrent<0 ){
135179 /* The SnippetIter object has just been initialized. The first snippet
135180 ** candidate always starts at offset 0 (even if this candidate has a
135181 ** score of 0.0).
135183 pIter->iCurrent = 0;
135185 /* Advance the 'head' iterator of each phrase to the first offset that
135186 ** is greater than or equal to (iNext+nSnippet).
135188 for(i=0; i<pIter->nPhrase; i++){
135189 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
135190 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
135192 }else{
135193 int iStart;
135194 int iEnd = 0x7FFFFFFF;
135196 for(i=0; i<pIter->nPhrase; i++){
135197 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
135198 if( pPhrase->pHead && pPhrase->iHead<iEnd ){
135199 iEnd = pPhrase->iHead;
135202 if( iEnd==0x7FFFFFFF ){
135203 return 1;
135206 pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
135207 for(i=0; i<pIter->nPhrase; i++){
135208 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
135209 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
135210 fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
135214 return 0;
135218 ** Retrieve information about the current candidate snippet of snippet
135219 ** iterator pIter.
135221 static void fts3SnippetDetails(
135222 SnippetIter *pIter, /* Snippet iterator */
135223 u64 mCovered, /* Bitmask of phrases already covered */
135224 int *piToken, /* OUT: First token of proposed snippet */
135225 int *piScore, /* OUT: "Score" for this snippet */
135226 u64 *pmCover, /* OUT: Bitmask of phrases covered */
135227 u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
135229 int iStart = pIter->iCurrent; /* First token of snippet */
135230 int iScore = 0; /* Score of this snippet */
135231 int i; /* Loop counter */
135232 u64 mCover = 0; /* Mask of phrases covered by this snippet */
135233 u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
135235 for(i=0; i<pIter->nPhrase; i++){
135236 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
135237 if( pPhrase->pTail ){
135238 char *pCsr = pPhrase->pTail;
135239 int iCsr = pPhrase->iTail;
135241 while( iCsr<(iStart+pIter->nSnippet) ){
135242 int j;
135243 u64 mPhrase = (u64)1 << i;
135244 u64 mPos = (u64)1 << (iCsr - iStart);
135245 assert( iCsr>=iStart );
135246 if( (mCover|mCovered)&mPhrase ){
135247 iScore++;
135248 }else{
135249 iScore += 1000;
135251 mCover |= mPhrase;
135253 for(j=0; j<pPhrase->nToken; j++){
135254 mHighlight |= (mPos>>j);
135257 if( 0==(*pCsr & 0x0FE) ) break;
135258 fts3GetDeltaPosition(&pCsr, &iCsr);
135263 /* Set the output variables before returning. */
135264 *piToken = iStart;
135265 *piScore = iScore;
135266 *pmCover = mCover;
135267 *pmHighlight = mHighlight;
135271 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
135272 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
135274 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
135275 SnippetIter *p = (SnippetIter *)ctx;
135276 SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
135277 char *pCsr;
135278 int rc;
135280 pPhrase->nToken = pExpr->pPhrase->nToken;
135281 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
135282 assert( rc==SQLITE_OK || pCsr==0 );
135283 if( pCsr ){
135284 int iFirst = 0;
135285 pPhrase->pList = pCsr;
135286 fts3GetDeltaPosition(&pCsr, &iFirst);
135287 assert( iFirst>=0 );
135288 pPhrase->pHead = pCsr;
135289 pPhrase->pTail = pCsr;
135290 pPhrase->iHead = iFirst;
135291 pPhrase->iTail = iFirst;
135292 }else{
135293 assert( rc!=SQLITE_OK || (
135294 pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
135298 return rc;
135302 ** Select the fragment of text consisting of nFragment contiguous tokens
135303 ** from column iCol that represent the "best" snippet. The best snippet
135304 ** is the snippet with the highest score, where scores are calculated
135305 ** by adding:
135307 ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
135309 ** (b) +1000 points for the first occurrence of each matchable phrase in
135310 ** the snippet for which the corresponding mCovered bit is not set.
135312 ** The selected snippet parameters are stored in structure *pFragment before
135313 ** returning. The score of the selected snippet is stored in *piScore
135314 ** before returning.
135316 static int fts3BestSnippet(
135317 int nSnippet, /* Desired snippet length */
135318 Fts3Cursor *pCsr, /* Cursor to create snippet for */
135319 int iCol, /* Index of column to create snippet from */
135320 u64 mCovered, /* Mask of phrases already covered */
135321 u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
135322 SnippetFragment *pFragment, /* OUT: Best snippet found */
135323 int *piScore /* OUT: Score of snippet pFragment */
135325 int rc; /* Return Code */
135326 int nList; /* Number of phrases in expression */
135327 SnippetIter sIter; /* Iterates through snippet candidates */
135328 int nByte; /* Number of bytes of space to allocate */
135329 int iBestScore = -1; /* Best snippet score found so far */
135330 int i; /* Loop counter */
135332 memset(&sIter, 0, sizeof(sIter));
135334 /* Iterate through the phrases in the expression to count them. The same
135335 ** callback makes sure the doclists are loaded for each phrase.
135337 rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
135338 if( rc!=SQLITE_OK ){
135339 return rc;
135342 /* Now that it is known how many phrases there are, allocate and zero
135343 ** the required space using malloc().
135345 nByte = sizeof(SnippetPhrase) * nList;
135346 sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
135347 if( !sIter.aPhrase ){
135348 return SQLITE_NOMEM;
135350 memset(sIter.aPhrase, 0, nByte);
135352 /* Initialize the contents of the SnippetIter object. Then iterate through
135353 ** the set of phrases in the expression to populate the aPhrase[] array.
135355 sIter.pCsr = pCsr;
135356 sIter.iCol = iCol;
135357 sIter.nSnippet = nSnippet;
135358 sIter.nPhrase = nList;
135359 sIter.iCurrent = -1;
135360 (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
135362 /* Set the *pmSeen output variable. */
135363 for(i=0; i<nList; i++){
135364 if( sIter.aPhrase[i].pHead ){
135365 *pmSeen |= (u64)1 << i;
135369 /* Loop through all candidate snippets. Store the best snippet in
135370 ** *pFragment. Store its associated 'score' in iBestScore.
135372 pFragment->iCol = iCol;
135373 while( !fts3SnippetNextCandidate(&sIter) ){
135374 int iPos;
135375 int iScore;
135376 u64 mCover;
135377 u64 mHighlight;
135378 fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
135379 assert( iScore>=0 );
135380 if( iScore>iBestScore ){
135381 pFragment->iPos = iPos;
135382 pFragment->hlmask = mHighlight;
135383 pFragment->covered = mCover;
135384 iBestScore = iScore;
135388 sqlite3_free(sIter.aPhrase);
135389 *piScore = iBestScore;
135390 return SQLITE_OK;
135395 ** Append a string to the string-buffer passed as the first argument.
135397 ** If nAppend is negative, then the length of the string zAppend is
135398 ** determined using strlen().
135400 static int fts3StringAppend(
135401 StrBuffer *pStr, /* Buffer to append to */
135402 const char *zAppend, /* Pointer to data to append to buffer */
135403 int nAppend /* Size of zAppend in bytes (or -1) */
135405 if( nAppend<0 ){
135406 nAppend = (int)strlen(zAppend);
135409 /* If there is insufficient space allocated at StrBuffer.z, use realloc()
135410 ** to grow the buffer until so that it is big enough to accomadate the
135411 ** appended data.
135413 if( pStr->n+nAppend+1>=pStr->nAlloc ){
135414 int nAlloc = pStr->nAlloc+nAppend+100;
135415 char *zNew = sqlite3_realloc(pStr->z, nAlloc);
135416 if( !zNew ){
135417 return SQLITE_NOMEM;
135419 pStr->z = zNew;
135420 pStr->nAlloc = nAlloc;
135422 assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
135424 /* Append the data to the string buffer. */
135425 memcpy(&pStr->z[pStr->n], zAppend, nAppend);
135426 pStr->n += nAppend;
135427 pStr->z[pStr->n] = '\0';
135429 return SQLITE_OK;
135433 ** The fts3BestSnippet() function often selects snippets that end with a
135434 ** query term. That is, the final term of the snippet is always a term
135435 ** that requires highlighting. For example, if 'X' is a highlighted term
135436 ** and '.' is a non-highlighted term, BestSnippet() may select:
135438 ** ........X.....X
135440 ** This function "shifts" the beginning of the snippet forward in the
135441 ** document so that there are approximately the same number of
135442 ** non-highlighted terms to the right of the final highlighted term as there
135443 ** are to the left of the first highlighted term. For example, to this:
135445 ** ....X.....X....
135447 ** This is done as part of extracting the snippet text, not when selecting
135448 ** the snippet. Snippet selection is done based on doclists only, so there
135449 ** is no way for fts3BestSnippet() to know whether or not the document
135450 ** actually contains terms that follow the final highlighted term.
135452 static int fts3SnippetShift(
135453 Fts3Table *pTab, /* FTS3 table snippet comes from */
135454 int iLangid, /* Language id to use in tokenizing */
135455 int nSnippet, /* Number of tokens desired for snippet */
135456 const char *zDoc, /* Document text to extract snippet from */
135457 int nDoc, /* Size of buffer zDoc in bytes */
135458 int *piPos, /* IN/OUT: First token of snippet */
135459 u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
135461 u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
135463 if( hlmask ){
135464 int nLeft; /* Tokens to the left of first highlight */
135465 int nRight; /* Tokens to the right of last highlight */
135466 int nDesired; /* Ideal number of tokens to shift forward */
135468 for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
135469 for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
135470 nDesired = (nLeft-nRight)/2;
135472 /* Ideally, the start of the snippet should be pushed forward in the
135473 ** document nDesired tokens. This block checks if there are actually
135474 ** nDesired tokens to the right of the snippet. If so, *piPos and
135475 ** *pHlMask are updated to shift the snippet nDesired tokens to the
135476 ** right. Otherwise, the snippet is shifted by the number of tokens
135477 ** available.
135479 if( nDesired>0 ){
135480 int nShift; /* Number of tokens to shift snippet by */
135481 int iCurrent = 0; /* Token counter */
135482 int rc; /* Return Code */
135483 sqlite3_tokenizer_module *pMod;
135484 sqlite3_tokenizer_cursor *pC;
135485 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
135487 /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
135488 ** or more tokens in zDoc/nDoc.
135490 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
135491 if( rc!=SQLITE_OK ){
135492 return rc;
135494 while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
135495 const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
135496 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
135498 pMod->xClose(pC);
135499 if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
135501 nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
135502 assert( nShift<=nDesired );
135503 if( nShift>0 ){
135504 *piPos += nShift;
135505 *pHlmask = hlmask >> nShift;
135509 return SQLITE_OK;
135513 ** Extract the snippet text for fragment pFragment from cursor pCsr and
135514 ** append it to string buffer pOut.
135516 static int fts3SnippetText(
135517 Fts3Cursor *pCsr, /* FTS3 Cursor */
135518 SnippetFragment *pFragment, /* Snippet to extract */
135519 int iFragment, /* Fragment number */
135520 int isLast, /* True for final fragment in snippet */
135521 int nSnippet, /* Number of tokens in extracted snippet */
135522 const char *zOpen, /* String inserted before highlighted term */
135523 const char *zClose, /* String inserted after highlighted term */
135524 const char *zEllipsis, /* String inserted between snippets */
135525 StrBuffer *pOut /* Write output here */
135527 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135528 int rc; /* Return code */
135529 const char *zDoc; /* Document text to extract snippet from */
135530 int nDoc; /* Size of zDoc in bytes */
135531 int iCurrent = 0; /* Current token number of document */
135532 int iEnd = 0; /* Byte offset of end of current token */
135533 int isShiftDone = 0; /* True after snippet is shifted */
135534 int iPos = pFragment->iPos; /* First token of snippet */
135535 u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
135536 int iCol = pFragment->iCol+1; /* Query column to extract text from */
135537 sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
135538 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
135540 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
135541 if( zDoc==0 ){
135542 if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
135543 return SQLITE_NOMEM;
135545 return SQLITE_OK;
135547 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
135549 /* Open a token cursor on the document. */
135550 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
135551 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
135552 if( rc!=SQLITE_OK ){
135553 return rc;
135556 while( rc==SQLITE_OK ){
135557 const char *ZDUMMY; /* Dummy argument used with tokenizer */
135558 int DUMMY1 = -1; /* Dummy argument used with tokenizer */
135559 int iBegin = 0; /* Offset in zDoc of start of token */
135560 int iFin = 0; /* Offset in zDoc of end of token */
135561 int isHighlight = 0; /* True for highlighted terms */
135563 /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
135564 ** in the FTS code the variable that the third argument to xNext points to
135565 ** is initialized to zero before the first (*but not necessarily
135566 ** subsequent*) call to xNext(). This is done for a particular application
135567 ** that needs to know whether or not the tokenizer is being used for
135568 ** snippet generation or for some other purpose.
135570 ** Extreme care is required when writing code to depend on this
135571 ** initialization. It is not a documented part of the tokenizer interface.
135572 ** If a tokenizer is used directly by any code outside of FTS, this
135573 ** convention might not be respected. */
135574 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
135575 if( rc!=SQLITE_OK ){
135576 if( rc==SQLITE_DONE ){
135577 /* Special case - the last token of the snippet is also the last token
135578 ** of the column. Append any punctuation that occurred between the end
135579 ** of the previous token and the end of the document to the output.
135580 ** Then break out of the loop. */
135581 rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
135583 break;
135585 if( iCurrent<iPos ){ continue; }
135587 if( !isShiftDone ){
135588 int n = nDoc - iBegin;
135589 rc = fts3SnippetShift(
135590 pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
135592 isShiftDone = 1;
135594 /* Now that the shift has been done, check if the initial "..." are
135595 ** required. They are required if (a) this is not the first fragment,
135596 ** or (b) this fragment does not begin at position 0 of its column.
135598 if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
135599 rc = fts3StringAppend(pOut, zEllipsis, -1);
135601 if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
135604 if( iCurrent>=(iPos+nSnippet) ){
135605 if( isLast ){
135606 rc = fts3StringAppend(pOut, zEllipsis, -1);
135608 break;
135611 /* Set isHighlight to true if this term should be highlighted. */
135612 isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
135614 if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
135615 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
135616 if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
135617 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
135619 iEnd = iFin;
135622 pMod->xClose(pC);
135623 return rc;
135628 ** This function is used to count the entries in a column-list (a
135629 ** delta-encoded list of term offsets within a single column of a single
135630 ** row). When this function is called, *ppCollist should point to the
135631 ** beginning of the first varint in the column-list (the varint that
135632 ** contains the position of the first matching term in the column data).
135633 ** Before returning, *ppCollist is set to point to the first byte after
135634 ** the last varint in the column-list (either the 0x00 signifying the end
135635 ** of the position-list, or the 0x01 that precedes the column number of
135636 ** the next column in the position-list).
135638 ** The number of elements in the column-list is returned.
135640 static int fts3ColumnlistCount(char **ppCollist){
135641 char *pEnd = *ppCollist;
135642 char c = 0;
135643 int nEntry = 0;
135645 /* A column-list is terminated by either a 0x01 or 0x00. */
135646 while( 0xFE & (*pEnd | c) ){
135647 c = *pEnd++ & 0x80;
135648 if( !c ) nEntry++;
135651 *ppCollist = pEnd;
135652 return nEntry;
135656 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
135657 ** for a single query.
135659 ** fts3ExprIterate() callback to load the 'global' elements of a
135660 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
135661 ** of the matchinfo array that are constant for all rows returned by the
135662 ** current query.
135664 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
135665 ** function populates Matchinfo.aMatchinfo[] as follows:
135667 ** for(iCol=0; iCol<nCol; iCol++){
135668 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
135669 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
135672 ** where X is the number of matches for phrase iPhrase is column iCol of all
135673 ** rows of the table. Y is the number of rows for which column iCol contains
135674 ** at least one instance of phrase iPhrase.
135676 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
135677 ** Y values are set to nDoc, where nDoc is the number of documents in the
135678 ** file system. This is done because the full-text index doclist is required
135679 ** to calculate these values properly, and the full-text index doclist is
135680 ** not available for deferred tokens.
135682 static int fts3ExprGlobalHitsCb(
135683 Fts3Expr *pExpr, /* Phrase expression node */
135684 int iPhrase, /* Phrase number (numbered from zero) */
135685 void *pCtx /* Pointer to MatchInfo structure */
135687 MatchInfo *p = (MatchInfo *)pCtx;
135688 return sqlite3Fts3EvalPhraseStats(
135689 p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
135694 ** fts3ExprIterate() callback used to collect the "local" part of the
135695 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
135696 ** array that are different for each row returned by the query.
135698 static int fts3ExprLocalHitsCb(
135699 Fts3Expr *pExpr, /* Phrase expression node */
135700 int iPhrase, /* Phrase number */
135701 void *pCtx /* Pointer to MatchInfo structure */
135703 int rc = SQLITE_OK;
135704 MatchInfo *p = (MatchInfo *)pCtx;
135705 int iStart = iPhrase * p->nCol * 3;
135706 int i;
135708 for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
135709 char *pCsr;
135710 rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
135711 if( pCsr ){
135712 p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
135713 }else{
135714 p->aMatchinfo[iStart+i*3] = 0;
135718 return rc;
135721 static int fts3MatchinfoCheck(
135722 Fts3Table *pTab,
135723 char cArg,
135724 char **pzErr
135726 if( (cArg==FTS3_MATCHINFO_NPHRASE)
135727 || (cArg==FTS3_MATCHINFO_NCOL)
135728 || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
135729 || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
135730 || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
135731 || (cArg==FTS3_MATCHINFO_LCS)
135732 || (cArg==FTS3_MATCHINFO_HITS)
135734 return SQLITE_OK;
135736 *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
135737 return SQLITE_ERROR;
135740 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
135741 int nVal; /* Number of integers output by cArg */
135743 switch( cArg ){
135744 case FTS3_MATCHINFO_NDOC:
135745 case FTS3_MATCHINFO_NPHRASE:
135746 case FTS3_MATCHINFO_NCOL:
135747 nVal = 1;
135748 break;
135750 case FTS3_MATCHINFO_AVGLENGTH:
135751 case FTS3_MATCHINFO_LENGTH:
135752 case FTS3_MATCHINFO_LCS:
135753 nVal = pInfo->nCol;
135754 break;
135756 default:
135757 assert( cArg==FTS3_MATCHINFO_HITS );
135758 nVal = pInfo->nCol * pInfo->nPhrase * 3;
135759 break;
135762 return nVal;
135765 static int fts3MatchinfoSelectDoctotal(
135766 Fts3Table *pTab,
135767 sqlite3_stmt **ppStmt,
135768 sqlite3_int64 *pnDoc,
135769 const char **paLen
135771 sqlite3_stmt *pStmt;
135772 const char *a;
135773 sqlite3_int64 nDoc;
135775 if( !*ppStmt ){
135776 int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
135777 if( rc!=SQLITE_OK ) return rc;
135779 pStmt = *ppStmt;
135780 assert( sqlite3_data_count(pStmt)==1 );
135782 a = sqlite3_column_blob(pStmt, 0);
135783 a += sqlite3Fts3GetVarint(a, &nDoc);
135784 if( nDoc==0 ) return FTS_CORRUPT_VTAB;
135785 *pnDoc = (u32)nDoc;
135787 if( paLen ) *paLen = a;
135788 return SQLITE_OK;
135792 ** An instance of the following structure is used to store state while
135793 ** iterating through a multi-column position-list corresponding to the
135794 ** hits for a single phrase on a single row in order to calculate the
135795 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
135797 typedef struct LcsIterator LcsIterator;
135798 struct LcsIterator {
135799 Fts3Expr *pExpr; /* Pointer to phrase expression */
135800 int iPosOffset; /* Tokens count up to end of this phrase */
135801 char *pRead; /* Cursor used to iterate through aDoclist */
135802 int iPos; /* Current position */
135806 ** If LcsIterator.iCol is set to the following value, the iterator has
135807 ** finished iterating through all offsets for all columns.
135809 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
135811 static int fts3MatchinfoLcsCb(
135812 Fts3Expr *pExpr, /* Phrase expression node */
135813 int iPhrase, /* Phrase number (numbered from zero) */
135814 void *pCtx /* Pointer to MatchInfo structure */
135816 LcsIterator *aIter = (LcsIterator *)pCtx;
135817 aIter[iPhrase].pExpr = pExpr;
135818 return SQLITE_OK;
135822 ** Advance the iterator passed as an argument to the next position. Return
135823 ** 1 if the iterator is at EOF or if it now points to the start of the
135824 ** position list for the next column.
135826 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
135827 char *pRead = pIter->pRead;
135828 sqlite3_int64 iRead;
135829 int rc = 0;
135831 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
135832 if( iRead==0 || iRead==1 ){
135833 pRead = 0;
135834 rc = 1;
135835 }else{
135836 pIter->iPos += (int)(iRead-2);
135839 pIter->pRead = pRead;
135840 return rc;
135844 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
135846 ** If the call is successful, the longest-common-substring lengths for each
135847 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
135848 ** array before returning. SQLITE_OK is returned in this case.
135850 ** Otherwise, if an error occurs, an SQLite error code is returned and the
135851 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
135852 ** undefined.
135854 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
135855 LcsIterator *aIter;
135856 int i;
135857 int iCol;
135858 int nToken = 0;
135860 /* Allocate and populate the array of LcsIterator objects. The array
135861 ** contains one element for each matchable phrase in the query.
135863 aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
135864 if( !aIter ) return SQLITE_NOMEM;
135865 memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
135866 (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
135868 for(i=0; i<pInfo->nPhrase; i++){
135869 LcsIterator *pIter = &aIter[i];
135870 nToken -= pIter->pExpr->pPhrase->nToken;
135871 pIter->iPosOffset = nToken;
135874 for(iCol=0; iCol<pInfo->nCol; iCol++){
135875 int nLcs = 0; /* LCS value for this column */
135876 int nLive = 0; /* Number of iterators in aIter not at EOF */
135878 for(i=0; i<pInfo->nPhrase; i++){
135879 int rc;
135880 LcsIterator *pIt = &aIter[i];
135881 rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
135882 if( rc!=SQLITE_OK ) return rc;
135883 if( pIt->pRead ){
135884 pIt->iPos = pIt->iPosOffset;
135885 fts3LcsIteratorAdvance(&aIter[i]);
135886 nLive++;
135890 while( nLive>0 ){
135891 LcsIterator *pAdv = 0; /* The iterator to advance by one position */
135892 int nThisLcs = 0; /* LCS for the current iterator positions */
135894 for(i=0; i<pInfo->nPhrase; i++){
135895 LcsIterator *pIter = &aIter[i];
135896 if( pIter->pRead==0 ){
135897 /* This iterator is already at EOF for this column. */
135898 nThisLcs = 0;
135899 }else{
135900 if( pAdv==0 || pIter->iPos<pAdv->iPos ){
135901 pAdv = pIter;
135903 if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
135904 nThisLcs++;
135905 }else{
135906 nThisLcs = 1;
135908 if( nThisLcs>nLcs ) nLcs = nThisLcs;
135911 if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
135914 pInfo->aMatchinfo[iCol] = nLcs;
135917 sqlite3_free(aIter);
135918 return SQLITE_OK;
135922 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
135923 ** be returned by the matchinfo() function. Argument zArg contains the
135924 ** format string passed as the second argument to matchinfo (or the
135925 ** default value "pcx" if no second argument was specified). The format
135926 ** string has already been validated and the pInfo->aMatchinfo[] array
135927 ** is guaranteed to be large enough for the output.
135929 ** If bGlobal is true, then populate all fields of the matchinfo() output.
135930 ** If it is false, then assume that those fields that do not change between
135931 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
135932 ** have already been populated.
135934 ** Return SQLITE_OK if successful, or an SQLite error code if an error
135935 ** occurs. If a value other than SQLITE_OK is returned, the state the
135936 ** pInfo->aMatchinfo[] buffer is left in is undefined.
135938 static int fts3MatchinfoValues(
135939 Fts3Cursor *pCsr, /* FTS3 cursor object */
135940 int bGlobal, /* True to grab the global stats */
135941 MatchInfo *pInfo, /* Matchinfo context object */
135942 const char *zArg /* Matchinfo format string */
135944 int rc = SQLITE_OK;
135945 int i;
135946 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135947 sqlite3_stmt *pSelect = 0;
135949 for(i=0; rc==SQLITE_OK && zArg[i]; i++){
135951 switch( zArg[i] ){
135952 case FTS3_MATCHINFO_NPHRASE:
135953 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
135954 break;
135956 case FTS3_MATCHINFO_NCOL:
135957 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
135958 break;
135960 case FTS3_MATCHINFO_NDOC:
135961 if( bGlobal ){
135962 sqlite3_int64 nDoc = 0;
135963 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
135964 pInfo->aMatchinfo[0] = (u32)nDoc;
135966 break;
135968 case FTS3_MATCHINFO_AVGLENGTH:
135969 if( bGlobal ){
135970 sqlite3_int64 nDoc; /* Number of rows in table */
135971 const char *a; /* Aggregate column length array */
135973 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
135974 if( rc==SQLITE_OK ){
135975 int iCol;
135976 for(iCol=0; iCol<pInfo->nCol; iCol++){
135977 u32 iVal;
135978 sqlite3_int64 nToken;
135979 a += sqlite3Fts3GetVarint(a, &nToken);
135980 iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
135981 pInfo->aMatchinfo[iCol] = iVal;
135985 break;
135987 case FTS3_MATCHINFO_LENGTH: {
135988 sqlite3_stmt *pSelectDocsize = 0;
135989 rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
135990 if( rc==SQLITE_OK ){
135991 int iCol;
135992 const char *a = sqlite3_column_blob(pSelectDocsize, 0);
135993 for(iCol=0; iCol<pInfo->nCol; iCol++){
135994 sqlite3_int64 nToken;
135995 a += sqlite3Fts3GetVarint(a, &nToken);
135996 pInfo->aMatchinfo[iCol] = (u32)nToken;
135999 sqlite3_reset(pSelectDocsize);
136000 break;
136003 case FTS3_MATCHINFO_LCS:
136004 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
136005 if( rc==SQLITE_OK ){
136006 rc = fts3MatchinfoLcs(pCsr, pInfo);
136008 break;
136010 default: {
136011 Fts3Expr *pExpr;
136012 assert( zArg[i]==FTS3_MATCHINFO_HITS );
136013 pExpr = pCsr->pExpr;
136014 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
136015 if( rc!=SQLITE_OK ) break;
136016 if( bGlobal ){
136017 if( pCsr->pDeferred ){
136018 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
136019 if( rc!=SQLITE_OK ) break;
136021 rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
136022 if( rc!=SQLITE_OK ) break;
136024 (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
136025 break;
136029 pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
136032 sqlite3_reset(pSelect);
136033 return rc;
136038 ** Populate pCsr->aMatchinfo[] with data for the current row. The
136039 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
136041 static int fts3GetMatchinfo(
136042 Fts3Cursor *pCsr, /* FTS3 Cursor object */
136043 const char *zArg /* Second argument to matchinfo() function */
136045 MatchInfo sInfo;
136046 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136047 int rc = SQLITE_OK;
136048 int bGlobal = 0; /* Collect 'global' stats as well as local */
136050 memset(&sInfo, 0, sizeof(MatchInfo));
136051 sInfo.pCursor = pCsr;
136052 sInfo.nCol = pTab->nColumn;
136054 /* If there is cached matchinfo() data, but the format string for the
136055 ** cache does not match the format string for this request, discard
136056 ** the cached data. */
136057 if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
136058 assert( pCsr->aMatchinfo );
136059 sqlite3_free(pCsr->aMatchinfo);
136060 pCsr->zMatchinfo = 0;
136061 pCsr->aMatchinfo = 0;
136064 /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
136065 ** matchinfo function has been called for this query. In this case
136066 ** allocate the array used to accumulate the matchinfo data and
136067 ** initialize those elements that are constant for every row.
136069 if( pCsr->aMatchinfo==0 ){
136070 int nMatchinfo = 0; /* Number of u32 elements in match-info */
136071 int nArg; /* Bytes in zArg */
136072 int i; /* Used to iterate through zArg */
136074 /* Determine the number of phrases in the query */
136075 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
136076 sInfo.nPhrase = pCsr->nPhrase;
136078 /* Determine the number of integers in the buffer returned by this call. */
136079 for(i=0; zArg[i]; i++){
136080 nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
136083 /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
136084 nArg = (int)strlen(zArg);
136085 pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
136086 if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
136088 pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
136089 pCsr->nMatchinfo = nMatchinfo;
136090 memcpy(pCsr->zMatchinfo, zArg, nArg+1);
136091 memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
136092 pCsr->isMatchinfoNeeded = 1;
136093 bGlobal = 1;
136096 sInfo.aMatchinfo = pCsr->aMatchinfo;
136097 sInfo.nPhrase = pCsr->nPhrase;
136098 if( pCsr->isMatchinfoNeeded ){
136099 rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
136100 pCsr->isMatchinfoNeeded = 0;
136103 return rc;
136107 ** Implementation of snippet() function.
136109 SQLITE_PRIVATE void sqlite3Fts3Snippet(
136110 sqlite3_context *pCtx, /* SQLite function call context */
136111 Fts3Cursor *pCsr, /* Cursor object */
136112 const char *zStart, /* Snippet start text - "<b>" */
136113 const char *zEnd, /* Snippet end text - "</b>" */
136114 const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
136115 int iCol, /* Extract snippet from this column */
136116 int nToken /* Approximate number of tokens in snippet */
136118 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136119 int rc = SQLITE_OK;
136120 int i;
136121 StrBuffer res = {0, 0, 0};
136123 /* The returned text includes up to four fragments of text extracted from
136124 ** the data in the current row. The first iteration of the for(...) loop
136125 ** below attempts to locate a single fragment of text nToken tokens in
136126 ** size that contains at least one instance of all phrases in the query
136127 ** expression that appear in the current row. If such a fragment of text
136128 ** cannot be found, the second iteration of the loop attempts to locate
136129 ** a pair of fragments, and so on.
136131 int nSnippet = 0; /* Number of fragments in this snippet */
136132 SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
136133 int nFToken = -1; /* Number of tokens in each fragment */
136135 if( !pCsr->pExpr ){
136136 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
136137 return;
136140 for(nSnippet=1; 1; nSnippet++){
136142 int iSnip; /* Loop counter 0..nSnippet-1 */
136143 u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
136144 u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
136146 if( nToken>=0 ){
136147 nFToken = (nToken+nSnippet-1) / nSnippet;
136148 }else{
136149 nFToken = -1 * nToken;
136152 for(iSnip=0; iSnip<nSnippet; iSnip++){
136153 int iBestScore = -1; /* Best score of columns checked so far */
136154 int iRead; /* Used to iterate through columns */
136155 SnippetFragment *pFragment = &aSnippet[iSnip];
136157 memset(pFragment, 0, sizeof(*pFragment));
136159 /* Loop through all columns of the table being considered for snippets.
136160 ** If the iCol argument to this function was negative, this means all
136161 ** columns of the FTS3 table. Otherwise, only column iCol is considered.
136163 for(iRead=0; iRead<pTab->nColumn; iRead++){
136164 SnippetFragment sF = {0, 0, 0, 0};
136165 int iS;
136166 if( iCol>=0 && iRead!=iCol ) continue;
136168 /* Find the best snippet of nFToken tokens in column iRead. */
136169 rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
136170 if( rc!=SQLITE_OK ){
136171 goto snippet_out;
136173 if( iS>iBestScore ){
136174 *pFragment = sF;
136175 iBestScore = iS;
136179 mCovered |= pFragment->covered;
136182 /* If all query phrases seen by fts3BestSnippet() are present in at least
136183 ** one of the nSnippet snippet fragments, break out of the loop.
136185 assert( (mCovered&mSeen)==mCovered );
136186 if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
136189 assert( nFToken>0 );
136191 for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
136192 rc = fts3SnippetText(pCsr, &aSnippet[i],
136193 i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
136197 snippet_out:
136198 sqlite3Fts3SegmentsClose(pTab);
136199 if( rc!=SQLITE_OK ){
136200 sqlite3_result_error_code(pCtx, rc);
136201 sqlite3_free(res.z);
136202 }else{
136203 sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
136208 typedef struct TermOffset TermOffset;
136209 typedef struct TermOffsetCtx TermOffsetCtx;
136211 struct TermOffset {
136212 char *pList; /* Position-list */
136213 int iPos; /* Position just read from pList */
136214 int iOff; /* Offset of this term from read positions */
136217 struct TermOffsetCtx {
136218 Fts3Cursor *pCsr;
136219 int iCol; /* Column of table to populate aTerm for */
136220 int iTerm;
136221 sqlite3_int64 iDocid;
136222 TermOffset *aTerm;
136226 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
136228 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
136229 TermOffsetCtx *p = (TermOffsetCtx *)ctx;
136230 int nTerm; /* Number of tokens in phrase */
136231 int iTerm; /* For looping through nTerm phrase terms */
136232 char *pList; /* Pointer to position list for phrase */
136233 int iPos = 0; /* First position in position-list */
136234 int rc;
136236 UNUSED_PARAMETER(iPhrase);
136237 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
136238 nTerm = pExpr->pPhrase->nToken;
136239 if( pList ){
136240 fts3GetDeltaPosition(&pList, &iPos);
136241 assert( iPos>=0 );
136244 for(iTerm=0; iTerm<nTerm; iTerm++){
136245 TermOffset *pT = &p->aTerm[p->iTerm++];
136246 pT->iOff = nTerm-iTerm-1;
136247 pT->pList = pList;
136248 pT->iPos = iPos;
136251 return rc;
136255 ** Implementation of offsets() function.
136257 SQLITE_PRIVATE void sqlite3Fts3Offsets(
136258 sqlite3_context *pCtx, /* SQLite function call context */
136259 Fts3Cursor *pCsr /* Cursor object */
136261 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136262 sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
136263 int rc; /* Return Code */
136264 int nToken; /* Number of tokens in query */
136265 int iCol; /* Column currently being processed */
136266 StrBuffer res = {0, 0, 0}; /* Result string */
136267 TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
136269 if( !pCsr->pExpr ){
136270 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
136271 return;
136274 memset(&sCtx, 0, sizeof(sCtx));
136275 assert( pCsr->isRequireSeek==0 );
136277 /* Count the number of terms in the query */
136278 rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
136279 if( rc!=SQLITE_OK ) goto offsets_out;
136281 /* Allocate the array of TermOffset iterators. */
136282 sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
136283 if( 0==sCtx.aTerm ){
136284 rc = SQLITE_NOMEM;
136285 goto offsets_out;
136287 sCtx.iDocid = pCsr->iPrevId;
136288 sCtx.pCsr = pCsr;
136290 /* Loop through the table columns, appending offset information to
136291 ** string-buffer res for each column.
136293 for(iCol=0; iCol<pTab->nColumn; iCol++){
136294 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
136295 const char *ZDUMMY; /* Dummy argument used with xNext() */
136296 int NDUMMY = 0; /* Dummy argument used with xNext() */
136297 int iStart = 0;
136298 int iEnd = 0;
136299 int iCurrent = 0;
136300 const char *zDoc;
136301 int nDoc;
136303 /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
136304 ** no way that this operation can fail, so the return code from
136305 ** fts3ExprIterate() can be discarded.
136307 sCtx.iCol = iCol;
136308 sCtx.iTerm = 0;
136309 (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
136311 /* Retreive the text stored in column iCol. If an SQL NULL is stored
136312 ** in column iCol, jump immediately to the next iteration of the loop.
136313 ** If an OOM occurs while retrieving the data (this can happen if SQLite
136314 ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
136315 ** to the caller.
136317 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
136318 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
136319 if( zDoc==0 ){
136320 if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
136321 continue;
136323 rc = SQLITE_NOMEM;
136324 goto offsets_out;
136327 /* Initialize a tokenizer iterator to iterate through column iCol. */
136328 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
136329 zDoc, nDoc, &pC
136331 if( rc!=SQLITE_OK ) goto offsets_out;
136333 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
136334 while( rc==SQLITE_OK ){
136335 int i; /* Used to loop through terms */
136336 int iMinPos = 0x7FFFFFFF; /* Position of next token */
136337 TermOffset *pTerm = 0; /* TermOffset associated with next token */
136339 for(i=0; i<nToken; i++){
136340 TermOffset *pT = &sCtx.aTerm[i];
136341 if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
136342 iMinPos = pT->iPos-pT->iOff;
136343 pTerm = pT;
136347 if( !pTerm ){
136348 /* All offsets for this column have been gathered. */
136349 rc = SQLITE_DONE;
136350 }else{
136351 assert( iCurrent<=iMinPos );
136352 if( 0==(0xFE&*pTerm->pList) ){
136353 pTerm->pList = 0;
136354 }else{
136355 fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
136357 while( rc==SQLITE_OK && iCurrent<iMinPos ){
136358 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
136360 if( rc==SQLITE_OK ){
136361 char aBuffer[64];
136362 sqlite3_snprintf(sizeof(aBuffer), aBuffer,
136363 "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
136365 rc = fts3StringAppend(&res, aBuffer, -1);
136366 }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
136367 rc = FTS_CORRUPT_VTAB;
136371 if( rc==SQLITE_DONE ){
136372 rc = SQLITE_OK;
136375 pMod->xClose(pC);
136376 if( rc!=SQLITE_OK ) goto offsets_out;
136379 offsets_out:
136380 sqlite3_free(sCtx.aTerm);
136381 assert( rc!=SQLITE_DONE );
136382 sqlite3Fts3SegmentsClose(pTab);
136383 if( rc!=SQLITE_OK ){
136384 sqlite3_result_error_code(pCtx, rc);
136385 sqlite3_free(res.z);
136386 }else{
136387 sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
136389 return;
136393 ** Implementation of matchinfo() function.
136395 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
136396 sqlite3_context *pContext, /* Function call context */
136397 Fts3Cursor *pCsr, /* FTS3 table cursor */
136398 const char *zArg /* Second arg to matchinfo() function */
136400 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136401 int rc;
136402 int i;
136403 const char *zFormat;
136405 if( zArg ){
136406 for(i=0; zArg[i]; i++){
136407 char *zErr = 0;
136408 if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
136409 sqlite3_result_error(pContext, zErr, -1);
136410 sqlite3_free(zErr);
136411 return;
136414 zFormat = zArg;
136415 }else{
136416 zFormat = FTS3_MATCHINFO_DEFAULT;
136419 if( !pCsr->pExpr ){
136420 sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
136421 return;
136424 /* Retrieve matchinfo() data. */
136425 rc = fts3GetMatchinfo(pCsr, zFormat);
136426 sqlite3Fts3SegmentsClose(pTab);
136428 if( rc!=SQLITE_OK ){
136429 sqlite3_result_error_code(pContext, rc);
136430 }else{
136431 int n = pCsr->nMatchinfo * sizeof(u32);
136432 sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
136436 #endif
136438 /************** End of fts3_snippet.c ****************************************/
136439 /************** Begin file fts3_unicode.c ************************************/
136441 ** 2012 May 24
136443 ** The author disclaims copyright to this source code. In place of
136444 ** a legal notice, here is a blessing:
136446 ** May you do good and not evil.
136447 ** May you find forgiveness for yourself and forgive others.
136448 ** May you share freely, never taking more than you give.
136450 ******************************************************************************
136452 ** Implementation of the "unicode" full-text-search tokenizer.
136455 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
136457 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
136459 /* #include <assert.h> */
136460 /* #include <stdlib.h> */
136461 /* #include <stdio.h> */
136462 /* #include <string.h> */
136466 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
136467 ** from the sqlite3 source file utf.c. If this file is compiled as part
136468 ** of the amalgamation, they are not required.
136470 #ifndef SQLITE_AMALGAMATION
136472 static const unsigned char sqlite3Utf8Trans1[] = {
136473 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
136474 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
136475 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
136476 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
136477 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
136478 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
136479 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
136480 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
136483 #define READ_UTF8(zIn, zTerm, c) \
136484 c = *(zIn++); \
136485 if( c>=0xc0 ){ \
136486 c = sqlite3Utf8Trans1[c-0xc0]; \
136487 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
136488 c = (c<<6) + (0x3f & *(zIn++)); \
136490 if( c<0x80 \
136491 || (c&0xFFFFF800)==0xD800 \
136492 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
136495 #define WRITE_UTF8(zOut, c) { \
136496 if( c<0x00080 ){ \
136497 *zOut++ = (u8)(c&0xFF); \
136499 else if( c<0x00800 ){ \
136500 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
136501 *zOut++ = 0x80 + (u8)(c & 0x3F); \
136503 else if( c<0x10000 ){ \
136504 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
136505 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
136506 *zOut++ = 0x80 + (u8)(c & 0x3F); \
136507 }else{ \
136508 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
136509 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
136510 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
136511 *zOut++ = 0x80 + (u8)(c & 0x3F); \
136515 #endif /* ifndef SQLITE_AMALGAMATION */
136517 typedef struct unicode_tokenizer unicode_tokenizer;
136518 typedef struct unicode_cursor unicode_cursor;
136520 struct unicode_tokenizer {
136521 sqlite3_tokenizer base;
136522 int bRemoveDiacritic;
136523 int nException;
136524 int *aiException;
136527 struct unicode_cursor {
136528 sqlite3_tokenizer_cursor base;
136529 const unsigned char *aInput; /* Input text being tokenized */
136530 int nInput; /* Size of aInput[] in bytes */
136531 int iOff; /* Current offset within aInput[] */
136532 int iToken; /* Index of next token to be returned */
136533 char *zToken; /* storage for current token */
136534 int nAlloc; /* space allocated at zToken */
136539 ** Destroy a tokenizer allocated by unicodeCreate().
136541 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
136542 if( pTokenizer ){
136543 unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
136544 sqlite3_free(p->aiException);
136545 sqlite3_free(p);
136547 return SQLITE_OK;
136551 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
136552 ** statement has specified that the tokenizer for this table shall consider
136553 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
136554 ** token characters (if bAlnum==1).
136556 ** For each codepoint in the zIn/nIn string, this function checks if the
136557 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
136558 ** If so, no action is taken. Otherwise, the codepoint is added to the
136559 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
136560 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
136561 ** codepoints in the aiException[] array.
136563 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
136564 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
136565 ** It is not possible to change the behavior of the tokenizer with respect
136566 ** to these codepoints.
136568 static int unicodeAddExceptions(
136569 unicode_tokenizer *p, /* Tokenizer to add exceptions to */
136570 int bAlnum, /* Replace Isalnum() return value with this */
136571 const char *zIn, /* Array of characters to make exceptions */
136572 int nIn /* Length of z in bytes */
136574 const unsigned char *z = (const unsigned char *)zIn;
136575 const unsigned char *zTerm = &z[nIn];
136576 int iCode;
136577 int nEntry = 0;
136579 assert( bAlnum==0 || bAlnum==1 );
136581 while( z<zTerm ){
136582 READ_UTF8(z, zTerm, iCode);
136583 assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
136584 if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
136585 && sqlite3FtsUnicodeIsdiacritic(iCode)==0
136587 nEntry++;
136591 if( nEntry ){
136592 int *aNew; /* New aiException[] array */
136593 int nNew; /* Number of valid entries in array aNew[] */
136595 aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
136596 if( aNew==0 ) return SQLITE_NOMEM;
136597 nNew = p->nException;
136599 z = (const unsigned char *)zIn;
136600 while( z<zTerm ){
136601 READ_UTF8(z, zTerm, iCode);
136602 if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
136603 && sqlite3FtsUnicodeIsdiacritic(iCode)==0
136605 int i, j;
136606 for(i=0; i<nNew && aNew[i]<iCode; i++);
136607 for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
136608 aNew[i] = iCode;
136609 nNew++;
136612 p->aiException = aNew;
136613 p->nException = nNew;
136616 return SQLITE_OK;
136620 ** Return true if the p->aiException[] array contains the value iCode.
136622 static int unicodeIsException(unicode_tokenizer *p, int iCode){
136623 if( p->nException>0 ){
136624 int *a = p->aiException;
136625 int iLo = 0;
136626 int iHi = p->nException-1;
136628 while( iHi>=iLo ){
136629 int iTest = (iHi + iLo) / 2;
136630 if( iCode==a[iTest] ){
136631 return 1;
136632 }else if( iCode>a[iTest] ){
136633 iLo = iTest+1;
136634 }else{
136635 iHi = iTest-1;
136640 return 0;
136644 ** Return true if, for the purposes of tokenization, codepoint iCode is
136645 ** considered a token character (not a separator).
136647 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
136648 assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
136649 return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
136653 ** Create a new tokenizer instance.
136655 static int unicodeCreate(
136656 int nArg, /* Size of array argv[] */
136657 const char * const *azArg, /* Tokenizer creation arguments */
136658 sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
136660 unicode_tokenizer *pNew; /* New tokenizer object */
136661 int i;
136662 int rc = SQLITE_OK;
136664 pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
136665 if( pNew==NULL ) return SQLITE_NOMEM;
136666 memset(pNew, 0, sizeof(unicode_tokenizer));
136667 pNew->bRemoveDiacritic = 1;
136669 for(i=0; rc==SQLITE_OK && i<nArg; i++){
136670 const char *z = azArg[i];
136671 int n = strlen(z);
136673 if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
136674 pNew->bRemoveDiacritic = 1;
136676 else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
136677 pNew->bRemoveDiacritic = 0;
136679 else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
136680 rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
136682 else if( n>=11 && memcmp("separators=", z, 11)==0 ){
136683 rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
136685 else{
136686 /* Unrecognized argument */
136687 rc = SQLITE_ERROR;
136691 if( rc!=SQLITE_OK ){
136692 unicodeDestroy((sqlite3_tokenizer *)pNew);
136693 pNew = 0;
136695 *pp = (sqlite3_tokenizer *)pNew;
136696 return rc;
136700 ** Prepare to begin tokenizing a particular string. The input
136701 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
136702 ** used to incrementally tokenize this string is returned in
136703 ** *ppCursor.
136705 static int unicodeOpen(
136706 sqlite3_tokenizer *p, /* The tokenizer */
136707 const char *aInput, /* Input string */
136708 int nInput, /* Size of string aInput in bytes */
136709 sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
136711 unicode_cursor *pCsr;
136713 pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
136714 if( pCsr==0 ){
136715 return SQLITE_NOMEM;
136717 memset(pCsr, 0, sizeof(unicode_cursor));
136719 pCsr->aInput = (const unsigned char *)aInput;
136720 if( aInput==0 ){
136721 pCsr->nInput = 0;
136722 }else if( nInput<0 ){
136723 pCsr->nInput = (int)strlen(aInput);
136724 }else{
136725 pCsr->nInput = nInput;
136728 *pp = &pCsr->base;
136729 UNUSED_PARAMETER(p);
136730 return SQLITE_OK;
136734 ** Close a tokenization cursor previously opened by a call to
136735 ** simpleOpen() above.
136737 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
136738 unicode_cursor *pCsr = (unicode_cursor *) pCursor;
136739 sqlite3_free(pCsr->zToken);
136740 sqlite3_free(pCsr);
136741 return SQLITE_OK;
136745 ** Extract the next token from a tokenization cursor. The cursor must
136746 ** have been opened by a prior call to simpleOpen().
136748 static int unicodeNext(
136749 sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
136750 const char **paToken, /* OUT: Token text */
136751 int *pnToken, /* OUT: Number of bytes at *paToken */
136752 int *piStart, /* OUT: Starting offset of token */
136753 int *piEnd, /* OUT: Ending offset of token */
136754 int *piPos /* OUT: Position integer of token */
136756 unicode_cursor *pCsr = (unicode_cursor *)pC;
136757 unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
136758 int iCode;
136759 char *zOut;
136760 const unsigned char *z = &pCsr->aInput[pCsr->iOff];
136761 const unsigned char *zStart = z;
136762 const unsigned char *zEnd;
136763 const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
136765 /* Scan past any delimiter characters before the start of the next token.
136766 ** Return SQLITE_DONE early if this takes us all the way to the end of
136767 ** the input. */
136768 while( z<zTerm ){
136769 READ_UTF8(z, zTerm, iCode);
136770 if( unicodeIsAlnum(p, iCode) ) break;
136771 zStart = z;
136773 if( zStart>=zTerm ) return SQLITE_DONE;
136775 zOut = pCsr->zToken;
136777 int iOut;
136779 /* Grow the output buffer if required. */
136780 if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
136781 char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
136782 if( !zNew ) return SQLITE_NOMEM;
136783 zOut = &zNew[zOut - pCsr->zToken];
136784 pCsr->zToken = zNew;
136785 pCsr->nAlloc += 64;
136788 /* Write the folded case of the last character read to the output */
136789 zEnd = z;
136790 iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
136791 if( iOut ){
136792 WRITE_UTF8(zOut, iOut);
136795 /* If the cursor is not at EOF, read the next character */
136796 if( z>=zTerm ) break;
136797 READ_UTF8(z, zTerm, iCode);
136798 }while( unicodeIsAlnum(p, iCode)
136799 || sqlite3FtsUnicodeIsdiacritic(iCode)
136802 /* Set the output variables and return. */
136803 pCsr->iOff = (z - pCsr->aInput);
136804 *paToken = pCsr->zToken;
136805 *pnToken = zOut - pCsr->zToken;
136806 *piStart = (zStart - pCsr->aInput);
136807 *piEnd = (zEnd - pCsr->aInput);
136808 *piPos = pCsr->iToken++;
136809 return SQLITE_OK;
136813 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
136814 ** structure for the unicode tokenizer.
136816 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
136817 static const sqlite3_tokenizer_module module = {
136819 unicodeCreate,
136820 unicodeDestroy,
136821 unicodeOpen,
136822 unicodeClose,
136823 unicodeNext,
136826 *ppModule = &module;
136829 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
136830 #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
136832 /************** End of fts3_unicode.c ****************************************/
136833 /************** Begin file fts3_unicode2.c ***********************************/
136835 ** 2012 May 25
136837 ** The author disclaims copyright to this source code. In place of
136838 ** a legal notice, here is a blessing:
136840 ** May you do good and not evil.
136841 ** May you find forgiveness for yourself and forgive others.
136842 ** May you share freely, never taking more than you give.
136844 ******************************************************************************
136848 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
136851 #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
136852 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
136854 /* #include <assert.h> */
136857 ** Return true if the argument corresponds to a unicode codepoint
136858 ** classified as either a letter or a number. Otherwise false.
136860 ** The results are undefined if the value passed to this function
136861 ** is less than zero.
136863 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
136864 /* Each unsigned integer in the following array corresponds to a contiguous
136865 ** range of unicode codepoints that are not either letters or numbers (i.e.
136866 ** codepoints for which this function should return 0).
136868 ** The most significant 22 bits in each 32-bit value contain the first
136869 ** codepoint in the range. The least significant 10 bits are used to store
136870 ** the size of the range (always at least 1). In other words, the value
136871 ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
136872 ** C. It is not possible to represent a range larger than 1023 codepoints
136873 ** using this format.
136875 const static unsigned int aEntry[] = {
136876 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
136877 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
136878 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
136879 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
136880 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
136881 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
136882 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
136883 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
136884 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
136885 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
136886 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
136887 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
136888 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
136889 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
136890 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
136891 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
136892 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
136893 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
136894 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
136895 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
136896 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
136897 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
136898 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
136899 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
136900 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
136901 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
136902 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
136903 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
136904 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
136905 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
136906 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
136907 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
136908 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
136909 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
136910 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
136911 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
136912 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
136913 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
136914 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
136915 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
136916 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
136917 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
136918 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
136919 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
136920 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
136921 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
136922 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
136923 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
136924 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
136925 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
136926 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
136927 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
136928 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
136929 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
136930 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
136931 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
136932 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
136933 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
136934 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
136935 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
136936 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
136937 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
136938 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
136939 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
136940 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
136941 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
136942 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
136943 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
136944 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
136945 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
136946 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
136947 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
136948 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
136949 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
136950 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
136951 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
136952 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
136953 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
136954 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
136955 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
136956 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
136957 0x380400F0,
136959 static const unsigned int aAscii[4] = {
136960 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
136963 if( c<128 ){
136964 return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
136965 }else if( c<(1<<22) ){
136966 unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
136967 int iRes;
136968 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
136969 int iLo = 0;
136970 while( iHi>=iLo ){
136971 int iTest = (iHi + iLo) / 2;
136972 if( key >= aEntry[iTest] ){
136973 iRes = iTest;
136974 iLo = iTest+1;
136975 }else{
136976 iHi = iTest-1;
136979 assert( aEntry[0]<key );
136980 assert( key>=aEntry[iRes] );
136981 return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
136983 return 1;
136988 ** If the argument is a codepoint corresponding to a lowercase letter
136989 ** in the ASCII range with a diacritic added, return the codepoint
136990 ** of the ASCII letter only. For example, if passed 235 - "LATIN
136991 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
136992 ** E"). The resuls of passing a codepoint that corresponds to an
136993 ** uppercase letter are undefined.
136995 static int remove_diacritic(int c){
136996 unsigned short aDia[] = {
136997 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
136998 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
136999 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
137000 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
137001 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
137002 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
137003 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
137004 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
137005 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
137006 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
137007 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
137008 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
137009 62924, 63050, 63082, 63274, 63390,
137011 char aChar[] = {
137012 '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
137013 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
137014 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
137015 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
137016 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
137017 '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
137018 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
137019 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
137020 'e', 'i', 'o', 'u', 'y',
137023 unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
137024 int iRes = 0;
137025 int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
137026 int iLo = 0;
137027 while( iHi>=iLo ){
137028 int iTest = (iHi + iLo) / 2;
137029 if( key >= aDia[iTest] ){
137030 iRes = iTest;
137031 iLo = iTest+1;
137032 }else{
137033 iHi = iTest-1;
137036 assert( key>=aDia[iRes] );
137037 return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
137042 ** Return true if the argument interpreted as a unicode codepoint
137043 ** is a diacritical modifier character.
137045 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
137046 unsigned int mask0 = 0x08029FDF;
137047 unsigned int mask1 = 0x000361F8;
137048 if( c<768 || c>817 ) return 0;
137049 return (c < 768+32) ?
137050 (mask0 & (1 << (c-768))) :
137051 (mask1 & (1 << (c-768-32)));
137056 ** Interpret the argument as a unicode codepoint. If the codepoint
137057 ** is an upper case character that has a lower case equivalent,
137058 ** return the codepoint corresponding to the lower case version.
137059 ** Otherwise, return a copy of the argument.
137061 ** The results are undefined if the value passed to this function
137062 ** is less than zero.
137064 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
137065 /* Each entry in the following array defines a rule for folding a range
137066 ** of codepoints to lower case. The rule applies to a range of nRange
137067 ** codepoints starting at codepoint iCode.
137069 ** If the least significant bit in flags is clear, then the rule applies
137070 ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
137071 ** need to be folded). Or, if it is set, then the rule only applies to
137072 ** every second codepoint in the range, starting with codepoint C.
137074 ** The 7 most significant bits in flags are an index into the aiOff[]
137075 ** array. If a specific codepoint C does require folding, then its lower
137076 ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
137078 ** The contents of this array are generated by parsing the CaseFolding.txt
137079 ** file distributed as part of the "Unicode Character Database". See
137080 ** http://www.unicode.org for details.
137082 static const struct TableEntry {
137083 unsigned short iCode;
137084 unsigned char flags;
137085 unsigned char nRange;
137086 } aEntry[] = {
137087 {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
137088 {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
137089 {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
137090 {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
137091 {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
137092 {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
137093 {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
137094 {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
137095 {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
137096 {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
137097 {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
137098 {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
137099 {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
137100 {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
137101 {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
137102 {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
137103 {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
137104 {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
137105 {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
137106 {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
137107 {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
137108 {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
137109 {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
137110 {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
137111 {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
137112 {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
137113 {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
137114 {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
137115 {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
137116 {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
137117 {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
137118 {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
137119 {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
137120 {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
137121 {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
137122 {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
137123 {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
137124 {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
137125 {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
137126 {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
137127 {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
137128 {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
137129 {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
137130 {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
137131 {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
137132 {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
137133 {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
137134 {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
137135 {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
137136 {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
137137 {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
137138 {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
137139 {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
137140 {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
137141 {65313, 14, 26},
137143 static const unsigned short aiOff[] = {
137144 1, 2, 8, 15, 16, 26, 28, 32,
137145 37, 38, 40, 48, 63, 64, 69, 71,
137146 79, 80, 116, 202, 203, 205, 206, 207,
137147 209, 210, 211, 213, 214, 217, 218, 219,
137148 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
137149 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
137150 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
137151 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
137152 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
137153 65514, 65521, 65527, 65528, 65529,
137156 int ret = c;
137158 assert( c>=0 );
137159 assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
137161 if( c<128 ){
137162 if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
137163 }else if( c<65536 ){
137164 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
137165 int iLo = 0;
137166 int iRes = -1;
137168 while( iHi>=iLo ){
137169 int iTest = (iHi + iLo) / 2;
137170 int cmp = (c - aEntry[iTest].iCode);
137171 if( cmp>=0 ){
137172 iRes = iTest;
137173 iLo = iTest+1;
137174 }else{
137175 iHi = iTest-1;
137178 assert( iRes<0 || c>=aEntry[iRes].iCode );
137180 if( iRes>=0 ){
137181 const struct TableEntry *p = &aEntry[iRes];
137182 if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
137183 ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
137184 assert( ret>0 );
137188 if( bRemoveDiacritic ) ret = remove_diacritic(ret);
137191 else if( c>=66560 && c<66600 ){
137192 ret = c + 40;
137195 return ret;
137197 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
137198 #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
137200 /************** End of fts3_unicode2.c ***************************************/
137201 /************** Begin file rtree.c *******************************************/
137203 ** 2001 September 15
137205 ** The author disclaims copyright to this source code. In place of
137206 ** a legal notice, here is a blessing:
137208 ** May you do good and not evil.
137209 ** May you find forgiveness for yourself and forgive others.
137210 ** May you share freely, never taking more than you give.
137212 *************************************************************************
137213 ** This file contains code for implementations of the r-tree and r*-tree
137214 ** algorithms packaged as an SQLite virtual table module.
137218 ** Database Format of R-Tree Tables
137219 ** --------------------------------
137221 ** The data structure for a single virtual r-tree table is stored in three
137222 ** native SQLite tables declared as follows. In each case, the '%' character
137223 ** in the table name is replaced with the user-supplied name of the r-tree
137224 ** table.
137226 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
137227 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
137228 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
137230 ** The data for each node of the r-tree structure is stored in the %_node
137231 ** table. For each node that is not the root node of the r-tree, there is
137232 ** an entry in the %_parent table associating the node with its parent.
137233 ** And for each row of data in the table, there is an entry in the %_rowid
137234 ** table that maps from the entries rowid to the id of the node that it
137235 ** is stored on.
137237 ** The root node of an r-tree always exists, even if the r-tree table is
137238 ** empty. The nodeno of the root node is always 1. All other nodes in the
137239 ** table must be the same size as the root node. The content of each node
137240 ** is formatted as follows:
137242 ** 1. If the node is the root node (node 1), then the first 2 bytes
137243 ** of the node contain the tree depth as a big-endian integer.
137244 ** For non-root nodes, the first 2 bytes are left unused.
137246 ** 2. The next 2 bytes contain the number of entries currently
137247 ** stored in the node.
137249 ** 3. The remainder of the node contains the node entries. Each entry
137250 ** consists of a single 8-byte integer followed by an even number
137251 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
137252 ** of a record. For internal nodes it is the node number of a
137253 ** child page.
137256 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
137259 ** This file contains an implementation of a couple of different variants
137260 ** of the r-tree algorithm. See the README file for further details. The
137261 ** same data-structure is used for all, but the algorithms for insert and
137262 ** delete operations vary. The variants used are selected at compile time
137263 ** by defining the following symbols:
137266 /* Either, both or none of the following may be set to activate
137267 ** r*tree variant algorithms.
137269 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
137270 #define VARIANT_RSTARTREE_REINSERT 1
137273 ** Exactly one of the following must be set to 1.
137275 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
137276 #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
137277 #define VARIANT_RSTARTREE_SPLIT 1
137279 #define VARIANT_GUTTMAN_SPLIT \
137280 (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
137282 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
137283 #define PickNext QuadraticPickNext
137284 #define PickSeeds QuadraticPickSeeds
137285 #define AssignCells splitNodeGuttman
137286 #endif
137287 #if VARIANT_GUTTMAN_LINEAR_SPLIT
137288 #define PickNext LinearPickNext
137289 #define PickSeeds LinearPickSeeds
137290 #define AssignCells splitNodeGuttman
137291 #endif
137292 #if VARIANT_RSTARTREE_SPLIT
137293 #define AssignCells splitNodeStartree
137294 #endif
137296 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
137297 # define NDEBUG 1
137298 #endif
137300 #ifndef SQLITE_CORE
137301 SQLITE_EXTENSION_INIT1
137302 #else
137303 #endif
137305 /* #include <string.h> */
137306 /* #include <assert.h> */
137308 #ifndef SQLITE_AMALGAMATION
137309 #include "sqlite3rtree.h"
137310 typedef sqlite3_int64 i64;
137311 typedef unsigned char u8;
137312 typedef unsigned int u32;
137313 #endif
137315 /* The following macro is used to suppress compiler warnings.
137317 #ifndef UNUSED_PARAMETER
137318 # define UNUSED_PARAMETER(x) (void)(x)
137319 #endif
137321 typedef struct Rtree Rtree;
137322 typedef struct RtreeCursor RtreeCursor;
137323 typedef struct RtreeNode RtreeNode;
137324 typedef struct RtreeCell RtreeCell;
137325 typedef struct RtreeConstraint RtreeConstraint;
137326 typedef struct RtreeMatchArg RtreeMatchArg;
137327 typedef struct RtreeGeomCallback RtreeGeomCallback;
137328 typedef union RtreeCoord RtreeCoord;
137330 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
137331 #define RTREE_MAX_DIMENSIONS 5
137333 /* Size of hash table Rtree.aHash. This hash table is not expected to
137334 ** ever contain very many entries, so a fixed number of buckets is
137335 ** used.
137337 #define HASHSIZE 128
137340 ** An rtree virtual-table object.
137342 struct Rtree {
137343 sqlite3_vtab base;
137344 sqlite3 *db; /* Host database connection */
137345 int iNodeSize; /* Size in bytes of each node in the node table */
137346 int nDim; /* Number of dimensions */
137347 int nBytesPerCell; /* Bytes consumed per cell */
137348 int iDepth; /* Current depth of the r-tree structure */
137349 char *zDb; /* Name of database containing r-tree table */
137350 char *zName; /* Name of r-tree table */
137351 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
137352 int nBusy; /* Current number of users of this structure */
137354 /* List of nodes removed during a CondenseTree operation. List is
137355 ** linked together via the pointer normally used for hash chains -
137356 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
137357 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
137359 RtreeNode *pDeleted;
137360 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
137362 /* Statements to read/write/delete a record from xxx_node */
137363 sqlite3_stmt *pReadNode;
137364 sqlite3_stmt *pWriteNode;
137365 sqlite3_stmt *pDeleteNode;
137367 /* Statements to read/write/delete a record from xxx_rowid */
137368 sqlite3_stmt *pReadRowid;
137369 sqlite3_stmt *pWriteRowid;
137370 sqlite3_stmt *pDeleteRowid;
137372 /* Statements to read/write/delete a record from xxx_parent */
137373 sqlite3_stmt *pReadParent;
137374 sqlite3_stmt *pWriteParent;
137375 sqlite3_stmt *pDeleteParent;
137377 int eCoordType;
137380 /* Possible values for eCoordType: */
137381 #define RTREE_COORD_REAL32 0
137382 #define RTREE_COORD_INT32 1
137385 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
137386 ** only deal with integer coordinates. No floating point operations
137387 ** will be done.
137389 #ifdef SQLITE_RTREE_INT_ONLY
137390 typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
137391 typedef int RtreeValue; /* Low accuracy coordinate */
137392 #else
137393 typedef double RtreeDValue; /* High accuracy coordinate */
137394 typedef float RtreeValue; /* Low accuracy coordinate */
137395 #endif
137398 ** The minimum number of cells allowed for a node is a third of the
137399 ** maximum. In Gutman's notation:
137401 ** m = M/3
137403 ** If an R*-tree "Reinsert" operation is required, the same number of
137404 ** cells are removed from the overfull node and reinserted into the tree.
137406 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
137407 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
137408 #define RTREE_MAXCELLS 51
137411 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
137412 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
137413 ** Therefore all non-root nodes must contain at least 3 entries. Since
137414 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
137415 ** 40 or less.
137417 #define RTREE_MAX_DEPTH 40
137420 ** An rtree cursor object.
137422 struct RtreeCursor {
137423 sqlite3_vtab_cursor base;
137424 RtreeNode *pNode; /* Node cursor is currently pointing at */
137425 int iCell; /* Index of current cell in pNode */
137426 int iStrategy; /* Copy of idxNum search parameter */
137427 int nConstraint; /* Number of entries in aConstraint */
137428 RtreeConstraint *aConstraint; /* Search constraints. */
137431 union RtreeCoord {
137432 RtreeValue f;
137433 int i;
137437 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
137438 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
137439 ** variable pRtree points to the Rtree structure associated with the
137440 ** RtreeCoord.
137442 #ifdef SQLITE_RTREE_INT_ONLY
137443 # define DCOORD(coord) ((RtreeDValue)coord.i)
137444 #else
137445 # define DCOORD(coord) ( \
137446 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
137447 ((double)coord.f) : \
137448 ((double)coord.i) \
137450 #endif
137453 ** A search constraint.
137455 struct RtreeConstraint {
137456 int iCoord; /* Index of constrained coordinate */
137457 int op; /* Constraining operation */
137458 RtreeDValue rValue; /* Constraint value. */
137459 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
137460 sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
137463 /* Possible values for RtreeConstraint.op */
137464 #define RTREE_EQ 0x41
137465 #define RTREE_LE 0x42
137466 #define RTREE_LT 0x43
137467 #define RTREE_GE 0x44
137468 #define RTREE_GT 0x45
137469 #define RTREE_MATCH 0x46
137472 ** An rtree structure node.
137474 struct RtreeNode {
137475 RtreeNode *pParent; /* Parent node */
137476 i64 iNode;
137477 int nRef;
137478 int isDirty;
137479 u8 *zData;
137480 RtreeNode *pNext; /* Next node in this hash chain */
137482 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
137485 ** Structure to store a deserialized rtree record.
137487 struct RtreeCell {
137488 i64 iRowid;
137489 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
137494 ** Value for the first field of every RtreeMatchArg object. The MATCH
137495 ** operator tests that the first field of a blob operand matches this
137496 ** value to avoid operating on invalid blobs (which could cause a segfault).
137498 #define RTREE_GEOMETRY_MAGIC 0x891245AB
137501 ** An instance of this structure must be supplied as a blob argument to
137502 ** the right-hand-side of an SQL MATCH operator used to constrain an
137503 ** r-tree query.
137505 struct RtreeMatchArg {
137506 u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
137507 int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
137508 void *pContext;
137509 int nParam;
137510 RtreeDValue aParam[1];
137514 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
137515 ** a single instance of the following structure is allocated. It is used
137516 ** as the context for the user-function created by by s_r_g_c(). The object
137517 ** is eventually deleted by the destructor mechanism provided by
137518 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
137519 ** the geometry callback function).
137521 struct RtreeGeomCallback {
137522 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
137523 void *pContext;
137526 #ifndef MAX
137527 # define MAX(x,y) ((x) < (y) ? (y) : (x))
137528 #endif
137529 #ifndef MIN
137530 # define MIN(x,y) ((x) > (y) ? (y) : (x))
137531 #endif
137534 ** Functions to deserialize a 16 bit integer, 32 bit real number and
137535 ** 64 bit integer. The deserialized value is returned.
137537 static int readInt16(u8 *p){
137538 return (p[0]<<8) + p[1];
137540 static void readCoord(u8 *p, RtreeCoord *pCoord){
137541 u32 i = (
137542 (((u32)p[0]) << 24) +
137543 (((u32)p[1]) << 16) +
137544 (((u32)p[2]) << 8) +
137545 (((u32)p[3]) << 0)
137547 *(u32 *)pCoord = i;
137549 static i64 readInt64(u8 *p){
137550 return (
137551 (((i64)p[0]) << 56) +
137552 (((i64)p[1]) << 48) +
137553 (((i64)p[2]) << 40) +
137554 (((i64)p[3]) << 32) +
137555 (((i64)p[4]) << 24) +
137556 (((i64)p[5]) << 16) +
137557 (((i64)p[6]) << 8) +
137558 (((i64)p[7]) << 0)
137563 ** Functions to serialize a 16 bit integer, 32 bit real number and
137564 ** 64 bit integer. The value returned is the number of bytes written
137565 ** to the argument buffer (always 2, 4 and 8 respectively).
137567 static int writeInt16(u8 *p, int i){
137568 p[0] = (i>> 8)&0xFF;
137569 p[1] = (i>> 0)&0xFF;
137570 return 2;
137572 static int writeCoord(u8 *p, RtreeCoord *pCoord){
137573 u32 i;
137574 assert( sizeof(RtreeCoord)==4 );
137575 assert( sizeof(u32)==4 );
137576 i = *(u32 *)pCoord;
137577 p[0] = (i>>24)&0xFF;
137578 p[1] = (i>>16)&0xFF;
137579 p[2] = (i>> 8)&0xFF;
137580 p[3] = (i>> 0)&0xFF;
137581 return 4;
137583 static int writeInt64(u8 *p, i64 i){
137584 p[0] = (i>>56)&0xFF;
137585 p[1] = (i>>48)&0xFF;
137586 p[2] = (i>>40)&0xFF;
137587 p[3] = (i>>32)&0xFF;
137588 p[4] = (i>>24)&0xFF;
137589 p[5] = (i>>16)&0xFF;
137590 p[6] = (i>> 8)&0xFF;
137591 p[7] = (i>> 0)&0xFF;
137592 return 8;
137596 ** Increment the reference count of node p.
137598 static void nodeReference(RtreeNode *p){
137599 if( p ){
137600 p->nRef++;
137605 ** Clear the content of node p (set all bytes to 0x00).
137607 static void nodeZero(Rtree *pRtree, RtreeNode *p){
137608 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
137609 p->isDirty = 1;
137613 ** Given a node number iNode, return the corresponding key to use
137614 ** in the Rtree.aHash table.
137616 static int nodeHash(i64 iNode){
137617 return (
137618 (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
137619 (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
137620 ) % HASHSIZE;
137624 ** Search the node hash table for node iNode. If found, return a pointer
137625 ** to it. Otherwise, return 0.
137627 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
137628 RtreeNode *p;
137629 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
137630 return p;
137634 ** Add node pNode to the node hash table.
137636 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
137637 int iHash;
137638 assert( pNode->pNext==0 );
137639 iHash = nodeHash(pNode->iNode);
137640 pNode->pNext = pRtree->aHash[iHash];
137641 pRtree->aHash[iHash] = pNode;
137645 ** Remove node pNode from the node hash table.
137647 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
137648 RtreeNode **pp;
137649 if( pNode->iNode!=0 ){
137650 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
137651 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
137652 *pp = pNode->pNext;
137653 pNode->pNext = 0;
137658 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
137659 ** indicating that node has not yet been assigned a node number. It is
137660 ** assigned a node number when nodeWrite() is called to write the
137661 ** node contents out to the database.
137663 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
137664 RtreeNode *pNode;
137665 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
137666 if( pNode ){
137667 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
137668 pNode->zData = (u8 *)&pNode[1];
137669 pNode->nRef = 1;
137670 pNode->pParent = pParent;
137671 pNode->isDirty = 1;
137672 nodeReference(pParent);
137674 return pNode;
137678 ** Obtain a reference to an r-tree node.
137680 static int
137681 nodeAcquire(
137682 Rtree *pRtree, /* R-tree structure */
137683 i64 iNode, /* Node number to load */
137684 RtreeNode *pParent, /* Either the parent node or NULL */
137685 RtreeNode **ppNode /* OUT: Acquired node */
137687 int rc;
137688 int rc2 = SQLITE_OK;
137689 RtreeNode *pNode;
137691 /* Check if the requested node is already in the hash table. If so,
137692 ** increase its reference count and return it.
137694 if( (pNode = nodeHashLookup(pRtree, iNode)) ){
137695 assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
137696 if( pParent && !pNode->pParent ){
137697 nodeReference(pParent);
137698 pNode->pParent = pParent;
137700 pNode->nRef++;
137701 *ppNode = pNode;
137702 return SQLITE_OK;
137705 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
137706 rc = sqlite3_step(pRtree->pReadNode);
137707 if( rc==SQLITE_ROW ){
137708 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
137709 if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
137710 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
137711 if( !pNode ){
137712 rc2 = SQLITE_NOMEM;
137713 }else{
137714 pNode->pParent = pParent;
137715 pNode->zData = (u8 *)&pNode[1];
137716 pNode->nRef = 1;
137717 pNode->iNode = iNode;
137718 pNode->isDirty = 0;
137719 pNode->pNext = 0;
137720 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
137721 nodeReference(pParent);
137725 rc = sqlite3_reset(pRtree->pReadNode);
137726 if( rc==SQLITE_OK ) rc = rc2;
137728 /* If the root node was just loaded, set pRtree->iDepth to the height
137729 ** of the r-tree structure. A height of zero means all data is stored on
137730 ** the root node. A height of one means the children of the root node
137731 ** are the leaves, and so on. If the depth as specified on the root node
137732 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
137734 if( pNode && iNode==1 ){
137735 pRtree->iDepth = readInt16(pNode->zData);
137736 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
137737 rc = SQLITE_CORRUPT_VTAB;
137741 /* If no error has occurred so far, check if the "number of entries"
137742 ** field on the node is too large. If so, set the return code to
137743 ** SQLITE_CORRUPT_VTAB.
137745 if( pNode && rc==SQLITE_OK ){
137746 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
137747 rc = SQLITE_CORRUPT_VTAB;
137751 if( rc==SQLITE_OK ){
137752 if( pNode!=0 ){
137753 nodeHashInsert(pRtree, pNode);
137754 }else{
137755 rc = SQLITE_CORRUPT_VTAB;
137757 *ppNode = pNode;
137758 }else{
137759 sqlite3_free(pNode);
137760 *ppNode = 0;
137763 return rc;
137767 ** Overwrite cell iCell of node pNode with the contents of pCell.
137769 static void nodeOverwriteCell(
137770 Rtree *pRtree,
137771 RtreeNode *pNode,
137772 RtreeCell *pCell,
137773 int iCell
137775 int ii;
137776 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
137777 p += writeInt64(p, pCell->iRowid);
137778 for(ii=0; ii<(pRtree->nDim*2); ii++){
137779 p += writeCoord(p, &pCell->aCoord[ii]);
137781 pNode->isDirty = 1;
137785 ** Remove cell the cell with index iCell from node pNode.
137787 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
137788 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
137789 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
137790 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
137791 memmove(pDst, pSrc, nByte);
137792 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
137793 pNode->isDirty = 1;
137797 ** Insert the contents of cell pCell into node pNode. If the insert
137798 ** is successful, return SQLITE_OK.
137800 ** If there is not enough free space in pNode, return SQLITE_FULL.
137802 static int
137803 nodeInsertCell(
137804 Rtree *pRtree,
137805 RtreeNode *pNode,
137806 RtreeCell *pCell
137808 int nCell; /* Current number of cells in pNode */
137809 int nMaxCell; /* Maximum number of cells for pNode */
137811 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
137812 nCell = NCELL(pNode);
137814 assert( nCell<=nMaxCell );
137815 if( nCell<nMaxCell ){
137816 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
137817 writeInt16(&pNode->zData[2], nCell+1);
137818 pNode->isDirty = 1;
137821 return (nCell==nMaxCell);
137825 ** If the node is dirty, write it out to the database.
137827 static int
137828 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
137829 int rc = SQLITE_OK;
137830 if( pNode->isDirty ){
137831 sqlite3_stmt *p = pRtree->pWriteNode;
137832 if( pNode->iNode ){
137833 sqlite3_bind_int64(p, 1, pNode->iNode);
137834 }else{
137835 sqlite3_bind_null(p, 1);
137837 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
137838 sqlite3_step(p);
137839 pNode->isDirty = 0;
137840 rc = sqlite3_reset(p);
137841 if( pNode->iNode==0 && rc==SQLITE_OK ){
137842 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
137843 nodeHashInsert(pRtree, pNode);
137846 return rc;
137850 ** Release a reference to a node. If the node is dirty and the reference
137851 ** count drops to zero, the node data is written to the database.
137853 static int
137854 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
137855 int rc = SQLITE_OK;
137856 if( pNode ){
137857 assert( pNode->nRef>0 );
137858 pNode->nRef--;
137859 if( pNode->nRef==0 ){
137860 if( pNode->iNode==1 ){
137861 pRtree->iDepth = -1;
137863 if( pNode->pParent ){
137864 rc = nodeRelease(pRtree, pNode->pParent);
137866 if( rc==SQLITE_OK ){
137867 rc = nodeWrite(pRtree, pNode);
137869 nodeHashDelete(pRtree, pNode);
137870 sqlite3_free(pNode);
137873 return rc;
137877 ** Return the 64-bit integer value associated with cell iCell of
137878 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
137879 ** an internal node, then the 64-bit integer is a child page number.
137881 static i64 nodeGetRowid(
137882 Rtree *pRtree,
137883 RtreeNode *pNode,
137884 int iCell
137886 assert( iCell<NCELL(pNode) );
137887 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
137891 ** Return coordinate iCoord from cell iCell in node pNode.
137893 static void nodeGetCoord(
137894 Rtree *pRtree,
137895 RtreeNode *pNode,
137896 int iCell,
137897 int iCoord,
137898 RtreeCoord *pCoord /* Space to write result to */
137900 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
137904 ** Deserialize cell iCell of node pNode. Populate the structure pointed
137905 ** to by pCell with the results.
137907 static void nodeGetCell(
137908 Rtree *pRtree,
137909 RtreeNode *pNode,
137910 int iCell,
137911 RtreeCell *pCell
137913 int ii;
137914 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
137915 for(ii=0; ii<pRtree->nDim*2; ii++){
137916 nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
137921 /* Forward declaration for the function that does the work of
137922 ** the virtual table module xCreate() and xConnect() methods.
137924 static int rtreeInit(
137925 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
137929 ** Rtree virtual table module xCreate method.
137931 static int rtreeCreate(
137932 sqlite3 *db,
137933 void *pAux,
137934 int argc, const char *const*argv,
137935 sqlite3_vtab **ppVtab,
137936 char **pzErr
137938 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
137942 ** Rtree virtual table module xConnect method.
137944 static int rtreeConnect(
137945 sqlite3 *db,
137946 void *pAux,
137947 int argc, const char *const*argv,
137948 sqlite3_vtab **ppVtab,
137949 char **pzErr
137951 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
137955 ** Increment the r-tree reference count.
137957 static void rtreeReference(Rtree *pRtree){
137958 pRtree->nBusy++;
137962 ** Decrement the r-tree reference count. When the reference count reaches
137963 ** zero the structure is deleted.
137965 static void rtreeRelease(Rtree *pRtree){
137966 pRtree->nBusy--;
137967 if( pRtree->nBusy==0 ){
137968 sqlite3_finalize(pRtree->pReadNode);
137969 sqlite3_finalize(pRtree->pWriteNode);
137970 sqlite3_finalize(pRtree->pDeleteNode);
137971 sqlite3_finalize(pRtree->pReadRowid);
137972 sqlite3_finalize(pRtree->pWriteRowid);
137973 sqlite3_finalize(pRtree->pDeleteRowid);
137974 sqlite3_finalize(pRtree->pReadParent);
137975 sqlite3_finalize(pRtree->pWriteParent);
137976 sqlite3_finalize(pRtree->pDeleteParent);
137977 sqlite3_free(pRtree);
137982 ** Rtree virtual table module xDisconnect method.
137984 static int rtreeDisconnect(sqlite3_vtab *pVtab){
137985 rtreeRelease((Rtree *)pVtab);
137986 return SQLITE_OK;
137990 ** Rtree virtual table module xDestroy method.
137992 static int rtreeDestroy(sqlite3_vtab *pVtab){
137993 Rtree *pRtree = (Rtree *)pVtab;
137994 int rc;
137995 char *zCreate = sqlite3_mprintf(
137996 "DROP TABLE '%q'.'%q_node';"
137997 "DROP TABLE '%q'.'%q_rowid';"
137998 "DROP TABLE '%q'.'%q_parent';",
137999 pRtree->zDb, pRtree->zName,
138000 pRtree->zDb, pRtree->zName,
138001 pRtree->zDb, pRtree->zName
138003 if( !zCreate ){
138004 rc = SQLITE_NOMEM;
138005 }else{
138006 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
138007 sqlite3_free(zCreate);
138009 if( rc==SQLITE_OK ){
138010 rtreeRelease(pRtree);
138013 return rc;
138017 ** Rtree virtual table module xOpen method.
138019 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
138020 int rc = SQLITE_NOMEM;
138021 RtreeCursor *pCsr;
138023 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
138024 if( pCsr ){
138025 memset(pCsr, 0, sizeof(RtreeCursor));
138026 pCsr->base.pVtab = pVTab;
138027 rc = SQLITE_OK;
138029 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
138031 return rc;
138036 ** Free the RtreeCursor.aConstraint[] array and its contents.
138038 static void freeCursorConstraints(RtreeCursor *pCsr){
138039 if( pCsr->aConstraint ){
138040 int i; /* Used to iterate through constraint array */
138041 for(i=0; i<pCsr->nConstraint; i++){
138042 sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
138043 if( pGeom ){
138044 if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
138045 sqlite3_free(pGeom);
138048 sqlite3_free(pCsr->aConstraint);
138049 pCsr->aConstraint = 0;
138054 ** Rtree virtual table module xClose method.
138056 static int rtreeClose(sqlite3_vtab_cursor *cur){
138057 Rtree *pRtree = (Rtree *)(cur->pVtab);
138058 int rc;
138059 RtreeCursor *pCsr = (RtreeCursor *)cur;
138060 freeCursorConstraints(pCsr);
138061 rc = nodeRelease(pRtree, pCsr->pNode);
138062 sqlite3_free(pCsr);
138063 return rc;
138067 ** Rtree virtual table module xEof method.
138069 ** Return non-zero if the cursor does not currently point to a valid
138070 ** record (i.e if the scan has finished), or zero otherwise.
138072 static int rtreeEof(sqlite3_vtab_cursor *cur){
138073 RtreeCursor *pCsr = (RtreeCursor *)cur;
138074 return (pCsr->pNode==0);
138078 ** The r-tree constraint passed as the second argument to this function is
138079 ** guaranteed to be a MATCH constraint.
138081 static int testRtreeGeom(
138082 Rtree *pRtree, /* R-Tree object */
138083 RtreeConstraint *pConstraint, /* MATCH constraint to test */
138084 RtreeCell *pCell, /* Cell to test */
138085 int *pbRes /* OUT: Test result */
138087 int i;
138088 RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
138089 int nCoord = pRtree->nDim*2;
138091 assert( pConstraint->op==RTREE_MATCH );
138092 assert( pConstraint->pGeom );
138094 for(i=0; i<nCoord; i++){
138095 aCoord[i] = DCOORD(pCell->aCoord[i]);
138097 return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
138101 ** Cursor pCursor currently points to a cell in a non-leaf page.
138102 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
138103 ** (excluded) by the constraints in the pCursor->aConstraint[]
138104 ** array, or false otherwise.
138106 ** Return SQLITE_OK if successful or an SQLite error code if an error
138107 ** occurs within a geometry callback.
138109 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
138110 RtreeCell cell;
138111 int ii;
138112 int bRes = 0;
138113 int rc = SQLITE_OK;
138115 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
138116 for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
138117 RtreeConstraint *p = &pCursor->aConstraint[ii];
138118 RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
138119 RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
138121 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
138122 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
138125 switch( p->op ){
138126 case RTREE_LE: case RTREE_LT:
138127 bRes = p->rValue<cell_min;
138128 break;
138130 case RTREE_GE: case RTREE_GT:
138131 bRes = p->rValue>cell_max;
138132 break;
138134 case RTREE_EQ:
138135 bRes = (p->rValue>cell_max || p->rValue<cell_min);
138136 break;
138138 default: {
138139 assert( p->op==RTREE_MATCH );
138140 rc = testRtreeGeom(pRtree, p, &cell, &bRes);
138141 bRes = !bRes;
138142 break;
138147 *pbEof = bRes;
138148 return rc;
138152 ** Test if the cell that cursor pCursor currently points to
138153 ** would be filtered (excluded) by the constraints in the
138154 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
138155 ** returning. If the cell is not filtered (excluded) by the constraints,
138156 ** set pbEof to zero.
138158 ** Return SQLITE_OK if successful or an SQLite error code if an error
138159 ** occurs within a geometry callback.
138161 ** This function assumes that the cell is part of a leaf node.
138163 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
138164 RtreeCell cell;
138165 int ii;
138166 *pbEof = 0;
138168 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
138169 for(ii=0; ii<pCursor->nConstraint; ii++){
138170 RtreeConstraint *p = &pCursor->aConstraint[ii];
138171 RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
138172 int res;
138173 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
138174 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
138176 switch( p->op ){
138177 case RTREE_LE: res = (coord<=p->rValue); break;
138178 case RTREE_LT: res = (coord<p->rValue); break;
138179 case RTREE_GE: res = (coord>=p->rValue); break;
138180 case RTREE_GT: res = (coord>p->rValue); break;
138181 case RTREE_EQ: res = (coord==p->rValue); break;
138182 default: {
138183 int rc;
138184 assert( p->op==RTREE_MATCH );
138185 rc = testRtreeGeom(pRtree, p, &cell, &res);
138186 if( rc!=SQLITE_OK ){
138187 return rc;
138189 break;
138193 if( !res ){
138194 *pbEof = 1;
138195 return SQLITE_OK;
138199 return SQLITE_OK;
138203 ** Cursor pCursor currently points at a node that heads a sub-tree of
138204 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
138205 ** to point to the left-most cell of the sub-tree that matches the
138206 ** configured constraints.
138208 static int descendToCell(
138209 Rtree *pRtree,
138210 RtreeCursor *pCursor,
138211 int iHeight,
138212 int *pEof /* OUT: Set to true if cannot descend */
138214 int isEof;
138215 int rc;
138216 int ii;
138217 RtreeNode *pChild;
138218 sqlite3_int64 iRowid;
138220 RtreeNode *pSavedNode = pCursor->pNode;
138221 int iSavedCell = pCursor->iCell;
138223 assert( iHeight>=0 );
138225 if( iHeight==0 ){
138226 rc = testRtreeEntry(pRtree, pCursor, &isEof);
138227 }else{
138228 rc = testRtreeCell(pRtree, pCursor, &isEof);
138230 if( rc!=SQLITE_OK || isEof || iHeight==0 ){
138231 goto descend_to_cell_out;
138234 iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
138235 rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
138236 if( rc!=SQLITE_OK ){
138237 goto descend_to_cell_out;
138240 nodeRelease(pRtree, pCursor->pNode);
138241 pCursor->pNode = pChild;
138242 isEof = 1;
138243 for(ii=0; isEof && ii<NCELL(pChild); ii++){
138244 pCursor->iCell = ii;
138245 rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
138246 if( rc!=SQLITE_OK ){
138247 goto descend_to_cell_out;
138251 if( isEof ){
138252 assert( pCursor->pNode==pChild );
138253 nodeReference(pSavedNode);
138254 nodeRelease(pRtree, pChild);
138255 pCursor->pNode = pSavedNode;
138256 pCursor->iCell = iSavedCell;
138259 descend_to_cell_out:
138260 *pEof = isEof;
138261 return rc;
138265 ** One of the cells in node pNode is guaranteed to have a 64-bit
138266 ** integer value equal to iRowid. Return the index of this cell.
138268 static int nodeRowidIndex(
138269 Rtree *pRtree,
138270 RtreeNode *pNode,
138271 i64 iRowid,
138272 int *piIndex
138274 int ii;
138275 int nCell = NCELL(pNode);
138276 for(ii=0; ii<nCell; ii++){
138277 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
138278 *piIndex = ii;
138279 return SQLITE_OK;
138282 return SQLITE_CORRUPT_VTAB;
138286 ** Return the index of the cell containing a pointer to node pNode
138287 ** in its parent. If pNode is the root node, return -1.
138289 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
138290 RtreeNode *pParent = pNode->pParent;
138291 if( pParent ){
138292 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
138294 *piIndex = -1;
138295 return SQLITE_OK;
138299 ** Rtree virtual table module xNext method.
138301 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
138302 Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
138303 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
138304 int rc = SQLITE_OK;
138306 /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
138307 ** already at EOF. It is against the rules to call the xNext() method of
138308 ** a cursor that has already reached EOF.
138310 assert( pCsr->pNode );
138312 if( pCsr->iStrategy==1 ){
138313 /* This "scan" is a direct lookup by rowid. There is no next entry. */
138314 nodeRelease(pRtree, pCsr->pNode);
138315 pCsr->pNode = 0;
138316 }else{
138317 /* Move to the next entry that matches the configured constraints. */
138318 int iHeight = 0;
138319 while( pCsr->pNode ){
138320 RtreeNode *pNode = pCsr->pNode;
138321 int nCell = NCELL(pNode);
138322 for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
138323 int isEof;
138324 rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
138325 if( rc!=SQLITE_OK || !isEof ){
138326 return rc;
138329 pCsr->pNode = pNode->pParent;
138330 rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
138331 if( rc!=SQLITE_OK ){
138332 return rc;
138334 nodeReference(pCsr->pNode);
138335 nodeRelease(pRtree, pNode);
138336 iHeight++;
138340 return rc;
138344 ** Rtree virtual table module xRowid method.
138346 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
138347 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
138348 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
138350 assert(pCsr->pNode);
138351 *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
138353 return SQLITE_OK;
138357 ** Rtree virtual table module xColumn method.
138359 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
138360 Rtree *pRtree = (Rtree *)cur->pVtab;
138361 RtreeCursor *pCsr = (RtreeCursor *)cur;
138363 if( i==0 ){
138364 i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
138365 sqlite3_result_int64(ctx, iRowid);
138366 }else{
138367 RtreeCoord c;
138368 nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
138369 #ifndef SQLITE_RTREE_INT_ONLY
138370 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
138371 sqlite3_result_double(ctx, c.f);
138372 }else
138373 #endif
138375 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
138376 sqlite3_result_int(ctx, c.i);
138380 return SQLITE_OK;
138384 ** Use nodeAcquire() to obtain the leaf node containing the record with
138385 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
138386 ** return SQLITE_OK. If there is no such record in the table, set
138387 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
138388 ** to zero and return an SQLite error code.
138390 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
138391 int rc;
138392 *ppLeaf = 0;
138393 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
138394 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
138395 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
138396 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
138397 sqlite3_reset(pRtree->pReadRowid);
138398 }else{
138399 rc = sqlite3_reset(pRtree->pReadRowid);
138401 return rc;
138405 ** This function is called to configure the RtreeConstraint object passed
138406 ** as the second argument for a MATCH constraint. The value passed as the
138407 ** first argument to this function is the right-hand operand to the MATCH
138408 ** operator.
138410 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
138411 RtreeMatchArg *p;
138412 sqlite3_rtree_geometry *pGeom;
138413 int nBlob;
138415 /* Check that value is actually a blob. */
138416 if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
138418 /* Check that the blob is roughly the right size. */
138419 nBlob = sqlite3_value_bytes(pValue);
138420 if( nBlob<(int)sizeof(RtreeMatchArg)
138421 || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
138423 return SQLITE_ERROR;
138426 pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
138427 sizeof(sqlite3_rtree_geometry) + nBlob
138429 if( !pGeom ) return SQLITE_NOMEM;
138430 memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
138431 p = (RtreeMatchArg *)&pGeom[1];
138433 memcpy(p, sqlite3_value_blob(pValue), nBlob);
138434 if( p->magic!=RTREE_GEOMETRY_MAGIC
138435 || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
138437 sqlite3_free(pGeom);
138438 return SQLITE_ERROR;
138441 pGeom->pContext = p->pContext;
138442 pGeom->nParam = p->nParam;
138443 pGeom->aParam = p->aParam;
138445 pCons->xGeom = p->xGeom;
138446 pCons->pGeom = pGeom;
138447 return SQLITE_OK;
138451 ** Rtree virtual table module xFilter method.
138453 static int rtreeFilter(
138454 sqlite3_vtab_cursor *pVtabCursor,
138455 int idxNum, const char *idxStr,
138456 int argc, sqlite3_value **argv
138458 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
138459 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
138461 RtreeNode *pRoot = 0;
138462 int ii;
138463 int rc = SQLITE_OK;
138465 rtreeReference(pRtree);
138467 freeCursorConstraints(pCsr);
138468 pCsr->iStrategy = idxNum;
138470 if( idxNum==1 ){
138471 /* Special case - lookup by rowid. */
138472 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
138473 i64 iRowid = sqlite3_value_int64(argv[0]);
138474 rc = findLeafNode(pRtree, iRowid, &pLeaf);
138475 pCsr->pNode = pLeaf;
138476 if( pLeaf ){
138477 assert( rc==SQLITE_OK );
138478 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
138480 }else{
138481 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
138482 ** with the configured constraints.
138484 if( argc>0 ){
138485 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
138486 pCsr->nConstraint = argc;
138487 if( !pCsr->aConstraint ){
138488 rc = SQLITE_NOMEM;
138489 }else{
138490 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
138491 assert( (idxStr==0 && argc==0)
138492 || (idxStr && (int)strlen(idxStr)==argc*2) );
138493 for(ii=0; ii<argc; ii++){
138494 RtreeConstraint *p = &pCsr->aConstraint[ii];
138495 p->op = idxStr[ii*2];
138496 p->iCoord = idxStr[ii*2+1]-'a';
138497 if( p->op==RTREE_MATCH ){
138498 /* A MATCH operator. The right-hand-side must be a blob that
138499 ** can be cast into an RtreeMatchArg object. One created using
138500 ** an sqlite3_rtree_geometry_callback() SQL user function.
138502 rc = deserializeGeometry(argv[ii], p);
138503 if( rc!=SQLITE_OK ){
138504 break;
138506 }else{
138507 #ifdef SQLITE_RTREE_INT_ONLY
138508 p->rValue = sqlite3_value_int64(argv[ii]);
138509 #else
138510 p->rValue = sqlite3_value_double(argv[ii]);
138511 #endif
138517 if( rc==SQLITE_OK ){
138518 pCsr->pNode = 0;
138519 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
138521 if( rc==SQLITE_OK ){
138522 int isEof = 1;
138523 int nCell = NCELL(pRoot);
138524 pCsr->pNode = pRoot;
138525 for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
138526 assert( pCsr->pNode==pRoot );
138527 rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
138528 if( !isEof ){
138529 break;
138532 if( rc==SQLITE_OK && isEof ){
138533 assert( pCsr->pNode==pRoot );
138534 nodeRelease(pRtree, pRoot);
138535 pCsr->pNode = 0;
138537 assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
138541 rtreeRelease(pRtree);
138542 return rc;
138546 ** Rtree virtual table module xBestIndex method. There are three
138547 ** table scan strategies to choose from (in order from most to
138548 ** least desirable):
138550 ** idxNum idxStr Strategy
138551 ** ------------------------------------------------
138552 ** 1 Unused Direct lookup by rowid.
138553 ** 2 See below R-tree query or full-table scan.
138554 ** ------------------------------------------------
138556 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
138557 ** 2 is used, idxStr is formatted to contain 2 bytes for each
138558 ** constraint used. The first two bytes of idxStr correspond to
138559 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
138560 ** (argvIndex==1) etc.
138562 ** The first of each pair of bytes in idxStr identifies the constraint
138563 ** operator as follows:
138565 ** Operator Byte Value
138566 ** ----------------------
138567 ** = 0x41 ('A')
138568 ** <= 0x42 ('B')
138569 ** < 0x43 ('C')
138570 ** >= 0x44 ('D')
138571 ** > 0x45 ('E')
138572 ** MATCH 0x46 ('F')
138573 ** ----------------------
138575 ** The second of each pair of bytes identifies the coordinate column
138576 ** to which the constraint applies. The leftmost coordinate column
138577 ** is 'a', the second from the left 'b' etc.
138579 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
138580 int rc = SQLITE_OK;
138581 int ii;
138583 int iIdx = 0;
138584 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
138585 memset(zIdxStr, 0, sizeof(zIdxStr));
138586 UNUSED_PARAMETER(tab);
138588 assert( pIdxInfo->idxStr==0 );
138589 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
138590 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
138592 if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
138593 /* We have an equality constraint on the rowid. Use strategy 1. */
138594 int jj;
138595 for(jj=0; jj<ii; jj++){
138596 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
138597 pIdxInfo->aConstraintUsage[jj].omit = 0;
138599 pIdxInfo->idxNum = 1;
138600 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
138601 pIdxInfo->aConstraintUsage[jj].omit = 1;
138603 /* This strategy involves a two rowid lookups on an B-Tree structures
138604 ** and then a linear search of an R-Tree node. This should be
138605 ** considered almost as quick as a direct rowid lookup (for which
138606 ** sqlite uses an internal cost of 0.0).
138608 pIdxInfo->estimatedCost = 10.0;
138609 return SQLITE_OK;
138612 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
138613 u8 op;
138614 switch( p->op ){
138615 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
138616 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
138617 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
138618 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
138619 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
138620 default:
138621 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
138622 op = RTREE_MATCH;
138623 break;
138625 zIdxStr[iIdx++] = op;
138626 zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
138627 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
138628 pIdxInfo->aConstraintUsage[ii].omit = 1;
138632 pIdxInfo->idxNum = 2;
138633 pIdxInfo->needToFreeIdxStr = 1;
138634 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
138635 return SQLITE_NOMEM;
138637 assert( iIdx>=0 );
138638 pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
138639 return rc;
138643 ** Return the N-dimensional volumn of the cell stored in *p.
138645 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
138646 RtreeDValue area = (RtreeDValue)1;
138647 int ii;
138648 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
138649 area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
138651 return area;
138655 ** Return the margin length of cell p. The margin length is the sum
138656 ** of the objects size in each dimension.
138658 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
138659 RtreeDValue margin = (RtreeDValue)0;
138660 int ii;
138661 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
138662 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
138664 return margin;
138668 ** Store the union of cells p1 and p2 in p1.
138670 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
138671 int ii;
138672 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
138673 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
138674 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
138675 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
138677 }else{
138678 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
138679 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
138680 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
138686 ** Return true if the area covered by p2 is a subset of the area covered
138687 ** by p1. False otherwise.
138689 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
138690 int ii;
138691 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
138692 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
138693 RtreeCoord *a1 = &p1->aCoord[ii];
138694 RtreeCoord *a2 = &p2->aCoord[ii];
138695 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
138696 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
138698 return 0;
138701 return 1;
138705 ** Return the amount cell p would grow by if it were unioned with pCell.
138707 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
138708 RtreeDValue area;
138709 RtreeCell cell;
138710 memcpy(&cell, p, sizeof(RtreeCell));
138711 area = cellArea(pRtree, &cell);
138712 cellUnion(pRtree, &cell, pCell);
138713 return (cellArea(pRtree, &cell)-area);
138716 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
138717 static RtreeDValue cellOverlap(
138718 Rtree *pRtree,
138719 RtreeCell *p,
138720 RtreeCell *aCell,
138721 int nCell,
138722 int iExclude
138724 int ii;
138725 RtreeDValue overlap = 0.0;
138726 for(ii=0; ii<nCell; ii++){
138727 #if VARIANT_RSTARTREE_CHOOSESUBTREE
138728 if( ii!=iExclude )
138729 #else
138730 assert( iExclude==-1 );
138731 UNUSED_PARAMETER(iExclude);
138732 #endif
138734 int jj;
138735 RtreeDValue o = (RtreeDValue)1;
138736 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
138737 RtreeDValue x1, x2;
138739 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
138740 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
138742 if( x2<x1 ){
138743 o = 0.0;
138744 break;
138745 }else{
138746 o = o * (x2-x1);
138749 overlap += o;
138752 return overlap;
138754 #endif
138756 #if VARIANT_RSTARTREE_CHOOSESUBTREE
138757 static RtreeDValue cellOverlapEnlargement(
138758 Rtree *pRtree,
138759 RtreeCell *p,
138760 RtreeCell *pInsert,
138761 RtreeCell *aCell,
138762 int nCell,
138763 int iExclude
138765 RtreeDValue before, after;
138766 before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
138767 cellUnion(pRtree, p, pInsert);
138768 after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
138769 return (after-before);
138771 #endif
138775 ** This function implements the ChooseLeaf algorithm from Gutman[84].
138776 ** ChooseSubTree in r*tree terminology.
138778 static int ChooseLeaf(
138779 Rtree *pRtree, /* Rtree table */
138780 RtreeCell *pCell, /* Cell to insert into rtree */
138781 int iHeight, /* Height of sub-tree rooted at pCell */
138782 RtreeNode **ppLeaf /* OUT: Selected leaf page */
138784 int rc;
138785 int ii;
138786 RtreeNode *pNode;
138787 rc = nodeAcquire(pRtree, 1, 0, &pNode);
138789 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
138790 int iCell;
138791 sqlite3_int64 iBest = 0;
138793 RtreeDValue fMinGrowth = 0.0;
138794 RtreeDValue fMinArea = 0.0;
138795 #if VARIANT_RSTARTREE_CHOOSESUBTREE
138796 RtreeDValue fMinOverlap = 0.0;
138797 RtreeDValue overlap;
138798 #endif
138800 int nCell = NCELL(pNode);
138801 RtreeCell cell;
138802 RtreeNode *pChild;
138804 RtreeCell *aCell = 0;
138806 #if VARIANT_RSTARTREE_CHOOSESUBTREE
138807 if( ii==(pRtree->iDepth-1) ){
138808 int jj;
138809 aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
138810 if( !aCell ){
138811 rc = SQLITE_NOMEM;
138812 nodeRelease(pRtree, pNode);
138813 pNode = 0;
138814 continue;
138816 for(jj=0; jj<nCell; jj++){
138817 nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
138820 #endif
138822 /* Select the child node which will be enlarged the least if pCell
138823 ** is inserted into it. Resolve ties by choosing the entry with
138824 ** the smallest area.
138826 for(iCell=0; iCell<nCell; iCell++){
138827 int bBest = 0;
138828 RtreeDValue growth;
138829 RtreeDValue area;
138830 nodeGetCell(pRtree, pNode, iCell, &cell);
138831 growth = cellGrowth(pRtree, &cell, pCell);
138832 area = cellArea(pRtree, &cell);
138834 #if VARIANT_RSTARTREE_CHOOSESUBTREE
138835 if( ii==(pRtree->iDepth-1) ){
138836 overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
138837 }else{
138838 overlap = 0.0;
138840 if( (iCell==0)
138841 || (overlap<fMinOverlap)
138842 || (overlap==fMinOverlap && growth<fMinGrowth)
138843 || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
138845 bBest = 1;
138846 fMinOverlap = overlap;
138848 #else
138849 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
138850 bBest = 1;
138852 #endif
138853 if( bBest ){
138854 fMinGrowth = growth;
138855 fMinArea = area;
138856 iBest = cell.iRowid;
138860 sqlite3_free(aCell);
138861 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
138862 nodeRelease(pRtree, pNode);
138863 pNode = pChild;
138866 *ppLeaf = pNode;
138867 return rc;
138871 ** A cell with the same content as pCell has just been inserted into
138872 ** the node pNode. This function updates the bounding box cells in
138873 ** all ancestor elements.
138875 static int AdjustTree(
138876 Rtree *pRtree, /* Rtree table */
138877 RtreeNode *pNode, /* Adjust ancestry of this node. */
138878 RtreeCell *pCell /* This cell was just inserted */
138880 RtreeNode *p = pNode;
138881 while( p->pParent ){
138882 RtreeNode *pParent = p->pParent;
138883 RtreeCell cell;
138884 int iCell;
138886 if( nodeParentIndex(pRtree, p, &iCell) ){
138887 return SQLITE_CORRUPT_VTAB;
138890 nodeGetCell(pRtree, pParent, iCell, &cell);
138891 if( !cellContains(pRtree, &cell, pCell) ){
138892 cellUnion(pRtree, &cell, pCell);
138893 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
138896 p = pParent;
138898 return SQLITE_OK;
138902 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
138904 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
138905 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
138906 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
138907 sqlite3_step(pRtree->pWriteRowid);
138908 return sqlite3_reset(pRtree->pWriteRowid);
138912 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
138914 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
138915 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
138916 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
138917 sqlite3_step(pRtree->pWriteParent);
138918 return sqlite3_reset(pRtree->pWriteParent);
138921 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
138923 #if VARIANT_GUTTMAN_LINEAR_SPLIT
138925 ** Implementation of the linear variant of the PickNext() function from
138926 ** Guttman[84].
138928 static RtreeCell *LinearPickNext(
138929 Rtree *pRtree,
138930 RtreeCell *aCell,
138931 int nCell,
138932 RtreeCell *pLeftBox,
138933 RtreeCell *pRightBox,
138934 int *aiUsed
138936 int ii;
138937 for(ii=0; aiUsed[ii]; ii++);
138938 aiUsed[ii] = 1;
138939 return &aCell[ii];
138943 ** Implementation of the linear variant of the PickSeeds() function from
138944 ** Guttman[84].
138946 static void LinearPickSeeds(
138947 Rtree *pRtree,
138948 RtreeCell *aCell,
138949 int nCell,
138950 int *piLeftSeed,
138951 int *piRightSeed
138953 int i;
138954 int iLeftSeed = 0;
138955 int iRightSeed = 1;
138956 RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
138958 /* Pick two "seed" cells from the array of cells. The algorithm used
138959 ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
138960 ** indices of the two seed cells in the array are stored in local
138961 ** variables iLeftSeek and iRightSeed.
138963 for(i=0; i<pRtree->nDim; i++){
138964 RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
138965 RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
138966 RtreeDValue x3 = x1;
138967 RtreeDValue x4 = x2;
138968 int jj;
138970 int iCellLeft = 0;
138971 int iCellRight = 0;
138973 for(jj=1; jj<nCell; jj++){
138974 RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
138975 RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
138977 if( left<x1 ) x1 = left;
138978 if( right>x4 ) x4 = right;
138979 if( left>x3 ){
138980 x3 = left;
138981 iCellRight = jj;
138983 if( right<x2 ){
138984 x2 = right;
138985 iCellLeft = jj;
138989 if( x4!=x1 ){
138990 RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
138991 if( normalwidth>maxNormalInnerWidth ){
138992 iLeftSeed = iCellLeft;
138993 iRightSeed = iCellRight;
138998 *piLeftSeed = iLeftSeed;
138999 *piRightSeed = iRightSeed;
139001 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
139003 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
139005 ** Implementation of the quadratic variant of the PickNext() function from
139006 ** Guttman[84].
139008 static RtreeCell *QuadraticPickNext(
139009 Rtree *pRtree,
139010 RtreeCell *aCell,
139011 int nCell,
139012 RtreeCell *pLeftBox,
139013 RtreeCell *pRightBox,
139014 int *aiUsed
139016 #define FABS(a) ((a)<0.0?-1.0*(a):(a))
139018 int iSelect = -1;
139019 RtreeDValue fDiff;
139020 int ii;
139021 for(ii=0; ii<nCell; ii++){
139022 if( aiUsed[ii]==0 ){
139023 RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
139024 RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
139025 RtreeDValue diff = FABS(right-left);
139026 if( iSelect<0 || diff>fDiff ){
139027 fDiff = diff;
139028 iSelect = ii;
139032 aiUsed[iSelect] = 1;
139033 return &aCell[iSelect];
139037 ** Implementation of the quadratic variant of the PickSeeds() function from
139038 ** Guttman[84].
139040 static void QuadraticPickSeeds(
139041 Rtree *pRtree,
139042 RtreeCell *aCell,
139043 int nCell,
139044 int *piLeftSeed,
139045 int *piRightSeed
139047 int ii;
139048 int jj;
139050 int iLeftSeed = 0;
139051 int iRightSeed = 1;
139052 RtreeDValue fWaste = 0.0;
139054 for(ii=0; ii<nCell; ii++){
139055 for(jj=ii+1; jj<nCell; jj++){
139056 RtreeDValue right = cellArea(pRtree, &aCell[jj]);
139057 RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
139058 RtreeDValue waste = growth - right;
139060 if( waste>fWaste ){
139061 iLeftSeed = ii;
139062 iRightSeed = jj;
139063 fWaste = waste;
139068 *piLeftSeed = iLeftSeed;
139069 *piRightSeed = iRightSeed;
139071 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
139074 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
139075 ** nIdx. The aIdx array contains the set of integers from 0 to
139076 ** (nIdx-1) in no particular order. This function sorts the values
139077 ** in aIdx according to the indexed values in aDistance. For
139078 ** example, assuming the inputs:
139080 ** aIdx = { 0, 1, 2, 3 }
139081 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
139083 ** this function sets the aIdx array to contain:
139085 ** aIdx = { 0, 1, 2, 3 }
139087 ** The aSpare array is used as temporary working space by the
139088 ** sorting algorithm.
139090 static void SortByDistance(
139091 int *aIdx,
139092 int nIdx,
139093 RtreeDValue *aDistance,
139094 int *aSpare
139096 if( nIdx>1 ){
139097 int iLeft = 0;
139098 int iRight = 0;
139100 int nLeft = nIdx/2;
139101 int nRight = nIdx-nLeft;
139102 int *aLeft = aIdx;
139103 int *aRight = &aIdx[nLeft];
139105 SortByDistance(aLeft, nLeft, aDistance, aSpare);
139106 SortByDistance(aRight, nRight, aDistance, aSpare);
139108 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
139109 aLeft = aSpare;
139111 while( iLeft<nLeft || iRight<nRight ){
139112 if( iLeft==nLeft ){
139113 aIdx[iLeft+iRight] = aRight[iRight];
139114 iRight++;
139115 }else if( iRight==nRight ){
139116 aIdx[iLeft+iRight] = aLeft[iLeft];
139117 iLeft++;
139118 }else{
139119 RtreeDValue fLeft = aDistance[aLeft[iLeft]];
139120 RtreeDValue fRight = aDistance[aRight[iRight]];
139121 if( fLeft<fRight ){
139122 aIdx[iLeft+iRight] = aLeft[iLeft];
139123 iLeft++;
139124 }else{
139125 aIdx[iLeft+iRight] = aRight[iRight];
139126 iRight++;
139131 #if 0
139132 /* Check that the sort worked */
139134 int jj;
139135 for(jj=1; jj<nIdx; jj++){
139136 RtreeDValue left = aDistance[aIdx[jj-1]];
139137 RtreeDValue right = aDistance[aIdx[jj]];
139138 assert( left<=right );
139141 #endif
139146 ** Arguments aIdx, aCell and aSpare all point to arrays of size
139147 ** nIdx. The aIdx array contains the set of integers from 0 to
139148 ** (nIdx-1) in no particular order. This function sorts the values
139149 ** in aIdx according to dimension iDim of the cells in aCell. The
139150 ** minimum value of dimension iDim is considered first, the
139151 ** maximum used to break ties.
139153 ** The aSpare array is used as temporary working space by the
139154 ** sorting algorithm.
139156 static void SortByDimension(
139157 Rtree *pRtree,
139158 int *aIdx,
139159 int nIdx,
139160 int iDim,
139161 RtreeCell *aCell,
139162 int *aSpare
139164 if( nIdx>1 ){
139166 int iLeft = 0;
139167 int iRight = 0;
139169 int nLeft = nIdx/2;
139170 int nRight = nIdx-nLeft;
139171 int *aLeft = aIdx;
139172 int *aRight = &aIdx[nLeft];
139174 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
139175 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
139177 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
139178 aLeft = aSpare;
139179 while( iLeft<nLeft || iRight<nRight ){
139180 RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
139181 RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
139182 RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
139183 RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
139184 if( (iLeft!=nLeft) && ((iRight==nRight)
139185 || (xleft1<xright1)
139186 || (xleft1==xright1 && xleft2<xright2)
139188 aIdx[iLeft+iRight] = aLeft[iLeft];
139189 iLeft++;
139190 }else{
139191 aIdx[iLeft+iRight] = aRight[iRight];
139192 iRight++;
139196 #if 0
139197 /* Check that the sort worked */
139199 int jj;
139200 for(jj=1; jj<nIdx; jj++){
139201 RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
139202 RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
139203 RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
139204 RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
139205 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
139208 #endif
139212 #if VARIANT_RSTARTREE_SPLIT
139214 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
139216 static int splitNodeStartree(
139217 Rtree *pRtree,
139218 RtreeCell *aCell,
139219 int nCell,
139220 RtreeNode *pLeft,
139221 RtreeNode *pRight,
139222 RtreeCell *pBboxLeft,
139223 RtreeCell *pBboxRight
139225 int **aaSorted;
139226 int *aSpare;
139227 int ii;
139229 int iBestDim = 0;
139230 int iBestSplit = 0;
139231 RtreeDValue fBestMargin = 0.0;
139233 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
139235 aaSorted = (int **)sqlite3_malloc(nByte);
139236 if( !aaSorted ){
139237 return SQLITE_NOMEM;
139240 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
139241 memset(aaSorted, 0, nByte);
139242 for(ii=0; ii<pRtree->nDim; ii++){
139243 int jj;
139244 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
139245 for(jj=0; jj<nCell; jj++){
139246 aaSorted[ii][jj] = jj;
139248 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
139251 for(ii=0; ii<pRtree->nDim; ii++){
139252 RtreeDValue margin = 0.0;
139253 RtreeDValue fBestOverlap = 0.0;
139254 RtreeDValue fBestArea = 0.0;
139255 int iBestLeft = 0;
139256 int nLeft;
139259 nLeft=RTREE_MINCELLS(pRtree);
139260 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
139261 nLeft++
139263 RtreeCell left;
139264 RtreeCell right;
139265 int kk;
139266 RtreeDValue overlap;
139267 RtreeDValue area;
139269 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
139270 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
139271 for(kk=1; kk<(nCell-1); kk++){
139272 if( kk<nLeft ){
139273 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
139274 }else{
139275 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
139278 margin += cellMargin(pRtree, &left);
139279 margin += cellMargin(pRtree, &right);
139280 overlap = cellOverlap(pRtree, &left, &right, 1, -1);
139281 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
139282 if( (nLeft==RTREE_MINCELLS(pRtree))
139283 || (overlap<fBestOverlap)
139284 || (overlap==fBestOverlap && area<fBestArea)
139286 iBestLeft = nLeft;
139287 fBestOverlap = overlap;
139288 fBestArea = area;
139292 if( ii==0 || margin<fBestMargin ){
139293 iBestDim = ii;
139294 fBestMargin = margin;
139295 iBestSplit = iBestLeft;
139299 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
139300 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
139301 for(ii=0; ii<nCell; ii++){
139302 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
139303 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
139304 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
139305 nodeInsertCell(pRtree, pTarget, pCell);
139306 cellUnion(pRtree, pBbox, pCell);
139309 sqlite3_free(aaSorted);
139310 return SQLITE_OK;
139312 #endif
139314 #if VARIANT_GUTTMAN_SPLIT
139316 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
139318 static int splitNodeGuttman(
139319 Rtree *pRtree,
139320 RtreeCell *aCell,
139321 int nCell,
139322 RtreeNode *pLeft,
139323 RtreeNode *pRight,
139324 RtreeCell *pBboxLeft,
139325 RtreeCell *pBboxRight
139327 int iLeftSeed = 0;
139328 int iRightSeed = 1;
139329 int *aiUsed;
139330 int i;
139332 aiUsed = sqlite3_malloc(sizeof(int)*nCell);
139333 if( !aiUsed ){
139334 return SQLITE_NOMEM;
139336 memset(aiUsed, 0, sizeof(int)*nCell);
139338 PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
139340 memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
139341 memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
139342 nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
139343 nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
139344 aiUsed[iLeftSeed] = 1;
139345 aiUsed[iRightSeed] = 1;
139347 for(i=nCell-2; i>0; i--){
139348 RtreeCell *pNext;
139349 pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
139350 RtreeDValue diff =
139351 cellGrowth(pRtree, pBboxLeft, pNext) -
139352 cellGrowth(pRtree, pBboxRight, pNext)
139354 if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
139355 || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
139357 nodeInsertCell(pRtree, pRight, pNext);
139358 cellUnion(pRtree, pBboxRight, pNext);
139359 }else{
139360 nodeInsertCell(pRtree, pLeft, pNext);
139361 cellUnion(pRtree, pBboxLeft, pNext);
139365 sqlite3_free(aiUsed);
139366 return SQLITE_OK;
139368 #endif
139370 static int updateMapping(
139371 Rtree *pRtree,
139372 i64 iRowid,
139373 RtreeNode *pNode,
139374 int iHeight
139376 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
139377 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
139378 if( iHeight>0 ){
139379 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
139380 if( pChild ){
139381 nodeRelease(pRtree, pChild->pParent);
139382 nodeReference(pNode);
139383 pChild->pParent = pNode;
139386 return xSetMapping(pRtree, iRowid, pNode->iNode);
139389 static int SplitNode(
139390 Rtree *pRtree,
139391 RtreeNode *pNode,
139392 RtreeCell *pCell,
139393 int iHeight
139395 int i;
139396 int newCellIsRight = 0;
139398 int rc = SQLITE_OK;
139399 int nCell = NCELL(pNode);
139400 RtreeCell *aCell;
139401 int *aiUsed;
139403 RtreeNode *pLeft = 0;
139404 RtreeNode *pRight = 0;
139406 RtreeCell leftbbox;
139407 RtreeCell rightbbox;
139409 /* Allocate an array and populate it with a copy of pCell and
139410 ** all cells from node pLeft. Then zero the original node.
139412 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
139413 if( !aCell ){
139414 rc = SQLITE_NOMEM;
139415 goto splitnode_out;
139417 aiUsed = (int *)&aCell[nCell+1];
139418 memset(aiUsed, 0, sizeof(int)*(nCell+1));
139419 for(i=0; i<nCell; i++){
139420 nodeGetCell(pRtree, pNode, i, &aCell[i]);
139422 nodeZero(pRtree, pNode);
139423 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
139424 nCell++;
139426 if( pNode->iNode==1 ){
139427 pRight = nodeNew(pRtree, pNode);
139428 pLeft = nodeNew(pRtree, pNode);
139429 pRtree->iDepth++;
139430 pNode->isDirty = 1;
139431 writeInt16(pNode->zData, pRtree->iDepth);
139432 }else{
139433 pLeft = pNode;
139434 pRight = nodeNew(pRtree, pLeft->pParent);
139435 nodeReference(pLeft);
139438 if( !pLeft || !pRight ){
139439 rc = SQLITE_NOMEM;
139440 goto splitnode_out;
139443 memset(pLeft->zData, 0, pRtree->iNodeSize);
139444 memset(pRight->zData, 0, pRtree->iNodeSize);
139446 rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
139447 if( rc!=SQLITE_OK ){
139448 goto splitnode_out;
139451 /* Ensure both child nodes have node numbers assigned to them by calling
139452 ** nodeWrite(). Node pRight always needs a node number, as it was created
139453 ** by nodeNew() above. But node pLeft sometimes already has a node number.
139454 ** In this case avoid the all to nodeWrite().
139456 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
139457 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
139459 goto splitnode_out;
139462 rightbbox.iRowid = pRight->iNode;
139463 leftbbox.iRowid = pLeft->iNode;
139465 if( pNode->iNode==1 ){
139466 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
139467 if( rc!=SQLITE_OK ){
139468 goto splitnode_out;
139470 }else{
139471 RtreeNode *pParent = pLeft->pParent;
139472 int iCell;
139473 rc = nodeParentIndex(pRtree, pLeft, &iCell);
139474 if( rc==SQLITE_OK ){
139475 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
139476 rc = AdjustTree(pRtree, pParent, &leftbbox);
139478 if( rc!=SQLITE_OK ){
139479 goto splitnode_out;
139482 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
139483 goto splitnode_out;
139486 for(i=0; i<NCELL(pRight); i++){
139487 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
139488 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
139489 if( iRowid==pCell->iRowid ){
139490 newCellIsRight = 1;
139492 if( rc!=SQLITE_OK ){
139493 goto splitnode_out;
139496 if( pNode->iNode==1 ){
139497 for(i=0; i<NCELL(pLeft); i++){
139498 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
139499 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
139500 if( rc!=SQLITE_OK ){
139501 goto splitnode_out;
139504 }else if( newCellIsRight==0 ){
139505 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
139508 if( rc==SQLITE_OK ){
139509 rc = nodeRelease(pRtree, pRight);
139510 pRight = 0;
139512 if( rc==SQLITE_OK ){
139513 rc = nodeRelease(pRtree, pLeft);
139514 pLeft = 0;
139517 splitnode_out:
139518 nodeRelease(pRtree, pRight);
139519 nodeRelease(pRtree, pLeft);
139520 sqlite3_free(aCell);
139521 return rc;
139525 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
139526 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
139527 ** the pLeaf->pParent chain all the way up to the root node.
139529 ** This operation is required when a row is deleted (or updated - an update
139530 ** is implemented as a delete followed by an insert). SQLite provides the
139531 ** rowid of the row to delete, which can be used to find the leaf on which
139532 ** the entry resides (argument pLeaf). Once the leaf is located, this
139533 ** function is called to determine its ancestry.
139535 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
139536 int rc = SQLITE_OK;
139537 RtreeNode *pChild = pLeaf;
139538 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
139539 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
139540 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
139541 rc = sqlite3_step(pRtree->pReadParent);
139542 if( rc==SQLITE_ROW ){
139543 RtreeNode *pTest; /* Used to test for reference loops */
139544 i64 iNode; /* Node number of parent node */
139546 /* Before setting pChild->pParent, test that we are not creating a
139547 ** loop of references (as we would if, say, pChild==pParent). We don't
139548 ** want to do this as it leads to a memory leak when trying to delete
139549 ** the referenced counted node structures.
139551 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
139552 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
139553 if( !pTest ){
139554 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
139557 rc = sqlite3_reset(pRtree->pReadParent);
139558 if( rc==SQLITE_OK ) rc = rc2;
139559 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
139560 pChild = pChild->pParent;
139562 return rc;
139565 static int deleteCell(Rtree *, RtreeNode *, int, int);
139567 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
139568 int rc;
139569 int rc2;
139570 RtreeNode *pParent = 0;
139571 int iCell;
139573 assert( pNode->nRef==1 );
139575 /* Remove the entry in the parent cell. */
139576 rc = nodeParentIndex(pRtree, pNode, &iCell);
139577 if( rc==SQLITE_OK ){
139578 pParent = pNode->pParent;
139579 pNode->pParent = 0;
139580 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
139582 rc2 = nodeRelease(pRtree, pParent);
139583 if( rc==SQLITE_OK ){
139584 rc = rc2;
139586 if( rc!=SQLITE_OK ){
139587 return rc;
139590 /* Remove the xxx_node entry. */
139591 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
139592 sqlite3_step(pRtree->pDeleteNode);
139593 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
139594 return rc;
139597 /* Remove the xxx_parent entry. */
139598 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
139599 sqlite3_step(pRtree->pDeleteParent);
139600 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
139601 return rc;
139604 /* Remove the node from the in-memory hash table and link it into
139605 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
139607 nodeHashDelete(pRtree, pNode);
139608 pNode->iNode = iHeight;
139609 pNode->pNext = pRtree->pDeleted;
139610 pNode->nRef++;
139611 pRtree->pDeleted = pNode;
139613 return SQLITE_OK;
139616 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
139617 RtreeNode *pParent = pNode->pParent;
139618 int rc = SQLITE_OK;
139619 if( pParent ){
139620 int ii;
139621 int nCell = NCELL(pNode);
139622 RtreeCell box; /* Bounding box for pNode */
139623 nodeGetCell(pRtree, pNode, 0, &box);
139624 for(ii=1; ii<nCell; ii++){
139625 RtreeCell cell;
139626 nodeGetCell(pRtree, pNode, ii, &cell);
139627 cellUnion(pRtree, &box, &cell);
139629 box.iRowid = pNode->iNode;
139630 rc = nodeParentIndex(pRtree, pNode, &ii);
139631 if( rc==SQLITE_OK ){
139632 nodeOverwriteCell(pRtree, pParent, &box, ii);
139633 rc = fixBoundingBox(pRtree, pParent);
139636 return rc;
139640 ** Delete the cell at index iCell of node pNode. After removing the
139641 ** cell, adjust the r-tree data structure if required.
139643 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
139644 RtreeNode *pParent;
139645 int rc;
139647 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
139648 return rc;
139651 /* Remove the cell from the node. This call just moves bytes around
139652 ** the in-memory node image, so it cannot fail.
139654 nodeDeleteCell(pRtree, pNode, iCell);
139656 /* If the node is not the tree root and now has less than the minimum
139657 ** number of cells, remove it from the tree. Otherwise, update the
139658 ** cell in the parent node so that it tightly contains the updated
139659 ** node.
139661 pParent = pNode->pParent;
139662 assert( pParent || pNode->iNode==1 );
139663 if( pParent ){
139664 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
139665 rc = removeNode(pRtree, pNode, iHeight);
139666 }else{
139667 rc = fixBoundingBox(pRtree, pNode);
139671 return rc;
139674 static int Reinsert(
139675 Rtree *pRtree,
139676 RtreeNode *pNode,
139677 RtreeCell *pCell,
139678 int iHeight
139680 int *aOrder;
139681 int *aSpare;
139682 RtreeCell *aCell;
139683 RtreeDValue *aDistance;
139684 int nCell;
139685 RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
139686 int iDim;
139687 int ii;
139688 int rc = SQLITE_OK;
139689 int n;
139691 memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
139693 nCell = NCELL(pNode)+1;
139694 n = (nCell+1)&(~1);
139696 /* Allocate the buffers used by this operation. The allocation is
139697 ** relinquished before this function returns.
139699 aCell = (RtreeCell *)sqlite3_malloc(n * (
139700 sizeof(RtreeCell) + /* aCell array */
139701 sizeof(int) + /* aOrder array */
139702 sizeof(int) + /* aSpare array */
139703 sizeof(RtreeDValue) /* aDistance array */
139705 if( !aCell ){
139706 return SQLITE_NOMEM;
139708 aOrder = (int *)&aCell[n];
139709 aSpare = (int *)&aOrder[n];
139710 aDistance = (RtreeDValue *)&aSpare[n];
139712 for(ii=0; ii<nCell; ii++){
139713 if( ii==(nCell-1) ){
139714 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
139715 }else{
139716 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
139718 aOrder[ii] = ii;
139719 for(iDim=0; iDim<pRtree->nDim; iDim++){
139720 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
139721 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
139724 for(iDim=0; iDim<pRtree->nDim; iDim++){
139725 aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
139728 for(ii=0; ii<nCell; ii++){
139729 aDistance[ii] = 0.0;
139730 for(iDim=0; iDim<pRtree->nDim; iDim++){
139731 RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
139732 DCOORD(aCell[ii].aCoord[iDim*2]));
139733 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
139737 SortByDistance(aOrder, nCell, aDistance, aSpare);
139738 nodeZero(pRtree, pNode);
139740 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
139741 RtreeCell *p = &aCell[aOrder[ii]];
139742 nodeInsertCell(pRtree, pNode, p);
139743 if( p->iRowid==pCell->iRowid ){
139744 if( iHeight==0 ){
139745 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
139746 }else{
139747 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
139751 if( rc==SQLITE_OK ){
139752 rc = fixBoundingBox(pRtree, pNode);
139754 for(; rc==SQLITE_OK && ii<nCell; ii++){
139755 /* Find a node to store this cell in. pNode->iNode currently contains
139756 ** the height of the sub-tree headed by the cell.
139758 RtreeNode *pInsert;
139759 RtreeCell *p = &aCell[aOrder[ii]];
139760 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
139761 if( rc==SQLITE_OK ){
139762 int rc2;
139763 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
139764 rc2 = nodeRelease(pRtree, pInsert);
139765 if( rc==SQLITE_OK ){
139766 rc = rc2;
139771 sqlite3_free(aCell);
139772 return rc;
139776 ** Insert cell pCell into node pNode. Node pNode is the head of a
139777 ** subtree iHeight high (leaf nodes have iHeight==0).
139779 static int rtreeInsertCell(
139780 Rtree *pRtree,
139781 RtreeNode *pNode,
139782 RtreeCell *pCell,
139783 int iHeight
139785 int rc = SQLITE_OK;
139786 if( iHeight>0 ){
139787 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
139788 if( pChild ){
139789 nodeRelease(pRtree, pChild->pParent);
139790 nodeReference(pNode);
139791 pChild->pParent = pNode;
139794 if( nodeInsertCell(pRtree, pNode, pCell) ){
139795 #if VARIANT_RSTARTREE_REINSERT
139796 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
139797 rc = SplitNode(pRtree, pNode, pCell, iHeight);
139798 }else{
139799 pRtree->iReinsertHeight = iHeight;
139800 rc = Reinsert(pRtree, pNode, pCell, iHeight);
139802 #else
139803 rc = SplitNode(pRtree, pNode, pCell, iHeight);
139804 #endif
139805 }else{
139806 rc = AdjustTree(pRtree, pNode, pCell);
139807 if( rc==SQLITE_OK ){
139808 if( iHeight==0 ){
139809 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
139810 }else{
139811 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
139815 return rc;
139818 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
139819 int ii;
139820 int rc = SQLITE_OK;
139821 int nCell = NCELL(pNode);
139823 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
139824 RtreeNode *pInsert;
139825 RtreeCell cell;
139826 nodeGetCell(pRtree, pNode, ii, &cell);
139828 /* Find a node to store this cell in. pNode->iNode currently contains
139829 ** the height of the sub-tree headed by the cell.
139831 rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
139832 if( rc==SQLITE_OK ){
139833 int rc2;
139834 rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
139835 rc2 = nodeRelease(pRtree, pInsert);
139836 if( rc==SQLITE_OK ){
139837 rc = rc2;
139841 return rc;
139845 ** Select a currently unused rowid for a new r-tree record.
139847 static int newRowid(Rtree *pRtree, i64 *piRowid){
139848 int rc;
139849 sqlite3_bind_null(pRtree->pWriteRowid, 1);
139850 sqlite3_bind_null(pRtree->pWriteRowid, 2);
139851 sqlite3_step(pRtree->pWriteRowid);
139852 rc = sqlite3_reset(pRtree->pWriteRowid);
139853 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
139854 return rc;
139858 ** Remove the entry with rowid=iDelete from the r-tree structure.
139860 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
139861 int rc; /* Return code */
139862 RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
139863 int iCell; /* Index of iDelete cell in pLeaf */
139864 RtreeNode *pRoot; /* Root node of rtree structure */
139867 /* Obtain a reference to the root node to initialize Rtree.iDepth */
139868 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
139870 /* Obtain a reference to the leaf node that contains the entry
139871 ** about to be deleted.
139873 if( rc==SQLITE_OK ){
139874 rc = findLeafNode(pRtree, iDelete, &pLeaf);
139877 /* Delete the cell in question from the leaf node. */
139878 if( rc==SQLITE_OK ){
139879 int rc2;
139880 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
139881 if( rc==SQLITE_OK ){
139882 rc = deleteCell(pRtree, pLeaf, iCell, 0);
139884 rc2 = nodeRelease(pRtree, pLeaf);
139885 if( rc==SQLITE_OK ){
139886 rc = rc2;
139890 /* Delete the corresponding entry in the <rtree>_rowid table. */
139891 if( rc==SQLITE_OK ){
139892 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
139893 sqlite3_step(pRtree->pDeleteRowid);
139894 rc = sqlite3_reset(pRtree->pDeleteRowid);
139897 /* Check if the root node now has exactly one child. If so, remove
139898 ** it, schedule the contents of the child for reinsertion and
139899 ** reduce the tree height by one.
139901 ** This is equivalent to copying the contents of the child into
139902 ** the root node (the operation that Gutman's paper says to perform
139903 ** in this scenario).
139905 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
139906 int rc2;
139907 RtreeNode *pChild;
139908 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
139909 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
139910 if( rc==SQLITE_OK ){
139911 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
139913 rc2 = nodeRelease(pRtree, pChild);
139914 if( rc==SQLITE_OK ) rc = rc2;
139915 if( rc==SQLITE_OK ){
139916 pRtree->iDepth--;
139917 writeInt16(pRoot->zData, pRtree->iDepth);
139918 pRoot->isDirty = 1;
139922 /* Re-insert the contents of any underfull nodes removed from the tree. */
139923 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
139924 if( rc==SQLITE_OK ){
139925 rc = reinsertNodeContent(pRtree, pLeaf);
139927 pRtree->pDeleted = pLeaf->pNext;
139928 sqlite3_free(pLeaf);
139931 /* Release the reference to the root node. */
139932 if( rc==SQLITE_OK ){
139933 rc = nodeRelease(pRtree, pRoot);
139934 }else{
139935 nodeRelease(pRtree, pRoot);
139938 return rc;
139942 ** Rounding constants for float->double conversion.
139944 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
139945 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
139947 #if !defined(SQLITE_RTREE_INT_ONLY)
139949 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
139950 ** while taking care to round toward negative or positive, respectively.
139952 static RtreeValue rtreeValueDown(sqlite3_value *v){
139953 double d = sqlite3_value_double(v);
139954 float f = (float)d;
139955 if( f>d ){
139956 f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
139958 return f;
139960 static RtreeValue rtreeValueUp(sqlite3_value *v){
139961 double d = sqlite3_value_double(v);
139962 float f = (float)d;
139963 if( f<d ){
139964 f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
139966 return f;
139968 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
139972 ** The xUpdate method for rtree module virtual tables.
139974 static int rtreeUpdate(
139975 sqlite3_vtab *pVtab,
139976 int nData,
139977 sqlite3_value **azData,
139978 sqlite_int64 *pRowid
139980 Rtree *pRtree = (Rtree *)pVtab;
139981 int rc = SQLITE_OK;
139982 RtreeCell cell; /* New cell to insert if nData>1 */
139983 int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
139985 rtreeReference(pRtree);
139986 assert(nData>=1);
139988 /* Constraint handling. A write operation on an r-tree table may return
139989 ** SQLITE_CONSTRAINT for two reasons:
139991 ** 1. A duplicate rowid value, or
139992 ** 2. The supplied data violates the "x2>=x1" constraint.
139994 ** In the first case, if the conflict-handling mode is REPLACE, then
139995 ** the conflicting row can be removed before proceeding. In the second
139996 ** case, SQLITE_CONSTRAINT must be returned regardless of the
139997 ** conflict-handling mode specified by the user.
139999 if( nData>1 ){
140000 int ii;
140002 /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
140003 assert( nData==(pRtree->nDim*2 + 3) );
140004 #ifndef SQLITE_RTREE_INT_ONLY
140005 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
140006 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
140007 cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
140008 cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
140009 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
140010 rc = SQLITE_CONSTRAINT;
140011 goto constraint;
140014 }else
140015 #endif
140017 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
140018 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
140019 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
140020 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
140021 rc = SQLITE_CONSTRAINT;
140022 goto constraint;
140027 /* If a rowid value was supplied, check if it is already present in
140028 ** the table. If so, the constraint has failed. */
140029 if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
140030 cell.iRowid = sqlite3_value_int64(azData[2]);
140031 if( sqlite3_value_type(azData[0])==SQLITE_NULL
140032 || sqlite3_value_int64(azData[0])!=cell.iRowid
140034 int steprc;
140035 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
140036 steprc = sqlite3_step(pRtree->pReadRowid);
140037 rc = sqlite3_reset(pRtree->pReadRowid);
140038 if( SQLITE_ROW==steprc ){
140039 if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
140040 rc = rtreeDeleteRowid(pRtree, cell.iRowid);
140041 }else{
140042 rc = SQLITE_CONSTRAINT;
140043 goto constraint;
140047 bHaveRowid = 1;
140051 /* If azData[0] is not an SQL NULL value, it is the rowid of a
140052 ** record to delete from the r-tree table. The following block does
140053 ** just that.
140055 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
140056 rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
140059 /* If the azData[] array contains more than one element, elements
140060 ** (azData[2]..azData[argc-1]) contain a new record to insert into
140061 ** the r-tree structure.
140063 if( rc==SQLITE_OK && nData>1 ){
140064 /* Insert the new record into the r-tree */
140065 RtreeNode *pLeaf = 0;
140067 /* Figure out the rowid of the new row. */
140068 if( bHaveRowid==0 ){
140069 rc = newRowid(pRtree, &cell.iRowid);
140071 *pRowid = cell.iRowid;
140073 if( rc==SQLITE_OK ){
140074 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
140076 if( rc==SQLITE_OK ){
140077 int rc2;
140078 pRtree->iReinsertHeight = -1;
140079 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
140080 rc2 = nodeRelease(pRtree, pLeaf);
140081 if( rc==SQLITE_OK ){
140082 rc = rc2;
140087 constraint:
140088 rtreeRelease(pRtree);
140089 return rc;
140093 ** The xRename method for rtree module virtual tables.
140095 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
140096 Rtree *pRtree = (Rtree *)pVtab;
140097 int rc = SQLITE_NOMEM;
140098 char *zSql = sqlite3_mprintf(
140099 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
140100 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
140101 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
140102 , pRtree->zDb, pRtree->zName, zNewName
140103 , pRtree->zDb, pRtree->zName, zNewName
140104 , pRtree->zDb, pRtree->zName, zNewName
140106 if( zSql ){
140107 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
140108 sqlite3_free(zSql);
140110 return rc;
140113 static sqlite3_module rtreeModule = {
140114 0, /* iVersion */
140115 rtreeCreate, /* xCreate - create a table */
140116 rtreeConnect, /* xConnect - connect to an existing table */
140117 rtreeBestIndex, /* xBestIndex - Determine search strategy */
140118 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
140119 rtreeDestroy, /* xDestroy - Drop a table */
140120 rtreeOpen, /* xOpen - open a cursor */
140121 rtreeClose, /* xClose - close a cursor */
140122 rtreeFilter, /* xFilter - configure scan constraints */
140123 rtreeNext, /* xNext - advance a cursor */
140124 rtreeEof, /* xEof */
140125 rtreeColumn, /* xColumn - read data */
140126 rtreeRowid, /* xRowid - read data */
140127 rtreeUpdate, /* xUpdate - write data */
140128 0, /* xBegin - begin transaction */
140129 0, /* xSync - sync transaction */
140130 0, /* xCommit - commit transaction */
140131 0, /* xRollback - rollback transaction */
140132 0, /* xFindFunction - function overloading */
140133 rtreeRename, /* xRename - rename the table */
140134 0, /* xSavepoint */
140135 0, /* xRelease */
140136 0 /* xRollbackTo */
140139 static int rtreeSqlInit(
140140 Rtree *pRtree,
140141 sqlite3 *db,
140142 const char *zDb,
140143 const char *zPrefix,
140144 int isCreate
140146 int rc = SQLITE_OK;
140148 #define N_STATEMENT 9
140149 static const char *azSql[N_STATEMENT] = {
140150 /* Read and write the xxx_node table */
140151 "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
140152 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
140153 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
140155 /* Read and write the xxx_rowid table */
140156 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
140157 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
140158 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
140160 /* Read and write the xxx_parent table */
140161 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
140162 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
140163 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
140165 sqlite3_stmt **appStmt[N_STATEMENT];
140166 int i;
140168 pRtree->db = db;
140170 if( isCreate ){
140171 char *zCreate = sqlite3_mprintf(
140172 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
140173 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
140174 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
140175 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
140176 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
140178 if( !zCreate ){
140179 return SQLITE_NOMEM;
140181 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
140182 sqlite3_free(zCreate);
140183 if( rc!=SQLITE_OK ){
140184 return rc;
140188 appStmt[0] = &pRtree->pReadNode;
140189 appStmt[1] = &pRtree->pWriteNode;
140190 appStmt[2] = &pRtree->pDeleteNode;
140191 appStmt[3] = &pRtree->pReadRowid;
140192 appStmt[4] = &pRtree->pWriteRowid;
140193 appStmt[5] = &pRtree->pDeleteRowid;
140194 appStmt[6] = &pRtree->pReadParent;
140195 appStmt[7] = &pRtree->pWriteParent;
140196 appStmt[8] = &pRtree->pDeleteParent;
140198 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
140199 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
140200 if( zSql ){
140201 rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
140202 }else{
140203 rc = SQLITE_NOMEM;
140205 sqlite3_free(zSql);
140208 return rc;
140212 ** The second argument to this function contains the text of an SQL statement
140213 ** that returns a single integer value. The statement is compiled and executed
140214 ** using database connection db. If successful, the integer value returned
140215 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
140216 ** code is returned and the value of *piVal after returning is not defined.
140218 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
140219 int rc = SQLITE_NOMEM;
140220 if( zSql ){
140221 sqlite3_stmt *pStmt = 0;
140222 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
140223 if( rc==SQLITE_OK ){
140224 if( SQLITE_ROW==sqlite3_step(pStmt) ){
140225 *piVal = sqlite3_column_int(pStmt, 0);
140227 rc = sqlite3_finalize(pStmt);
140230 return rc;
140234 ** This function is called from within the xConnect() or xCreate() method to
140235 ** determine the node-size used by the rtree table being created or connected
140236 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
140237 ** Otherwise, an SQLite error code is returned.
140239 ** If this function is being called as part of an xConnect(), then the rtree
140240 ** table already exists. In this case the node-size is determined by inspecting
140241 ** the root node of the tree.
140243 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
140244 ** This ensures that each node is stored on a single database page. If the
140245 ** database page-size is so large that more than RTREE_MAXCELLS entries
140246 ** would fit in a single node, use a smaller node-size.
140248 static int getNodeSize(
140249 sqlite3 *db, /* Database handle */
140250 Rtree *pRtree, /* Rtree handle */
140251 int isCreate, /* True for xCreate, false for xConnect */
140252 char **pzErr /* OUT: Error message, if any */
140254 int rc;
140255 char *zSql;
140256 if( isCreate ){
140257 int iPageSize = 0;
140258 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
140259 rc = getIntFromStmt(db, zSql, &iPageSize);
140260 if( rc==SQLITE_OK ){
140261 pRtree->iNodeSize = iPageSize-64;
140262 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
140263 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
140265 }else{
140266 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
140268 }else{
140269 zSql = sqlite3_mprintf(
140270 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
140271 pRtree->zDb, pRtree->zName
140273 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
140274 if( rc!=SQLITE_OK ){
140275 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
140279 sqlite3_free(zSql);
140280 return rc;
140284 ** This function is the implementation of both the xConnect and xCreate
140285 ** methods of the r-tree virtual table.
140287 ** argv[0] -> module name
140288 ** argv[1] -> database name
140289 ** argv[2] -> table name
140290 ** argv[...] -> column names...
140292 static int rtreeInit(
140293 sqlite3 *db, /* Database connection */
140294 void *pAux, /* One of the RTREE_COORD_* constants */
140295 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
140296 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
140297 char **pzErr, /* OUT: Error message, if any */
140298 int isCreate /* True for xCreate, false for xConnect */
140300 int rc = SQLITE_OK;
140301 Rtree *pRtree;
140302 int nDb; /* Length of string argv[1] */
140303 int nName; /* Length of string argv[2] */
140304 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
140306 const char *aErrMsg[] = {
140307 0, /* 0 */
140308 "Wrong number of columns for an rtree table", /* 1 */
140309 "Too few columns for an rtree table", /* 2 */
140310 "Too many columns for an rtree table" /* 3 */
140313 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
140314 if( aErrMsg[iErr] ){
140315 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
140316 return SQLITE_ERROR;
140319 sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
140321 /* Allocate the sqlite3_vtab structure */
140322 nDb = (int)strlen(argv[1]);
140323 nName = (int)strlen(argv[2]);
140324 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
140325 if( !pRtree ){
140326 return SQLITE_NOMEM;
140328 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
140329 pRtree->nBusy = 1;
140330 pRtree->base.pModule = &rtreeModule;
140331 pRtree->zDb = (char *)&pRtree[1];
140332 pRtree->zName = &pRtree->zDb[nDb+1];
140333 pRtree->nDim = (argc-4)/2;
140334 pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
140335 pRtree->eCoordType = eCoordType;
140336 memcpy(pRtree->zDb, argv[1], nDb);
140337 memcpy(pRtree->zName, argv[2], nName);
140339 /* Figure out the node size to use. */
140340 rc = getNodeSize(db, pRtree, isCreate, pzErr);
140342 /* Create/Connect to the underlying relational database schema. If
140343 ** that is successful, call sqlite3_declare_vtab() to configure
140344 ** the r-tree table schema.
140346 if( rc==SQLITE_OK ){
140347 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
140348 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
140349 }else{
140350 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
140351 char *zTmp;
140352 int ii;
140353 for(ii=4; zSql && ii<argc; ii++){
140354 zTmp = zSql;
140355 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
140356 sqlite3_free(zTmp);
140358 if( zSql ){
140359 zTmp = zSql;
140360 zSql = sqlite3_mprintf("%s);", zTmp);
140361 sqlite3_free(zTmp);
140363 if( !zSql ){
140364 rc = SQLITE_NOMEM;
140365 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
140366 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
140368 sqlite3_free(zSql);
140372 if( rc==SQLITE_OK ){
140373 *ppVtab = (sqlite3_vtab *)pRtree;
140374 }else{
140375 rtreeRelease(pRtree);
140377 return rc;
140382 ** Implementation of a scalar function that decodes r-tree nodes to
140383 ** human readable strings. This can be used for debugging and analysis.
140385 ** The scalar function takes two arguments, a blob of data containing
140386 ** an r-tree node, and the number of dimensions the r-tree indexes.
140387 ** For a two-dimensional r-tree structure called "rt", to deserialize
140388 ** all nodes, a statement like:
140390 ** SELECT rtreenode(2, data) FROM rt_node;
140392 ** The human readable string takes the form of a Tcl list with one
140393 ** entry for each cell in the r-tree node. Each entry is itself a
140394 ** list, containing the 8-byte rowid/pageno followed by the
140395 ** <num-dimension>*2 coordinates.
140397 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
140398 char *zText = 0;
140399 RtreeNode node;
140400 Rtree tree;
140401 int ii;
140403 UNUSED_PARAMETER(nArg);
140404 memset(&node, 0, sizeof(RtreeNode));
140405 memset(&tree, 0, sizeof(Rtree));
140406 tree.nDim = sqlite3_value_int(apArg[0]);
140407 tree.nBytesPerCell = 8 + 8 * tree.nDim;
140408 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
140410 for(ii=0; ii<NCELL(&node); ii++){
140411 char zCell[512];
140412 int nCell = 0;
140413 RtreeCell cell;
140414 int jj;
140416 nodeGetCell(&tree, &node, ii, &cell);
140417 sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
140418 nCell = (int)strlen(zCell);
140419 for(jj=0; jj<tree.nDim*2; jj++){
140420 #ifndef SQLITE_RTREE_INT_ONLY
140421 sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
140422 (double)cell.aCoord[jj].f);
140423 #else
140424 sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
140425 cell.aCoord[jj].i);
140426 #endif
140427 nCell = (int)strlen(zCell);
140430 if( zText ){
140431 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
140432 sqlite3_free(zText);
140433 zText = zTextNew;
140434 }else{
140435 zText = sqlite3_mprintf("{%s}", zCell);
140439 sqlite3_result_text(ctx, zText, -1, sqlite3_free);
140442 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
140443 UNUSED_PARAMETER(nArg);
140444 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
140445 || sqlite3_value_bytes(apArg[0])<2
140447 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
140448 }else{
140449 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
140450 sqlite3_result_int(ctx, readInt16(zBlob));
140455 ** Register the r-tree module with database handle db. This creates the
140456 ** virtual table module "rtree" and the debugging/analysis scalar
140457 ** function "rtreenode".
140459 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
140460 const int utf8 = SQLITE_UTF8;
140461 int rc;
140463 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
140464 if( rc==SQLITE_OK ){
140465 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
140467 if( rc==SQLITE_OK ){
140468 #ifdef SQLITE_RTREE_INT_ONLY
140469 void *c = (void *)RTREE_COORD_INT32;
140470 #else
140471 void *c = (void *)RTREE_COORD_REAL32;
140472 #endif
140473 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
140475 if( rc==SQLITE_OK ){
140476 void *c = (void *)RTREE_COORD_INT32;
140477 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
140480 return rc;
140484 ** A version of sqlite3_free() that can be used as a callback. This is used
140485 ** in two places - as the destructor for the blob value returned by the
140486 ** invocation of a geometry function, and as the destructor for the geometry
140487 ** functions themselves.
140489 static void doSqlite3Free(void *p){
140490 sqlite3_free(p);
140494 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
140495 ** scalar user function. This C function is the callback used for all such
140496 ** registered SQL functions.
140498 ** The scalar user functions return a blob that is interpreted by r-tree
140499 ** table MATCH operators.
140501 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
140502 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
140503 RtreeMatchArg *pBlob;
140504 int nBlob;
140506 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
140507 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
140508 if( !pBlob ){
140509 sqlite3_result_error_nomem(ctx);
140510 }else{
140511 int i;
140512 pBlob->magic = RTREE_GEOMETRY_MAGIC;
140513 pBlob->xGeom = pGeomCtx->xGeom;
140514 pBlob->pContext = pGeomCtx->pContext;
140515 pBlob->nParam = nArg;
140516 for(i=0; i<nArg; i++){
140517 #ifdef SQLITE_RTREE_INT_ONLY
140518 pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
140519 #else
140520 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
140521 #endif
140523 sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
140528 ** Register a new geometry function for use with the r-tree MATCH operator.
140530 SQLITE_API int sqlite3_rtree_geometry_callback(
140531 sqlite3 *db,
140532 const char *zGeom,
140533 int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
140534 void *pContext
140536 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
140538 /* Allocate and populate the context object. */
140539 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
140540 if( !pGeomCtx ) return SQLITE_NOMEM;
140541 pGeomCtx->xGeom = xGeom;
140542 pGeomCtx->pContext = pContext;
140544 /* Create the new user-function. Register a destructor function to delete
140545 ** the context object when it is no longer required. */
140546 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
140547 (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
140551 #if !SQLITE_CORE
140552 #ifdef _WIN32
140553 __declspec(dllexport)
140554 #endif
140555 SQLITE_API int sqlite3_rtree_init(
140556 sqlite3 *db,
140557 char **pzErrMsg,
140558 const sqlite3_api_routines *pApi
140560 SQLITE_EXTENSION_INIT2(pApi)
140561 return sqlite3RtreeInit(db);
140563 #endif
140565 #endif
140567 /************** End of rtree.c ***********************************************/
140568 /************** Begin file icu.c *********************************************/
140570 ** 2007 May 6
140572 ** The author disclaims copyright to this source code. In place of
140573 ** a legal notice, here is a blessing:
140575 ** May you do good and not evil.
140576 ** May you find forgiveness for yourself and forgive others.
140577 ** May you share freely, never taking more than you give.
140579 *************************************************************************
140580 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
140582 ** This file implements an integration between the ICU library
140583 ** ("International Components for Unicode", an open-source library
140584 ** for handling unicode data) and SQLite. The integration uses
140585 ** ICU to provide the following to SQLite:
140587 ** * An implementation of the SQL regexp() function (and hence REGEXP
140588 ** operator) using the ICU uregex_XX() APIs.
140590 ** * Implementations of the SQL scalar upper() and lower() functions
140591 ** for case mapping.
140593 ** * Integration of ICU and SQLite collation sequences.
140595 ** * An implementation of the LIKE operator that uses ICU to
140596 ** provide case-independent matching.
140599 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
140601 /* Include ICU headers */
140602 #include <unicode/utypes.h>
140603 #include <unicode/uregex.h>
140604 #include <unicode/ustring.h>
140605 #include <unicode/ucol.h>
140607 /* #include <assert.h> */
140609 #ifndef SQLITE_CORE
140610 SQLITE_EXTENSION_INIT1
140611 #else
140612 #endif
140615 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
140616 ** operator.
140618 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
140619 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
140620 #endif
140623 ** Version of sqlite3_free() that is always a function, never a macro.
140625 static void xFree(void *p){
140626 sqlite3_free(p);
140630 ** Compare two UTF-8 strings for equality where the first string is
140631 ** a "LIKE" expression. Return true (1) if they are the same and
140632 ** false (0) if they are different.
140634 static int icuLikeCompare(
140635 const uint8_t *zPattern, /* LIKE pattern */
140636 const uint8_t *zString, /* The UTF-8 string to compare against */
140637 const UChar32 uEsc /* The escape character */
140639 static const int MATCH_ONE = (UChar32)'_';
140640 static const int MATCH_ALL = (UChar32)'%';
140642 int iPattern = 0; /* Current byte index in zPattern */
140643 int iString = 0; /* Current byte index in zString */
140645 int prevEscape = 0; /* True if the previous character was uEsc */
140647 while( zPattern[iPattern]!=0 ){
140649 /* Read (and consume) the next character from the input pattern. */
140650 UChar32 uPattern;
140651 U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
140652 assert(uPattern!=0);
140654 /* There are now 4 possibilities:
140656 ** 1. uPattern is an unescaped match-all character "%",
140657 ** 2. uPattern is an unescaped match-one character "_",
140658 ** 3. uPattern is an unescaped escape character, or
140659 ** 4. uPattern is to be handled as an ordinary character
140661 if( !prevEscape && uPattern==MATCH_ALL ){
140662 /* Case 1. */
140663 uint8_t c;
140665 /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
140666 ** MATCH_ALL. For each MATCH_ONE, skip one character in the
140667 ** test string.
140669 while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
140670 if( c==MATCH_ONE ){
140671 if( zString[iString]==0 ) return 0;
140672 U8_FWD_1_UNSAFE(zString, iString);
140674 iPattern++;
140677 if( zPattern[iPattern]==0 ) return 1;
140679 while( zString[iString] ){
140680 if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
140681 return 1;
140683 U8_FWD_1_UNSAFE(zString, iString);
140685 return 0;
140687 }else if( !prevEscape && uPattern==MATCH_ONE ){
140688 /* Case 2. */
140689 if( zString[iString]==0 ) return 0;
140690 U8_FWD_1_UNSAFE(zString, iString);
140692 }else if( !prevEscape && uPattern==uEsc){
140693 /* Case 3. */
140694 prevEscape = 1;
140696 }else{
140697 /* Case 4. */
140698 UChar32 uString;
140699 U8_NEXT_UNSAFE(zString, iString, uString);
140700 uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
140701 uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
140702 if( uString!=uPattern ){
140703 return 0;
140705 prevEscape = 0;
140709 return zString[iString]==0;
140713 ** Implementation of the like() SQL function. This function implements
140714 ** the build-in LIKE operator. The first argument to the function is the
140715 ** pattern and the second argument is the string. So, the SQL statements:
140717 ** A LIKE B
140719 ** is implemented as like(B, A). If there is an escape character E,
140721 ** A LIKE B ESCAPE E
140723 ** is mapped to like(B, A, E).
140725 static void icuLikeFunc(
140726 sqlite3_context *context,
140727 int argc,
140728 sqlite3_value **argv
140730 const unsigned char *zA = sqlite3_value_text(argv[0]);
140731 const unsigned char *zB = sqlite3_value_text(argv[1]);
140732 UChar32 uEsc = 0;
140734 /* Limit the length of the LIKE or GLOB pattern to avoid problems
140735 ** of deep recursion and N*N behavior in patternCompare().
140737 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
140738 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
140739 return;
140743 if( argc==3 ){
140744 /* The escape character string must consist of a single UTF-8 character.
140745 ** Otherwise, return an error.
140747 int nE= sqlite3_value_bytes(argv[2]);
140748 const unsigned char *zE = sqlite3_value_text(argv[2]);
140749 int i = 0;
140750 if( zE==0 ) return;
140751 U8_NEXT(zE, i, nE, uEsc);
140752 if( i!=nE){
140753 sqlite3_result_error(context,
140754 "ESCAPE expression must be a single character", -1);
140755 return;
140759 if( zA && zB ){
140760 sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
140765 ** This function is called when an ICU function called from within
140766 ** the implementation of an SQL scalar function returns an error.
140768 ** The scalar function context passed as the first argument is
140769 ** loaded with an error message based on the following two args.
140771 static void icuFunctionError(
140772 sqlite3_context *pCtx, /* SQLite scalar function context */
140773 const char *zName, /* Name of ICU function that failed */
140774 UErrorCode e /* Error code returned by ICU function */
140776 char zBuf[128];
140777 sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
140778 zBuf[127] = '\0';
140779 sqlite3_result_error(pCtx, zBuf, -1);
140783 ** Function to delete compiled regexp objects. Registered as
140784 ** a destructor function with sqlite3_set_auxdata().
140786 static void icuRegexpDelete(void *p){
140787 URegularExpression *pExpr = (URegularExpression *)p;
140788 uregex_close(pExpr);
140792 ** Implementation of SQLite REGEXP operator. This scalar function takes
140793 ** two arguments. The first is a regular expression pattern to compile
140794 ** the second is a string to match against that pattern. If either
140795 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
140796 ** is 1 if the string matches the pattern, or 0 otherwise.
140798 ** SQLite maps the regexp() function to the regexp() operator such
140799 ** that the following two are equivalent:
140801 ** zString REGEXP zPattern
140802 ** regexp(zPattern, zString)
140804 ** Uses the following ICU regexp APIs:
140806 ** uregex_open()
140807 ** uregex_matches()
140808 ** uregex_close()
140810 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
140811 UErrorCode status = U_ZERO_ERROR;
140812 URegularExpression *pExpr;
140813 UBool res;
140814 const UChar *zString = sqlite3_value_text16(apArg[1]);
140816 (void)nArg; /* Unused parameter */
140818 /* If the left hand side of the regexp operator is NULL,
140819 ** then the result is also NULL.
140821 if( !zString ){
140822 return;
140825 pExpr = sqlite3_get_auxdata(p, 0);
140826 if( !pExpr ){
140827 const UChar *zPattern = sqlite3_value_text16(apArg[0]);
140828 if( !zPattern ){
140829 return;
140831 pExpr = uregex_open(zPattern, -1, 0, 0, &status);
140833 if( U_SUCCESS(status) ){
140834 sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
140835 }else{
140836 assert(!pExpr);
140837 icuFunctionError(p, "uregex_open", status);
140838 return;
140842 /* Configure the text that the regular expression operates on. */
140843 uregex_setText(pExpr, zString, -1, &status);
140844 if( !U_SUCCESS(status) ){
140845 icuFunctionError(p, "uregex_setText", status);
140846 return;
140849 /* Attempt the match */
140850 res = uregex_matches(pExpr, 0, &status);
140851 if( !U_SUCCESS(status) ){
140852 icuFunctionError(p, "uregex_matches", status);
140853 return;
140856 /* Set the text that the regular expression operates on to a NULL
140857 ** pointer. This is not really necessary, but it is tidier than
140858 ** leaving the regular expression object configured with an invalid
140859 ** pointer after this function returns.
140861 uregex_setText(pExpr, 0, 0, &status);
140863 /* Return 1 or 0. */
140864 sqlite3_result_int(p, res ? 1 : 0);
140868 ** Implementations of scalar functions for case mapping - upper() and
140869 ** lower(). Function upper() converts its input to upper-case (ABC).
140870 ** Function lower() converts to lower-case (abc).
140872 ** ICU provides two types of case mapping, "general" case mapping and
140873 ** "language specific". Refer to ICU documentation for the differences
140874 ** between the two.
140876 ** To utilise "general" case mapping, the upper() or lower() scalar
140877 ** functions are invoked with one argument:
140879 ** upper('ABC') -> 'abc'
140880 ** lower('abc') -> 'ABC'
140882 ** To access ICU "language specific" case mapping, upper() or lower()
140883 ** should be invoked with two arguments. The second argument is the name
140884 ** of the locale to use. Passing an empty string ("") or SQL NULL value
140885 ** as the second argument is the same as invoking the 1 argument version
140886 ** of upper() or lower().
140888 ** lower('I', 'en_us') -> 'i'
140889 ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
140891 ** http://www.icu-project.org/userguide/posix.html#case_mappings
140893 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
140894 const UChar *zInput;
140895 UChar *zOutput;
140896 int nInput;
140897 int nOutput;
140899 UErrorCode status = U_ZERO_ERROR;
140900 const char *zLocale = 0;
140902 assert(nArg==1 || nArg==2);
140903 if( nArg==2 ){
140904 zLocale = (const char *)sqlite3_value_text(apArg[1]);
140907 zInput = sqlite3_value_text16(apArg[0]);
140908 if( !zInput ){
140909 return;
140911 nInput = sqlite3_value_bytes16(apArg[0]);
140913 nOutput = nInput * 2 + 2;
140914 zOutput = sqlite3_malloc(nOutput);
140915 if( !zOutput ){
140916 return;
140919 if( sqlite3_user_data(p) ){
140920 u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
140921 }else{
140922 u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
140925 if( !U_SUCCESS(status) ){
140926 icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
140927 return;
140930 sqlite3_result_text16(p, zOutput, -1, xFree);
140934 ** Collation sequence destructor function. The pCtx argument points to
140935 ** a UCollator structure previously allocated using ucol_open().
140937 static void icuCollationDel(void *pCtx){
140938 UCollator *p = (UCollator *)pCtx;
140939 ucol_close(p);
140943 ** Collation sequence comparison function. The pCtx argument points to
140944 ** a UCollator structure previously allocated using ucol_open().
140946 static int icuCollationColl(
140947 void *pCtx,
140948 int nLeft,
140949 const void *zLeft,
140950 int nRight,
140951 const void *zRight
140953 UCollationResult res;
140954 UCollator *p = (UCollator *)pCtx;
140955 res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
140956 switch( res ){
140957 case UCOL_LESS: return -1;
140958 case UCOL_GREATER: return +1;
140959 case UCOL_EQUAL: return 0;
140961 assert(!"Unexpected return value from ucol_strcoll()");
140962 return 0;
140966 ** Implementation of the scalar function icu_load_collation().
140968 ** This scalar function is used to add ICU collation based collation
140969 ** types to an SQLite database connection. It is intended to be called
140970 ** as follows:
140972 ** SELECT icu_load_collation(<locale>, <collation-name>);
140974 ** Where <locale> is a string containing an ICU locale identifier (i.e.
140975 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
140976 ** collation sequence to create.
140978 static void icuLoadCollation(
140979 sqlite3_context *p,
140980 int nArg,
140981 sqlite3_value **apArg
140983 sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
140984 UErrorCode status = U_ZERO_ERROR;
140985 const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
140986 const char *zName; /* SQL Collation sequence name (eg. "japanese") */
140987 UCollator *pUCollator; /* ICU library collation object */
140988 int rc; /* Return code from sqlite3_create_collation_x() */
140990 assert(nArg==2);
140991 zLocale = (const char *)sqlite3_value_text(apArg[0]);
140992 zName = (const char *)sqlite3_value_text(apArg[1]);
140994 if( !zLocale || !zName ){
140995 return;
140998 pUCollator = ucol_open(zLocale, &status);
140999 if( !U_SUCCESS(status) ){
141000 icuFunctionError(p, "ucol_open", status);
141001 return;
141003 assert(p);
141005 rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
141006 icuCollationColl, icuCollationDel
141008 if( rc!=SQLITE_OK ){
141009 ucol_close(pUCollator);
141010 sqlite3_result_error(p, "Error registering collation function", -1);
141015 ** Register the ICU extension functions with database db.
141017 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
141018 struct IcuScalar {
141019 const char *zName; /* Function name */
141020 int nArg; /* Number of arguments */
141021 int enc; /* Optimal text encoding */
141022 void *pContext; /* sqlite3_user_data() context */
141023 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
141024 } scalars[] = {
141025 {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
141027 {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
141028 {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
141029 {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
141030 {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
141032 {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
141033 {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
141034 {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
141035 {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
141037 {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
141038 {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
141040 {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
141043 int rc = SQLITE_OK;
141044 int i;
141046 for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
141047 struct IcuScalar *p = &scalars[i];
141048 rc = sqlite3_create_function(
141049 db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
141053 return rc;
141056 #if !SQLITE_CORE
141057 #ifdef _WIN32
141058 __declspec(dllexport)
141059 #endif
141060 SQLITE_API int sqlite3_icu_init(
141061 sqlite3 *db,
141062 char **pzErrMsg,
141063 const sqlite3_api_routines *pApi
141065 SQLITE_EXTENSION_INIT2(pApi)
141066 return sqlite3IcuInit(db);
141068 #endif
141070 #endif
141072 /************** End of icu.c *************************************************/
141073 /************** Begin file fts3_icu.c ****************************************/
141075 ** 2007 June 22
141077 ** The author disclaims copyright to this source code. In place of
141078 ** a legal notice, here is a blessing:
141080 ** May you do good and not evil.
141081 ** May you find forgiveness for yourself and forgive others.
141082 ** May you share freely, never taking more than you give.
141084 *************************************************************************
141085 ** This file implements a tokenizer for fts3 based on the ICU library.
141087 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141088 #ifdef SQLITE_ENABLE_ICU
141090 /* #include <assert.h> */
141091 /* #include <string.h> */
141093 #include <unicode/ubrk.h>
141094 /* #include <unicode/ucol.h> */
141095 /* #include <unicode/ustring.h> */
141096 #include <unicode/utf16.h>
141098 typedef struct IcuTokenizer IcuTokenizer;
141099 typedef struct IcuCursor IcuCursor;
141101 struct IcuTokenizer {
141102 sqlite3_tokenizer base;
141103 char *zLocale;
141106 struct IcuCursor {
141107 sqlite3_tokenizer_cursor base;
141109 UBreakIterator *pIter; /* ICU break-iterator object */
141110 int nChar; /* Number of UChar elements in pInput */
141111 UChar *aChar; /* Copy of input using utf-16 encoding */
141112 int *aOffset; /* Offsets of each character in utf-8 input */
141114 int nBuffer;
141115 char *zBuffer;
141117 int iToken;
141121 ** Create a new tokenizer instance.
141123 static int icuCreate(
141124 int argc, /* Number of entries in argv[] */
141125 const char * const *argv, /* Tokenizer creation arguments */
141126 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
141128 IcuTokenizer *p;
141129 int n = 0;
141131 if( argc>0 ){
141132 n = strlen(argv[0])+1;
141134 p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
141135 if( !p ){
141136 return SQLITE_NOMEM;
141138 memset(p, 0, sizeof(IcuTokenizer));
141140 if( n ){
141141 p->zLocale = (char *)&p[1];
141142 memcpy(p->zLocale, argv[0], n);
141145 *ppTokenizer = (sqlite3_tokenizer *)p;
141147 return SQLITE_OK;
141151 ** Destroy a tokenizer
141153 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
141154 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
141155 sqlite3_free(p);
141156 return SQLITE_OK;
141160 ** Prepare to begin tokenizing a particular string. The input
141161 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
141162 ** used to incrementally tokenize this string is returned in
141163 ** *ppCursor.
141165 static int icuOpen(
141166 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
141167 const char *zInput, /* Input string */
141168 int nInput, /* Length of zInput in bytes */
141169 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
141171 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
141172 IcuCursor *pCsr;
141174 const int32_t opt = U_FOLD_CASE_DEFAULT;
141175 UErrorCode status = U_ZERO_ERROR;
141176 int nChar;
141178 UChar32 c;
141179 int iInput = 0;
141180 int iOut = 0;
141182 *ppCursor = 0;
141184 if( zInput==0 ){
141185 nInput = 0;
141186 zInput = "";
141187 }else if( nInput<0 ){
141188 nInput = strlen(zInput);
141190 nChar = nInput+1;
141191 pCsr = (IcuCursor *)sqlite3_malloc(
141192 sizeof(IcuCursor) + /* IcuCursor */
141193 ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
141194 (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
141196 if( !pCsr ){
141197 return SQLITE_NOMEM;
141199 memset(pCsr, 0, sizeof(IcuCursor));
141200 pCsr->aChar = (UChar *)&pCsr[1];
141201 pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
141203 pCsr->aOffset[iOut] = iInput;
141204 U8_NEXT(zInput, iInput, nInput, c);
141205 while( c>0 ){
141206 int isError = 0;
141207 c = u_foldCase(c, opt);
141208 U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
141209 if( isError ){
141210 sqlite3_free(pCsr);
141211 return SQLITE_ERROR;
141213 pCsr->aOffset[iOut] = iInput;
141215 if( iInput<nInput ){
141216 U8_NEXT(zInput, iInput, nInput, c);
141217 }else{
141218 c = 0;
141222 pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
141223 if( !U_SUCCESS(status) ){
141224 sqlite3_free(pCsr);
141225 return SQLITE_ERROR;
141227 pCsr->nChar = iOut;
141229 ubrk_first(pCsr->pIter);
141230 *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
141231 return SQLITE_OK;
141235 ** Close a tokenization cursor previously opened by a call to icuOpen().
141237 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
141238 IcuCursor *pCsr = (IcuCursor *)pCursor;
141239 ubrk_close(pCsr->pIter);
141240 sqlite3_free(pCsr->zBuffer);
141241 sqlite3_free(pCsr);
141242 return SQLITE_OK;
141246 ** Extract the next token from a tokenization cursor.
141248 static int icuNext(
141249 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
141250 const char **ppToken, /* OUT: *ppToken is the token text */
141251 int *pnBytes, /* OUT: Number of bytes in token */
141252 int *piStartOffset, /* OUT: Starting offset of token */
141253 int *piEndOffset, /* OUT: Ending offset of token */
141254 int *piPosition /* OUT: Position integer of token */
141256 IcuCursor *pCsr = (IcuCursor *)pCursor;
141258 int iStart = 0;
141259 int iEnd = 0;
141260 int nByte = 0;
141262 while( iStart==iEnd ){
141263 UChar32 c;
141265 iStart = ubrk_current(pCsr->pIter);
141266 iEnd = ubrk_next(pCsr->pIter);
141267 if( iEnd==UBRK_DONE ){
141268 return SQLITE_DONE;
141271 while( iStart<iEnd ){
141272 int iWhite = iStart;
141273 U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
141274 if( u_isspace(c) ){
141275 iStart = iWhite;
141276 }else{
141277 break;
141280 assert(iStart<=iEnd);
141284 UErrorCode status = U_ZERO_ERROR;
141285 if( nByte ){
141286 char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
141287 if( !zNew ){
141288 return SQLITE_NOMEM;
141290 pCsr->zBuffer = zNew;
141291 pCsr->nBuffer = nByte;
141294 u_strToUTF8(
141295 pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
141296 &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
141297 &status /* Output success/failure */
141299 } while( nByte>pCsr->nBuffer );
141301 *ppToken = pCsr->zBuffer;
141302 *pnBytes = nByte;
141303 *piStartOffset = pCsr->aOffset[iStart];
141304 *piEndOffset = pCsr->aOffset[iEnd];
141305 *piPosition = pCsr->iToken++;
141307 return SQLITE_OK;
141311 ** The set of routines that implement the simple tokenizer
141313 static const sqlite3_tokenizer_module icuTokenizerModule = {
141314 0, /* iVersion */
141315 icuCreate, /* xCreate */
141316 icuDestroy, /* xCreate */
141317 icuOpen, /* xOpen */
141318 icuClose, /* xClose */
141319 icuNext, /* xNext */
141323 ** Set *ppModule to point at the implementation of the ICU tokenizer.
141325 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
141326 sqlite3_tokenizer_module const**ppModule
141328 *ppModule = &icuTokenizerModule;
141331 #endif /* defined(SQLITE_ENABLE_ICU) */
141332 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141334 /************** End of fts3_icu.c ********************************************/